diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..ddd699c3568b05d28e5f28ab86ef709b5e854e5a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +web/client/node_modules/esbuild-windows-64/esbuild.exe filter=lfs diff=lfs merge=lfs -text +web/node_modules/@esbuild/win32-x64/esbuild.exe filter=lfs diff=lfs merge=lfs -text +web/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f303e86e4d1fd108ead04ee3a2d2433bf37296e1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,36 @@ +FROM python:3.8 + +# Install Node.js and npm +RUN apt-get update && apt-get install -y curl && \ + curl -sL https://deb.nodesource.com/setup_16.x | bash - && \ + apt-get install -y nodejs \ + npm + +RUN apt-get update && apt-get install -y rsync +RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y + +RUN export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 + +# Set the working directory to /app +WORKDIR /app + +# Copy the requirements file into the container +COPY requirements.txt . + +# Install any needed packages specified in requirements.txt +RUN pip install --no-cache-dir -r requirements.txt + +# copy /web folder and install client's dependencies +COPY ./web /app +WORKDIR /app +RUN npm run install:client +RUN npm run build-deploy:client + +# Expose port 8000 for the Django server +EXPOSE 8000 + +# Start the server +CMD ["python", "server/manage.py", "runserver", "0.0.0.0:8000"] + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f25ff6daf41d72b7317d59f915348c3fba0205e6 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +opencv-python==4.6.0.66 +keras==2.9.0 +keras-tuner==1.1.3 +scikit-learn==1.1.2 +numpy==1.23.3 +panda==1.4.3 +matplotlib==3.6.0 +seaborn==0.12.0 +yellowbrick==1.5 +Django==4.1.2 +djangorestframework==3.14.0 +django-cors-headers==3.13.0 +django-extensions==3.2.1 +protobuf==3.20.* diff --git a/web/README.md b/web/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d16d271de7bafee30c484ec300463d84f2e715a2 --- /dev/null +++ b/web/README.md @@ -0,0 +1,40 @@ +

Website for Models Demonstration

+ +Dependencies install in this section do not contain other machine learning packages, they just contain enough packages to run the website. + +#### Setting Up Environment + +``` + Python 3.8.13 + Node 17.8.0 + NPM 8.5.5 + OS: Linux or MacOS +``` + +Installation + +1. Clone the repo and change directory to that folder _(skip this part if it is already cloned)_ + + ```sh + git clone https://github.com/NgoQuocBao1010/Exercise-Correction.git + ``` + +1. Change directory to _./web_ folder + + ```bash + cd web + ``` + +1. Install all dependencies for client and server _(skip this part if they are already installed)_ + + ```bash + npm run install:all + ``` + +1. Start website - Run on http://127.0.0.1:8000/ + + ```bash + npm run start:website + ``` + +1. Look through [here](./package.json) for other commands to run dev server. diff --git a/web/client/.env.local b/web/client/.env.local new file mode 100644 index 0000000000000000000000000000000000000000..bf645b73d5e3e62bc0e818a119f66f5f105abec9 --- /dev/null +++ b/web/client/.env.local @@ -0,0 +1 @@ +VITE_BASE_URL=http://127.0.0.1 diff --git a/web/client/README.md b/web/client/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c12e12e6f88b7279764f6df0c310b73836feae03 --- /dev/null +++ b/web/client/README.md @@ -0,0 +1,35 @@ +# exercise-correction + +This template should help get you started developing with Vue 3 in Vite. + +## Recommended IDE Setup + +[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin). + +## Customize configuration + +See [Vite Configuration Reference](https://vitejs.dev/config/). + +## Project Setup + +```sh +npm install +``` + +### Compile and Hot-Reload for Development + +```sh +npm run dev +``` + +### Compile and Minify for Production + +```sh +npm run build +``` + +### Run Unit Tests with [Vitest](https://vitest.dev/) + +```sh +npm run test:unit +``` diff --git a/web/client/dist/favicon.ico b/web/client/dist/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..df36fcfb72584e00488330b560ebcf34a41c64c2 Binary files /dev/null and b/web/client/dist/favicon.ico differ diff --git a/web/client/dist/index.html b/web/client/dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6a86d773eec4a26dbb4e2c83b1859d2dff3157e8 --- /dev/null +++ b/web/client/dist/index.html @@ -0,0 +1,22 @@ + + + + + + + + Exercise Correction + + + + +
+ + + diff --git a/web/client/dist/static/assets/js/Home-338d7092.js b/web/client/dist/static/assets/js/Home-338d7092.js new file mode 100644 index 0000000000000000000000000000000000000000..3b0180f795ffcc665d82dc1e440261fa4f31814f --- /dev/null +++ b/web/client/dist/static/assets/js/Home-338d7092.js @@ -0,0 +1 @@ +import{_,r as d,o as n,c as i,a,w as c,p as l,b as p,d as e}from"./index-02ab79b9.js";const r={},s=o=>(l("data-v-63b73dd0"),o=o(),p(),o),u={class:"container"},f=s(()=>e("i",{class:"fa-solid fa-video"},null,-1)),m=s(()=>e("p",{class:"box__description"},"Real Time",-1)),h=s(()=>e("i",{class:"fa-solid fa-upload"},null,-1)),x=s(()=>e("p",{class:"box__description"},"Video Upload",-1));function b(o,v){const t=d("RouterLink");return n(),i("div",u,[a(t,{to:"#",class:"box"},{default:c(()=>[f,m]),_:1}),a(t,{to:{name:"VideoStreaming"},class:"box"},{default:c(()=>[h,x]),_:1})])}const I=_(r,[["render",b],["__scopeId","data-v-63b73dd0"]]);export{I as default}; diff --git a/web/client/dist/static/assets/js/VideoStreaming-c81ea837.js b/web/client/dist/static/assets/js/VideoStreaming-c81ea837.js new file mode 100644 index 0000000000000000000000000000000000000000..27adc8abd9513682e861f7048bf38952688eea0b --- /dev/null +++ b/web/client/dist/static/assets/js/VideoStreaming-c81ea837.js @@ -0,0 +1,6 @@ +import{_ as z,e as v,f as pe,g as st,o as _,c as w,F as D,h as F,t as O,d as y,n as I,i as ot,p as K,b as X,j as it,k as B,l as oe,m as ie,K as we,a as ae,q as Se,v as ge}from"./index-02ab79b9.js";function Fe(e,t){return function(){return e.apply(t,arguments)}}const{toString:at}=Object.prototype,{getPrototypeOf:he}=Object,G=(e=>t=>{const r=at.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),x=e=>(e=e.toLowerCase(),t=>G(t)===e),Q=e=>t=>typeof t===e,{isArray:U}=Array,$=Q("undefined");function ct(e){return e!==null&&!$(e)&&e.constructor!==null&&!$(e.constructor)&&T(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Be=x("ArrayBuffer");function lt(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Be(e.buffer),t}const ut=Q("string"),T=Q("function"),Le=Q("number"),Z=e=>e!==null&&typeof e=="object",dt=e=>e===!0||e===!1,M=e=>{if(G(e)!=="object")return!1;const t=he(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},ft=x("Date"),pt=x("File"),ht=x("Blob"),mt=x("FileList"),yt=e=>Z(e)&&T(e.pipe),_t=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||T(e.append)&&((t=G(e))==="formdata"||t==="object"&&T(e.toString)&&e.toString()==="[object FormData]"))},bt=x("URLSearchParams"),Et=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function H(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,s;if(typeof e!="object"&&(e=[e]),U(e))for(n=0,s=e.length;n0;)if(s=r[n],t===s.toLowerCase())return s;return null}const je=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),Ie=e=>!$(e)&&e!==je;function ce(){const{caseless:e}=Ie(this)&&this||{},t={},r=(n,s)=>{const o=e&&Ue(t,s)||s;M(t[o])&&M(n)?t[o]=ce(t[o],n):M(n)?t[o]=ce({},n):U(n)?t[o]=n.slice():t[o]=n};for(let n=0,s=arguments.length;n(H(t,(s,o)=>{r&&T(s)?e[o]=Fe(s,r):e[o]=s},{allOwnKeys:n}),e),St=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),gt=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},Rt=(e,t,r,n)=>{let s,o,i;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)i=s[o],(!n||n(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=r!==!1&&he(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Ot=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return n!==-1&&n===r},Tt=e=>{if(!e)return null;if(U(e))return e;let t=e.length;if(!Le(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},At=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&he(Uint8Array)),vt=(e,t)=>{const n=(e&&e[Symbol.iterator]).call(e);let s;for(;(s=n.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},xt=(e,t)=>{let r;const n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},Ct=x("HTMLFormElement"),Nt=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,s){return n.toUpperCase()+s}),Re=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Pt=x("RegExp"),$e=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};H(r,(s,o)=>{let i;(i=t(s,o,e))!==!1&&(n[o]=i||s)}),Object.defineProperties(e,n)},kt=e=>{$e(e,(t,r)=>{if(T(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const n=e[r];if(!!T(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Dt=(e,t)=>{const r={},n=s=>{s.forEach(o=>{r[o]=!0})};return U(e)?n(e):n(String(e).split(t)),r},Ft=()=>{},Bt=(e,t)=>(e=+e,Number.isFinite(e)?e:t),te="abcdefghijklmnopqrstuvwxyz",Oe="0123456789",ze={DIGIT:Oe,ALPHA:te,ALPHA_DIGIT:te+te.toUpperCase()+Oe},Lt=(e=16,t=ze.ALPHA_DIGIT)=>{let r="";const{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function Ut(e){return!!(e&&T(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const jt=e=>{const t=new Array(10),r=(n,s)=>{if(Z(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[s]=n;const o=U(n)?[]:{};return H(n,(i,c)=>{const f=r(i,s+1);!$(f)&&(o[c]=f)}),t[s]=void 0,o}}return n};return r(e,0)},It=x("AsyncFunction"),$t=e=>e&&(Z(e)||T(e))&&T(e.then)&&T(e.catch),a={isArray:U,isArrayBuffer:Be,isBuffer:ct,isFormData:_t,isArrayBufferView:lt,isString:ut,isNumber:Le,isBoolean:dt,isObject:Z,isPlainObject:M,isUndefined:$,isDate:ft,isFile:pt,isBlob:ht,isRegExp:Pt,isFunction:T,isStream:yt,isURLSearchParams:bt,isTypedArray:At,isFileList:mt,forEach:H,merge:ce,extend:wt,trim:Et,stripBOM:St,inherits:gt,toFlatObject:Rt,kindOf:G,kindOfTest:x,endsWith:Ot,toArray:Tt,forEachEntry:vt,matchAll:xt,isHTMLForm:Ct,hasOwnProperty:Re,hasOwnProp:Re,reduceDescriptors:$e,freezeMethods:kt,toObjectSet:Dt,toCamelCase:Nt,noop:Ft,toFiniteNumber:Bt,findKey:Ue,global:je,isContextDefined:Ie,ALPHABET:ze,generateString:Lt,isSpecCompliantForm:Ut,toJSONObject:jt,isAsyncFn:It,isThenable:$t};function m(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s)}a.inherits(m,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const He=m.prototype,qe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{qe[e]={value:e}});Object.defineProperties(m,qe);Object.defineProperty(He,"isAxiosError",{value:!0});m.from=(e,t,r,n,s,o)=>{const i=Object.create(He);return a.toFlatObject(e,i,function(f){return f!==Error.prototype},c=>c!=="isAxiosError"),m.call(i,e.message,t,r,n,s),i.cause=e,i.name=e.name,o&&Object.assign(i,o),i};const zt=null;function le(e){return a.isPlainObject(e)||a.isArray(e)}function Me(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function Te(e,t,r){return e?e.concat(t).map(function(s,o){return s=Me(s),!r&&o?"["+s+"]":s}).join(r?".":""):t}function Ht(e){return a.isArray(e)&&!e.some(le)}const qt=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function Y(e,t,r){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,r=a.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,E){return!a.isUndefined(E[h])});const n=r.metaTokens,s=r.visitor||p,o=r.dots,i=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function d(u){if(u===null)return"";if(a.isDate(u))return u.toISOString();if(!f&&a.isBlob(u))throw new m("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(u)||a.isTypedArray(u)?f&&typeof Blob=="function"?new Blob([u]):Buffer.from(u):u}function p(u,h,E){let g=u;if(u&&!E&&typeof u=="object"){if(a.endsWith(h,"{}"))h=n?h:h.slice(0,-2),u=JSON.stringify(u);else if(a.isArray(u)&&Ht(u)||(a.isFileList(u)||a.endsWith(h,"[]"))&&(g=a.toArray(u)))return h=Me(h),g.forEach(function(P,rt){!(a.isUndefined(P)||P===null)&&t.append(i===!0?Te([h],rt,o):i===null?h:h+"[]",d(P))}),!1}return le(u)?!0:(t.append(Te(E,h,o),d(u)),!1)}const l=[],b=Object.assign(qt,{defaultVisitor:p,convertValue:d,isVisitable:le});function R(u,h){if(!a.isUndefined(u)){if(l.indexOf(u)!==-1)throw Error("Circular reference detected in "+h.join("."));l.push(u),a.forEach(u,function(g,N){(!(a.isUndefined(g)||g===null)&&s.call(t,g,a.isString(N)?N.trim():N,h,b))===!0&&R(g,h?h.concat(N):[N])}),l.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return R(e),t}function Ae(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function me(e,t){this._pairs=[],e&&Y(e,this,t)}const Ve=me.prototype;Ve.append=function(t,r){this._pairs.push([t,r])};Ve.toString=function(t){const r=t?function(n){return t.call(this,n,Ae)}:Ae;return this._pairs.map(function(s){return r(s[0])+"="+r(s[1])},"").join("&")};function Mt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Je(e,t,r){if(!t)return e;const n=r&&r.encode||Mt,s=r&&r.serialize;let o;if(s?o=s(t,r):o=a.isURLSearchParams(t)?t.toString():new me(t,r).toString(n),o){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class Vt{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(n){n!==null&&t(n)})}}const ve=Vt,We={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Jt=typeof URLSearchParams<"u"?URLSearchParams:me,Wt=typeof FormData<"u"?FormData:null,Kt=typeof Blob<"u"?Blob:null,Xt={isBrowser:!0,classes:{URLSearchParams:Jt,FormData:Wt,Blob:Kt},protocols:["http","https","file","blob","url","data"]},Ke=typeof window<"u"&&typeof document<"u",Gt=(e=>Ke&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),Qt=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),Zt=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ke,hasStandardBrowserWebWorkerEnv:Qt,hasStandardBrowserEnv:Gt},Symbol.toStringTag,{value:"Module"})),A={...Zt,...Xt};function Yt(e,t){return Y(e,new A.classes.URLSearchParams,Object.assign({visitor:function(r,n,s,o){return A.isNode&&a.isBuffer(r)?(this.append(n,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}function en(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function tn(e){const t={},r=Object.keys(e);let n;const s=r.length;let o;for(n=0;n=r.length;return i=!i&&a.isArray(s)?s.length:i,f?(a.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),t(r,n,s[i],o)&&a.isArray(s[i])&&(s[i]=tn(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const r={};return a.forEachEntry(e,(n,s)=>{t(en(n),s,r,0)}),r}return null}function nn(e,t,r){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}const ye={transitional:We,adapter:["xhr","http"],transformRequest:[function(t,r){const n=r.getContentType()||"",s=n.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return s?JSON.stringify(Xe(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Yt(t,this.formSerializer).toString();if((c=a.isFileList(t))||n.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return Y(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return o||s?(r.setContentType("application/json",!1),nn(t)):t}],transformResponse:[function(t){const r=this.transitional||ye.transitional,n=r&&r.forcedJSONParsing,s=this.responseType==="json";if(t&&a.isString(t)&&(n&&!this.responseType||s)){const i=!(r&&r.silentJSONParsing)&&s;try{return JSON.parse(t)}catch(c){if(i)throw c.name==="SyntaxError"?m.from(c,m.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:A.classes.FormData,Blob:A.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],e=>{ye.headers[e]={}});const _e=ye,rn=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),sn=e=>{const t={};let r,n,s;return e&&e.split(` +`).forEach(function(i){s=i.indexOf(":"),r=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!r||t[r]&&rn[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t},xe=Symbol("internals");function j(e){return e&&String(e).trim().toLowerCase()}function V(e){return e===!1||e==null?e:a.isArray(e)?e.map(V):String(e)}function on(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const an=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ne(e,t,r,n,s){if(a.isFunction(n))return n.call(this,t,r);if(s&&(t=r),!!a.isString(t)){if(a.isString(n))return t.indexOf(n)!==-1;if(a.isRegExp(n))return n.test(t)}}function cn(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function ln(e,t){const r=a.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(s,o,i){return this[n].call(this,t,s,o,i)},configurable:!0})})}class ee{constructor(t){t&&this.set(t)}set(t,r,n){const s=this;function o(c,f,d){const p=j(f);if(!p)throw new Error("header name must be a non-empty string");const l=a.findKey(s,p);(!l||s[l]===void 0||d===!0||d===void 0&&s[l]!==!1)&&(s[l||f]=V(c))}const i=(c,f)=>a.forEach(c,(d,p)=>o(d,p,f));return a.isPlainObject(t)||t instanceof this.constructor?i(t,r):a.isString(t)&&(t=t.trim())&&!an(t)?i(sn(t),r):t!=null&&o(r,t,n),this}get(t,r){if(t=j(t),t){const n=a.findKey(this,t);if(n){const s=this[n];if(!r)return s;if(r===!0)return on(s);if(a.isFunction(r))return r.call(this,s,n);if(a.isRegExp(r))return r.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=j(t),t){const n=a.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||ne(this,this[n],n,r)))}return!1}delete(t,r){const n=this;let s=!1;function o(i){if(i=j(i),i){const c=a.findKey(n,i);c&&(!r||ne(n,n[c],c,r))&&(delete n[c],s=!0)}}return a.isArray(t)?t.forEach(o):o(t),s}clear(t){const r=Object.keys(this);let n=r.length,s=!1;for(;n--;){const o=r[n];(!t||ne(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const r=this,n={};return a.forEach(this,(s,o)=>{const i=a.findKey(n,o);if(i){r[i]=V(s),delete r[o];return}const c=t?cn(o):String(o).trim();c!==o&&delete r[o],r[c]=V(s),n[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const r=Object.create(null);return a.forEach(this,(n,s)=>{n!=null&&n!==!1&&(r[s]=t&&a.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){const n=new this(t);return r.forEach(s=>n.set(s)),n}static accessor(t){const n=(this[xe]=this[xe]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=j(i);n[c]||(ln(s,i),n[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}}ee.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(ee.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});a.freezeMethods(ee);const C=ee;function re(e,t){const r=this||_e,n=t||r,s=C.from(n.headers);let o=n.data;return a.forEach(e,function(c){o=c.call(r,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function Ge(e){return!!(e&&e.__CANCEL__)}function q(e,t,r){m.call(this,e==null?"canceled":e,m.ERR_CANCELED,t,r),this.name="CanceledError"}a.inherits(q,m,{__CANCEL__:!0});function un(e,t,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new m("Request failed with status code "+r.status,[m.ERR_BAD_REQUEST,m.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}const dn=A.hasStandardBrowserEnv?{write(e,t,r,n,s,o){const i=[e+"="+encodeURIComponent(t)];a.isNumber(r)&&i.push("expires="+new Date(r).toGMTString()),a.isString(n)&&i.push("path="+n),a.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function fn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function pn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Qe(e,t){return e&&!fn(t)?pn(e,t):t}const hn=A.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");let n;function s(o){let i=o;return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=s(window.location.href),function(i){const c=a.isString(i)?s(i):i;return c.protocol===n.protocol&&c.host===n.host}}():function(){return function(){return!0}}();function mn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function yn(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(f){const d=Date.now(),p=n[o];i||(i=d),r[s]=f,n[s]=d;let l=o,b=0;for(;l!==s;)b+=r[l++],l=l%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),d-i{const o=s.loaded,i=s.lengthComputable?s.total:void 0,c=o-r,f=n(c),d=o<=i;r=o;const p={loaded:o,total:i,progress:i?o/i:void 0,bytes:c,rate:f||void 0,estimated:f&&i&&d?(i-o)/f:void 0,event:s};p[t?"download":"upload"]=!0,e(p)}}const _n=typeof XMLHttpRequest<"u",bn=_n&&function(e){return new Promise(function(r,n){let s=e.data;const o=C.from(e.headers).normalize();let{responseType:i,withXSRFToken:c}=e,f;function d(){e.cancelToken&&e.cancelToken.unsubscribe(f),e.signal&&e.signal.removeEventListener("abort",f)}let p;if(a.isFormData(s)){if(A.hasStandardBrowserEnv||A.hasStandardBrowserWebWorkerEnv)o.setContentType(!1);else if((p=o.getContentType())!==!1){const[h,...E]=p?p.split(";").map(g=>g.trim()).filter(Boolean):[];o.setContentType([h||"multipart/form-data",...E].join("; "))}}let l=new XMLHttpRequest;if(e.auth){const h=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.set("Authorization","Basic "+btoa(h+":"+E))}const b=Qe(e.baseURL,e.url);l.open(e.method.toUpperCase(),Je(b,e.params,e.paramsSerializer),!0),l.timeout=e.timeout;function R(){if(!l)return;const h=C.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders()),g={data:!i||i==="text"||i==="json"?l.responseText:l.response,status:l.status,statusText:l.statusText,headers:h,config:e,request:l};un(function(P){r(P),d()},function(P){n(P),d()},g),l=null}if("onloadend"in l?l.onloadend=R:l.onreadystatechange=function(){!l||l.readyState!==4||l.status===0&&!(l.responseURL&&l.responseURL.indexOf("file:")===0)||setTimeout(R)},l.onabort=function(){!l||(n(new m("Request aborted",m.ECONNABORTED,e,l)),l=null)},l.onerror=function(){n(new m("Network Error",m.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const g=e.transitional||We;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),n(new m(E,g.clarifyTimeoutError?m.ETIMEDOUT:m.ECONNABORTED,e,l)),l=null},A.hasStandardBrowserEnv&&(c&&a.isFunction(c)&&(c=c(e)),c||c!==!1&&hn(b))){const h=e.xsrfHeaderName&&e.xsrfCookieName&&dn.read(e.xsrfCookieName);h&&o.set(e.xsrfHeaderName,h)}s===void 0&&o.setContentType(null),"setRequestHeader"in l&&a.forEach(o.toJSON(),function(E,g){l.setRequestHeader(g,E)}),a.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),i&&i!=="json"&&(l.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&l.addEventListener("progress",Ce(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&l.upload&&l.upload.addEventListener("progress",Ce(e.onUploadProgress)),(e.cancelToken||e.signal)&&(f=h=>{!l||(n(!h||h.type?new q(null,e,l):h),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(f),e.signal&&(e.signal.aborted?f():e.signal.addEventListener("abort",f)));const u=mn(b);if(u&&A.protocols.indexOf(u)===-1){n(new m("Unsupported protocol "+u+":",m.ERR_BAD_REQUEST,e));return}l.send(s||null)})},ue={http:zt,xhr:bn};a.forEach(ue,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Ne=e=>`- ${e}`,En=e=>a.isFunction(e)||e===null||e===!1,Ze={getAdapter:e=>{e=a.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let o=0;o`adapter ${c} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=t?o.length>1?`since : +`+o.map(Ne).join(` +`):" "+Ne(o[0]):"as no adapter specified";throw new m("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return n},adapters:ue};function se(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new q(null,e)}function Pe(e){return se(e),e.headers=C.from(e.headers),e.data=re.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ze.getAdapter(e.adapter||_e.adapter)(e).then(function(n){return se(e),n.data=re.call(e,e.transformResponse,n),n.headers=C.from(n.headers),n},function(n){return Ge(n)||(se(e),n&&n.response&&(n.response.data=re.call(e,e.transformResponse,n.response),n.response.headers=C.from(n.response.headers))),Promise.reject(n)})}const ke=e=>e instanceof C?e.toJSON():e;function L(e,t){t=t||{};const r={};function n(d,p,l){return a.isPlainObject(d)&&a.isPlainObject(p)?a.merge.call({caseless:l},d,p):a.isPlainObject(p)?a.merge({},p):a.isArray(p)?p.slice():p}function s(d,p,l){if(a.isUndefined(p)){if(!a.isUndefined(d))return n(void 0,d,l)}else return n(d,p,l)}function o(d,p){if(!a.isUndefined(p))return n(void 0,p)}function i(d,p){if(a.isUndefined(p)){if(!a.isUndefined(d))return n(void 0,d)}else return n(void 0,p)}function c(d,p,l){if(l in t)return n(d,p);if(l in e)return n(void 0,d)}const f={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(d,p)=>s(ke(d),ke(p),!0)};return a.forEach(Object.keys(Object.assign({},e,t)),function(p){const l=f[p]||s,b=l(e[p],t[p],p);a.isUndefined(b)&&l!==c||(r[p]=b)}),r}const Ye="1.6.7",be={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{be[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const De={};be.transitional=function(t,r,n){function s(o,i){return"[Axios v"+Ye+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,c)=>{if(t===!1)throw new m(s(i," has been removed"+(r?" in "+r:"")),m.ERR_DEPRECATED);return r&&!De[i]&&(De[i]=!0,console.warn(s(i," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,i,c):!0}};function wn(e,t,r){if(typeof e!="object")throw new m("options must be an object",m.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const o=n[s],i=t[o];if(i){const c=e[o],f=c===void 0||i(c,o,e);if(f!==!0)throw new m("option "+o+" must be "+f,m.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new m("Unknown option "+o,m.ERR_BAD_OPTION)}}const de={assertOptions:wn,validators:be},k=de.validators;class W{constructor(t){this.defaults=t,this.interceptors={request:new ve,response:new ve}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=` +`+o):n.stack=o}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=L(this.defaults,r);const{transitional:n,paramsSerializer:s,headers:o}=r;n!==void 0&&de.assertOptions(n,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?r.paramsSerializer={serialize:s}:de.assertOptions(s,{encode:k.function,serialize:k.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[r.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],u=>{delete o[u]}),r.headers=C.concat(i,o);const c=[];let f=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(r)===!1||(f=f&&h.synchronous,c.unshift(h.fulfilled,h.rejected))});const d=[];this.interceptors.response.forEach(function(h){d.push(h.fulfilled,h.rejected)});let p,l=0,b;if(!f){const u=[Pe.bind(this),void 0];for(u.unshift.apply(u,c),u.push.apply(u,d),b=u.length,p=Promise.resolve(r);l{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{n.subscribe(c),o=c}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},t(function(o,i,c){n.reason||(n.reason=new q(o,i,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}static source(){let t;return{token:new Ee(function(s){t=s}),cancel:t}}}const Sn=Ee;function gn(e){return function(r){return e.apply(null,r)}}function Rn(e){return a.isObject(e)&&e.isAxiosError===!0}const fe={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(fe).forEach(([e,t])=>{fe[t]=e});const On=fe;function et(e){const t=new J(e),r=Fe(J.prototype.request,t);return a.extend(r,J.prototype,t,{allOwnKeys:!0}),a.extend(r,t,null,{allOwnKeys:!0}),r.create=function(s){return et(L(e,s))},r}const S=et(_e);S.Axios=J;S.CanceledError=q;S.CancelToken=Sn;S.isCancel=Ge;S.VERSION=Ye;S.toFormData=Y;S.AxiosError=m;S.Cancel=S.CanceledError;S.all=function(t){return Promise.all(t)};S.spread=gn;S.isAxiosError=Rn;S.mergeConfig=L;S.AxiosHeaders=C;S.formToJSON=e=>Xe(a.isHTMLForm(e)?new FormData(e):e);S.getAdapter=Ze.getAdapter;S.HttpStatusCode=On;S.default=S;const Tn=S;const tt=e=>(K("data-v-f95f1d7c"),e=e(),X(),e),An=tt(()=>y("i",{class:"fa-solid fa-cloud-arrow-up dropzone-icon"},null,-1)),vn=tt(()=>y("i",{class:"fa-regular fa-file-video dropzone-icon"},null,-1)),xn={__name:"Dropzone",emits:["fileUploaded"],setup(e,{emit:t}){const r=v(null),n=v(null),s=pe(()=>!!n.value),o=v(!1),i=t;st(()=>n.value,(u,h)=>{u&&i("fileUploaded",u)});const c=u=>{u.preventDefault(),u.stopPropagation()},f=u=>{c(u),o.value=!0},d=u=>{c(u),o.value=!1},p=u=>{c(u),o.value=!1;let h=u.dataTransfer.files[0],E=new DataTransfer;E.items.add(h);let g=E.files;r.value.files=g,n.value=h},l=()=>{r.value.click()},b=u=>{const h=u.target;h&&h.files&&(n.value=h.files[0])},R=u=>Math.round(u/1e6);return(u,h)=>(_(),w("div",{class:I(["dropzone",{"dropzone-dragging":o.value}]),id:"dropzone",onDrag:c,onDragstart:c,onDragend:c,onDragover:f,onDragenter:d,onDragleave:c,onDrop:p,onClick:ot(l,["self"])},[s.value?(_(),w(D,{key:1},[vn,F(" "+O(n.value.name)+" ("+O(R(n.value.size))+" MB) ",1)],64)):(_(),w(D,{key:0},[An,F(" Drop files or Click here to select files to upload. ")],64)),y("input",{type:"file",name:"files",class:"dropzone-input",ref_key:"dropzoneInput",ref:r,onChange:b},null,544)],34))}},Cn=z(xn,[["__scopeId","data-v-f95f1d7c"]]);const Nn={},Pn=e=>(K("data-v-3efb54fc"),e=e(),X(),e),kn={class:"dropzone"},Dn=Pn(()=>y("div",{class:"loading-animation"},[y("div",{class:"dot"}),y("div",{class:"dot"}),y("div",{class:"dot"})],-1));function Fn(e,t){return _(),w("div",kn,[Dn,F(" Processing ... ")])}const Bn=z(Nn,[["render",Fn],["__scopeId","data-v-3efb54fc"]]);const Ln=["src"],Un={__name:"Video",props:{videoName:String,startAt:{required:!1,type:Number}},setup(e){const t="http://127.0.0.1",{videoName:r,startAt:n}=e,s=pe(()=>`${t}/api/video/stream?video_name=${r}`),o=v(null),i=v(null);it(()=>{n&&(o.value.currentTime=n)});const c=()=>{i.value.scrollIntoView({behavior:"smooth",block:"center"})};return(f,d)=>(_(),w(D,null,[y("p",null,O(s.value),1),y("div",{class:"player",ref_key:"videoContainer",ref:i},[y("video",{controls:"",ref_key:"video",ref:o,onLoadeddata:c,autoplay:"",loop:"",muted:""},[y("source",{src:`${s.value}`,type:"video/mp4"},null,8,Ln)],544)],512)],64))}},jn=z(Un,[["__scopeId","data-v-ea1329c7"]]);const nt=e=>(K("data-v-e0283d6e"),e=e(),X(),e),In={class:"result-section"},$n={class:"tab-links"},zn={class:"tab-container"},Hn={key:0,class:"main"},qn={key:0,class:"info-color"},Mn={key:1,class:"info-color"},Vn={class:"main"},Jn={class:"error-color"},Wn={key:0,class:"fa-solid fa-circle-exclamation error-color"},Kn={key:1,class:"fa-solid fa-circle-check"},Xn={key:1,class:"errors"},Gn=nt(()=>y("i",{class:"fa-solid fa-caret-right"},null,-1)),Qn={class:"box-error"},Zn=["onClick"],Yn=["src"],er=nt(()=>y("hr",null,null,-1)),tr={key:0,class:"video-container"},nr={__name:"Result",props:["data"],setup(e){const{data:t}=e,r=pe(()=>{let i={total:0,totalInString:"",details:{}},c=t.details.length;return i.total=c,c==0||c==1?i.totalInString=`${c} error`:i.totalInString=`${c} errors`,t.details.forEach(f=>{let d=f.stage;i.details[d]=i.details[d]?i.details[d]+1:1}),i}),n=v("summary"),s=v(0),o=i=>{n.value="video",s.value=i};return(i,c)=>(_(),w("section",In,[y("ul",$n,[y("li",{class:I({active:n.value=="summary"}),onClick:c[0]||(c[0]=()=>n.value="summary")}," Summary ",2),y("li",{class:I({active:n.value=="detail"}),onClick:c[1]||(c[1]=()=>n.value="detail")}," Detail ",2),y("li",{class:I({active:n.value=="video"}),onClick:c[2]||(c[2]=()=>n.value="video")}," Full Video ",2)]),y("div",zn,[n.value=="summary"?(_(),w(D,{key:0},[e.data.counter?(_(),w("p",Hn,[e.data.type!="bicep_curl"?(_(),w("span",qn," Counter: "+O(e.data.counter),1)):(_(),w("span",Mn," Left arm counter: "+O(e.data.counter.left_counter)+" - Right arm counter: "+O(e.data.counter.right_counter),1))])):B("",!0),y("p",Vn,[F(" There are "),y("span",Jn,O(r.value.totalInString),1),F(" found. "),r.value.total>0?(_(),w("i",Wn)):(_(),w("i",Kn))]),r.value.total>0?(_(),w("ul",Xn,[(_(!0),w(D,null,oe(r.value.details,(f,d)=>(_(),w("li",null,[Gn,F(" "+O(d)+": "+O(f),1)]))),256))])):B("",!0)],64)):B("",!0),(_(),ie(we,null,[n.value=="detail"?(_(!0),w(D,{key:0},oe(e.data.details,(f,d)=>(_(),w("div",Qn,[y("p",null,[F(O(d+1)+". "+O(f.stage)+" at ",1),y("span",{class:"error-time",onClick:p=>o(f.timestamp)},O(f.timestamp)+" second ",9,Zn)]),y("img",{src:`${f.frame}`},null,8,Yn),er]))),256)):B("",!0)],1024)),(_(),ie(we,null,[n.value=="video"?(_(),w("div",tr,[ae(jn,{"video-name":e.data.file_name,"start-at":s.value},null,8,["video-name","start-at"])])):B("",!0)],1024))])]))}},rr=z(nr,[["__scopeId","data-v-e0283d6e"]]);const sr=e=>(K("data-v-1253291f"),e=e(),X(),e),or={class:"input-section"},ir={class:"right-container"},ar={class:"exercises-container"},cr=["onClick"],lr=sr(()=>y("span",null,"Process!",-1)),ur=[lr],dr={__name:"VideoStreaming",setup(e){const t="http://127.0.0.1",r=["squat","plank","bicep_curl","lunge"],n=v({videoFile:null,exerciseType:null}),s=v(null),o=v(!1),i=async()=>{if(!n.value.videoFile){alert("No video selected");return}if(!n.value.exerciseType){alert("No exercise type selected");return}s.value=null;try{o.value=!0;const{data:c}=await Tn.post(`${t}/api/video/upload?type=${n.value.exerciseType}`,{file:n.value.videoFile},{headers:{"Content-Type":"multipart/form-data"}});s.value=c}catch(c){console.error("Error: ",c)}finally{o.value=!1}};return(c,f)=>(_(),w(D,null,[y("section",or,[Se(ae(Cn,{onFileUploaded:f[0]||(f[0]=d=>n.value.videoFile=d)},null,512),[[ge,!o.value]]),Se(ae(Bn,null,null,512),[[ge,o.value]]),y("div",ir,[y("div",ar,[(_(),w(D,null,oe(r,d=>y("p",{class:I(["exercise",{active:n.value.exerciseType==d}]),onClick:p=>n.value.exerciseType=d},O(d),11,cr)),64))]),y("button",{class:"process-btn",onClick:i},ur)])]),s.value?(_(),ie(rr,{key:0,data:s.value},null,8,["data"])):B("",!0)],64))}},pr=z(dr,[["__scopeId","data-v-1253291f"]]);export{pr as default}; diff --git a/web/client/dist/static/assets/js/index-02ab79b9.js b/web/client/dist/static/assets/js/index-02ab79b9.js new file mode 100644 index 0000000000000000000000000000000000000000..56c11a40e712cbed3b6c3b60fbe1d99280e475de --- /dev/null +++ b/web/client/dist/static/assets/js/index-02ab79b9.js @@ -0,0 +1,25 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerpolicy&&(o.referrerPolicy=r.referrerpolicy),r.crossorigin==="use-credentials"?o.credentials="include":r.crossorigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();/** +* @vue/shared v3.4.20 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function ts(e,t){const n=new Set(e.split(","));return t?s=>n.has(s.toLowerCase()):s=>n.has(s)}const X={},gt=[],be=()=>{},Do=()=>!1,hn=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),ns=e=>e.startsWith("onUpdate:"),ce=Object.assign,ss=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},Wo=Object.prototype.hasOwnProperty,D=(e,t)=>Wo.call(e,t),k=Array.isArray,mt=e=>qt(e)==="[object Map]",Rr=e=>qt(e)==="[object Set]",qo=e=>qt(e)==="[object RegExp]",K=e=>typeof e=="function",ne=e=>typeof e=="string",wt=e=>typeof e=="symbol",te=e=>e!==null&&typeof e=="object",Sr=e=>(te(e)||K(e))&&K(e.then)&&K(e.catch),Cr=Object.prototype.toString,qt=e=>Cr.call(e),zo=e=>qt(e).slice(8,-1),Pr=e=>qt(e)==="[object Object]",rs=e=>ne(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,It=ts(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),pn=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},Go=/-(\w)/g,Le=pn(e=>e.replace(Go,(t,n)=>n?n.toUpperCase():"")),Qo=/\B([A-Z])/g,Rt=pn(e=>e.replace(Qo,"-$1").toLowerCase()),gn=pn(e=>e.charAt(0).toUpperCase()+e.slice(1)),Pn=pn(e=>e?`on${gn(e)}`:""),Je=(e,t)=>!Object.is(e,t),Mt=(e,t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:n})},Yo=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let Ps;const os=()=>Ps||(Ps=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function is(e){if(k(e)){const t={};for(let n=0;n{if(n){const s=n.split(Xo);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function ls(e){let t="";if(ne(e))t=e;else if(k(e))for(let n=0;nne(e)?e:e==null?"":k(e)||te(e)&&(e.toString===Cr||!K(e.toString))?JSON.stringify(e,Or,2):String(e),Or=(e,t)=>t&&t.__v_isRef?Or(e,t.value):mt(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,r],o)=>(n[An(s,o)+" =>"]=r,n),{})}:Rr(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>An(n))}:wt(t)?An(t):te(t)&&!k(t)&&!Pr(t)?String(t):t,An=(e,t="")=>{var n;return wt(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};/** +* @vue/reactivity v3.4.20 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/let we;class Tr{constructor(t=!1){this.detached=t,this._active=!0,this.effects=[],this.cleanups=[],this.parent=we,!t&&we&&(this.index=(we.scopes||(we.scopes=[])).push(this)-1)}get active(){return this._active}run(t){if(this._active){const n=we;try{return we=this,t()}finally{we=n}}}on(){we=this}off(){we=this.parent}stop(t){if(this._active){let n,s;for(n=0,s=this.effects.length;n=4))break}this._dirtyLevel===1&&(this._dirtyLevel=0),ct()}return this._dirtyLevel>=4}set dirty(t){this._dirtyLevel=t?4:0}run(){if(this._dirtyLevel=0,!this.active)return this.fn();let t=Qe,n=st;try{return Qe=!0,st=this,this._runnings++,As(this),this.fn()}finally{Os(this),this._runnings--,st=n,Qe=t}}stop(){var t;this.active&&(As(this),Os(this),(t=this.onStop)==null||t.call(this),this.active=!1)}}function ii(e){return e.value}function As(e){e._trackId++,e._depsLength=0}function Os(e){if(e.deps.length>e._depsLength){for(let t=e._depsLength;t{const n=new Map;return n.cleanup=e,n.computed=t,n},Vn=new WeakMap,rt=Symbol(""),Un=Symbol("");function me(e,t,n){if(Qe&&st){let s=Vn.get(e);s||Vn.set(e,s=new Map);let r=s.get(n);r||s.set(n,r=Nr(()=>s.delete(n))),Fr(st,r)}}function je(e,t,n,s,r,o){const i=Vn.get(e);if(!i)return;let c=[];if(t==="clear")c=[...i.values()];else if(n==="length"&&k(e)){const l=Number(s);i.forEach((d,f)=>{(f==="length"||!wt(f)&&f>=l)&&c.push(d)})}else switch(n!==void 0&&c.push(i.get(n)),t){case"add":k(e)?rs(n)&&c.push(i.get("length")):(c.push(i.get(rt)),mt(e)&&c.push(i.get(Un)));break;case"delete":k(e)||(c.push(i.get(rt)),mt(e)&&c.push(i.get(Un)));break;case"set":mt(e)&&c.push(i.get(rt));break}us();for(const l of c)l&&Lr(l,4);fs()}const li=ts("__proto__,__v_isRef,__isVue"),$r=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(wt)),Ts=ci();function ci(){const e={};return["includes","indexOf","lastIndexOf"].forEach(t=>{e[t]=function(...n){const s=W(this);for(let o=0,i=this.length;o{e[t]=function(...n){lt(),us();const s=W(this)[t].apply(this,n);return fs(),ct(),s}}),e}function ui(e){const t=W(this);return me(t,"has",e),t.hasOwnProperty(e)}class Hr{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,s){const r=this._isReadonly,o=this._isShallow;if(n==="__v_isReactive")return!r;if(n==="__v_isReadonly")return r;if(n==="__v_isShallow")return o;if(n==="__v_raw")return s===(r?o?xi:Kr:o?Br:kr).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(s)?t:void 0;const i=k(t);if(!r){if(i&&D(Ts,n))return Reflect.get(Ts,n,s);if(n==="hasOwnProperty")return ui}const c=Reflect.get(t,n,s);return(wt(n)?$r.has(n):li(n))||(r||me(t,"get",n),o)?c:_e(c)?i&&rs(n)?c:c.value:te(c)?r?Ur(c):_n(c):c}}class jr extends Hr{constructor(t=!1){super(!1,t)}set(t,n,s,r){let o=t[n];if(!this._isShallow){const l=vt(o);if(!ln(s)&&!vt(s)&&(o=W(o),s=W(s)),!k(t)&&_e(o)&&!_e(s))return l?!1:(o.value=s,!0)}const i=k(t)&&rs(n)?Number(n)e,mn=e=>Reflect.getPrototypeOf(e);function Qt(e,t,n=!1,s=!1){e=e.__v_raw;const r=W(e),o=W(t);n||(Je(t,o)&&me(r,"get",t),me(r,"get",o));const{has:i}=mn(r),c=s?as:n?gs:Bt;if(i.call(r,t))return c(e.get(t));if(i.call(r,o))return c(e.get(o));e!==r&&e.get(t)}function Yt(e,t=!1){const n=this.__v_raw,s=W(n),r=W(e);return t||(Je(e,r)&&me(s,"has",e),me(s,"has",r)),e===r?n.has(e):n.has(e)||n.has(r)}function Jt(e,t=!1){return e=e.__v_raw,!t&&me(W(e),"iterate",rt),Reflect.get(e,"size",e)}function Is(e){e=W(e);const t=W(this);return mn(t).has.call(t,e)||(t.add(e),je(t,"add",e,e)),this}function Ms(e,t){t=W(t);const n=W(this),{has:s,get:r}=mn(n);let o=s.call(n,e);o||(e=W(e),o=s.call(n,e));const i=r.call(n,e);return n.set(e,t),o?Je(t,i)&&je(n,"set",e,t):je(n,"add",e,t),this}function Fs(e){const t=W(this),{has:n,get:s}=mn(t);let r=n.call(t,e);r||(e=W(e),r=n.call(t,e)),s&&s.call(t,e);const o=t.delete(e);return r&&je(t,"delete",e,void 0),o}function Ls(){const e=W(this),t=e.size!==0,n=e.clear();return t&&je(e,"clear",void 0,void 0),n}function Xt(e,t){return function(s,r){const o=this,i=o.__v_raw,c=W(i),l=t?as:e?gs:Bt;return!e&&me(c,"iterate",rt),i.forEach((d,f)=>s.call(r,l(d),l(f),o))}}function Zt(e,t,n){return function(...s){const r=this.__v_raw,o=W(r),i=mt(o),c=e==="entries"||e===Symbol.iterator&&i,l=e==="keys"&&i,d=r[e](...s),f=n?as:t?gs:Bt;return!t&&me(o,"iterate",l?Un:rt),{next(){const{value:h,done:p}=d.next();return p?{value:h,done:p}:{value:c?[f(h[0]),f(h[1])]:f(h),done:p}},[Symbol.iterator](){return this}}}}function Ve(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function pi(){const e={get(o){return Qt(this,o)},get size(){return Jt(this)},has:Yt,add:Is,set:Ms,delete:Fs,clear:Ls,forEach:Xt(!1,!1)},t={get(o){return Qt(this,o,!1,!0)},get size(){return Jt(this)},has:Yt,add:Is,set:Ms,delete:Fs,clear:Ls,forEach:Xt(!1,!0)},n={get(o){return Qt(this,o,!0)},get size(){return Jt(this,!0)},has(o){return Yt.call(this,o,!0)},add:Ve("add"),set:Ve("set"),delete:Ve("delete"),clear:Ve("clear"),forEach:Xt(!0,!1)},s={get(o){return Qt(this,o,!0,!0)},get size(){return Jt(this,!0)},has(o){return Yt.call(this,o,!0)},add:Ve("add"),set:Ve("set"),delete:Ve("delete"),clear:Ve("clear"),forEach:Xt(!0,!0)};return["keys","values","entries",Symbol.iterator].forEach(o=>{e[o]=Zt(o,!1,!1),n[o]=Zt(o,!0,!1),t[o]=Zt(o,!1,!0),s[o]=Zt(o,!0,!0)}),[e,n,t,s]}const[gi,mi,_i,yi]=pi();function ds(e,t){const n=t?e?yi:_i:e?mi:gi;return(s,r,o)=>r==="__v_isReactive"?!e:r==="__v_isReadonly"?e:r==="__v_raw"?s:Reflect.get(D(n,r)&&r in s?n:s,r,o)}const bi={get:ds(!1,!1)},vi={get:ds(!1,!0)},Ei={get:ds(!0,!1)},kr=new WeakMap,Br=new WeakMap,Kr=new WeakMap,xi=new WeakMap;function wi(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Ri(e){return e.__v_skip||!Object.isExtensible(e)?0:wi(zo(e))}function _n(e){return vt(e)?e:hs(e,!1,ai,bi,kr)}function Vr(e){return hs(e,!1,hi,vi,Br)}function Ur(e){return hs(e,!0,di,Ei,Kr)}function hs(e,t,n,s,r){if(!te(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const o=r.get(e);if(o)return o;const i=Ri(e);if(i===0)return e;const c=new Proxy(e,i===2?s:n);return r.set(e,c),c}function _t(e){return vt(e)?_t(e.__v_raw):!!(e&&e.__v_isReactive)}function vt(e){return!!(e&&e.__v_isReadonly)}function ln(e){return!!(e&&e.__v_isShallow)}function Dr(e){return _t(e)||vt(e)}function W(e){const t=e&&e.__v_raw;return t?W(t):e}function ps(e){return Object.isExtensible(e)&&on(e,"__v_skip",!0),e}const Bt=e=>te(e)?_n(e):e,gs=e=>te(e)?Ur(e):e;class Wr{constructor(t,n,s,r){this.getter=t,this._setter=n,this.dep=void 0,this.__v_isRef=!0,this.__v_isReadonly=!1,this.effect=new cs(()=>t(this._value),()=>tn(this,this.effect._dirtyLevel===2?2:3)),this.effect.computed=this,this.effect.active=this._cacheable=!r,this.__v_isReadonly=s}get value(){const t=W(this);return(!t._cacheable||t.effect.dirty)&&Je(t._value,t._value=t.effect.run())&&tn(t,4),qr(t),t.effect._dirtyLevel>=2&&tn(t,2),t._value}set value(t){this._setter(t)}get _dirty(){return this.effect.dirty}set _dirty(t){this.effect.dirty=t}}function Si(e,t,n=!1){let s,r;const o=K(e);return o?(s=e,r=be):(s=e.get,r=e.set),new Wr(s,r,o||!r,n)}function qr(e){var t;Qe&&st&&(e=W(e),Fr(st,(t=e.dep)!=null?t:e.dep=Nr(()=>e.dep=void 0,e instanceof Wr?e:void 0)))}function tn(e,t=4,n){e=W(e);const s=e.dep;s&&Lr(s,t)}function _e(e){return!!(e&&e.__v_isRef===!0)}function zr(e){return Gr(e,!1)}function Ci(e){return Gr(e,!0)}function Gr(e,t){return _e(e)?e:new Pi(e,t)}class Pi{constructor(t,n){this.__v_isShallow=n,this.dep=void 0,this.__v_isRef=!0,this._rawValue=n?t:W(t),this._value=n?t:Bt(t)}get value(){return qr(this),this._value}set value(t){const n=this.__v_isShallow||ln(t)||vt(t);t=n?t:W(t),Je(t,this._rawValue)&&(this._rawValue=t,this._value=n?t:Bt(t),tn(this,4))}}function yt(e){return _e(e)?e.value:e}const Ai={get:(e,t,n)=>yt(Reflect.get(e,t,n)),set:(e,t,n,s)=>{const r=e[t];return _e(r)&&!_e(n)?(r.value=n,!0):Reflect.set(e,t,n,s)}};function Qr(e){return _t(e)?e:new Proxy(e,Ai)}/** +* @vue/runtime-core v3.4.20 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function Ye(e,t,n,s){try{return s?e(...s):e()}catch(r){yn(r,t,n)}}function Ce(e,t,n,s){if(K(e)){const o=Ye(e,t,n,s);return o&&Sr(o)&&o.catch(i=>{yn(i,t,n)}),o}const r=[];for(let o=0;o>>1,r=ae[s],o=Vt(r);oFe&&ae.splice(t,1)}function Mi(e){k(e)?bt.push(...e):(!De||!De.includes(e,e.allowRecurse?tt+1:tt))&&bt.push(e),Xr()}function Ns(e,t,n=Kt?Fe+1:0){for(;nVt(n)-Vt(s));if(bt.length=0,De){De.push(...t);return}for(De=t,tt=0;tte.id==null?1/0:e.id,Fi=(e,t)=>{const n=Vt(e)-Vt(t);if(n===0){if(e.pre&&!t.pre)return-1;if(t.pre&&!e.pre)return 1}return n};function eo(e){Dn=!1,Kt=!0,ae.sort(Fi);const t=be;try{for(Fe=0;Fene(b)?b.trim():b)),h&&(r=n.map(Yo))}let c,l=s[c=Pn(t)]||s[c=Pn(Le(t))];!l&&o&&(l=s[c=Pn(Rt(t))]),l&&Ce(l,e,6,r);const d=s[c+"Once"];if(d){if(!e.emitted)e.emitted={};else if(e.emitted[c])return;e.emitted[c]=!0,Ce(d,e,6,r)}}function to(e,t,n=!1){const s=t.emitsCache,r=s.get(e);if(r!==void 0)return r;const o=e.emits;let i={},c=!1;if(!K(e)){const l=d=>{const f=to(d,t,!0);f&&(c=!0,ce(i,f))};!n&&t.mixins.length&&t.mixins.forEach(l),e.extends&&l(e.extends),e.mixins&&e.mixins.forEach(l)}return!o&&!c?(te(e)&&s.set(e,null),null):(k(o)?o.forEach(l=>i[l]=null):ce(i,o),te(e)&&s.set(e,i),i)}function bn(e,t){return!e||!hn(t)?!1:(t=t.slice(2).replace(/Once$/,""),D(e,t[0].toLowerCase()+t.slice(1))||D(e,Rt(t))||D(e,t))}let he=null,vn=null;function cn(e){const t=he;return he=e,vn=e&&e.type.__scopeId||null,t}function Cu(e){vn=e}function Pu(){vn=null}function no(e,t=he,n){if(!t||e._n)return e;const s=(...r)=>{s._d&&zs(-1);const o=cn(t);let i;try{i=e(...r)}finally{cn(o),s._d&&zs(1)}return i};return s._n=!0,s._c=!0,s._d=!0,s}function On(e){const{type:t,vnode:n,proxy:s,withProxy:r,props:o,propsOptions:[i],slots:c,attrs:l,emit:d,render:f,renderCache:h,data:p,setupState:b,ctx:I,inheritAttrs:N}=e;let j,F;const E=cn(e);try{if(n.shapeFlag&4){const T=r||s,U=T;j=Me(f.call(U,T,h,o,b,p,I)),F=l}else{const T=t;j=Me(T.length>1?T(o,{attrs:l,slots:c,emit:d}):T(o,null)),F=t.props?l:Ni(l)}}catch(T){Ht.length=0,yn(T,e,1),j=pe(ot)}let P=j;if(F&&N!==!1){const T=Object.keys(F),{shapeFlag:U}=P;T.length&&U&7&&(i&&T.some(ns)&&(F=$i(F,i)),P=it(P,F))}return n.dirs&&(P=it(P),P.dirs=P.dirs?P.dirs.concat(n.dirs):n.dirs),n.transition&&(P.transition=n.transition),j=P,cn(E),j}const Ni=e=>{let t;for(const n in e)(n==="class"||n==="style"||hn(n))&&((t||(t={}))[n]=e[n]);return t},$i=(e,t)=>{const n={};for(const s in e)(!ns(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function Hi(e,t,n){const{props:s,children:r,component:o}=e,{props:i,children:c,patchFlag:l}=t,d=o.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&l>=0){if(l&1024)return!0;if(l&16)return s?$s(s,i,d):!!i;if(l&8){const f=t.dynamicProps;for(let h=0;he.__isSuspense;function Ki(e,t){t&&t.pendingBranch?k(e)?t.effects.push(...e):t.effects.push(e):Mi(e)}const Vi=Symbol.for("v-scx"),Ui=()=>ke(Vi),en={};function Ft(e,t,n){return oo(e,t,n)}function oo(e,t,{immediate:n,deep:s,flush:r,once:o,onTrack:i,onTrigger:c}=X){if(t&&o){const $=t;t=(...J)=>{$(...J),U()}}const l=le,d=$=>s===!0?$:nt($,s===!1?1:void 0);let f,h=!1,p=!1;if(_e(e)?(f=()=>e.value,h=ln(e)):_t(e)?(f=()=>d(e),h=!0):k(e)?(p=!0,h=e.some($=>_t($)||ln($)),f=()=>e.map($=>{if(_e($))return $.value;if(_t($))return d($);if(K($))return Ye($,l,2)})):K(e)?t?f=()=>Ye(e,l,2):f=()=>(b&&b(),Ce(e,l,3,[I])):f=be,t&&s){const $=f;f=()=>nt($())}let b,I=$=>{b=P.onStop=()=>{Ye($,l,4),b=P.onStop=void 0}},N;if(Rn)if(I=be,t?n&&Ce(t,l,3,[f(),p?[]:void 0,I]):f(),r==="sync"){const $=Ui();N=$.__watcherHandles||($.__watcherHandles=[])}else return be;let j=p?new Array(e.length).fill(en):en;const F=()=>{if(!(!P.active||!P.dirty))if(t){const $=P.run();(s||h||(p?$.some((J,se)=>Je(J,j[se])):Je($,j)))&&(b&&b(),Ce(t,l,3,[$,j===en?void 0:p&&j[0]===en?[]:j,I]),j=$)}else P.run()};F.allowRecurse=!!t;let E;r==="sync"?E=F:r==="post"?E=()=>ie(F,l&&l.suspense):(F.pre=!0,l&&(F.id=l.uid),E=()=>_s(F));const P=new cs(f,be,E),T=oi(),U=()=>{P.stop(),T&&ss(T.effects,P)};return t?n?F():j=P.run():r==="post"?ie(P.run.bind(P),l&&l.suspense):P.run(),N&&N.push(U),U}function Di(e,t,n){const s=this.proxy,r=ne(e)?e.includes(".")?io(s,e):()=>s[e]:e.bind(s,s);let o;K(t)?o=t:(o=t.handler,n=t);const i=zt(this),c=oo(r,o.bind(s),n);return i(),c}function io(e,t){const n=t.split(".");return()=>{let s=e;for(let r=0;r0){if(n>=t)return e;n++}if(s=s||new Set,s.has(e))return e;if(s.add(e),_e(e))nt(e.value,t,n,s);else if(k(e))for(let r=0;r{nt(r,t,n,s)});else if(Pr(e))for(const r in e)nt(e[r],t,n,s);return e}function Au(e,t){if(he===null)return e;const n=Sn(he)||he.proxy,s=e.dirs||(e.dirs=[]);for(let r=0;rce({name:e.name},t,{setup:e}))():e}const Lt=e=>!!e.type.__asyncLoader,uo=e=>e.type.__isKeepAlive,Wi={name:"KeepAlive",__isKeepAlive:!0,props:{include:[String,RegExp,Array],exclude:[String,RegExp,Array],max:[String,Number]},setup(e,{slots:t}){const n=Ol(),s=n.ctx;if(!s.renderer)return()=>{const E=t.default&&t.default();return E&&E.length===1?E[0]:E};const r=new Map,o=new Set;let i=null;const c=n.suspense,{renderer:{p:l,m:d,um:f,o:{createElement:h}}}=s,p=h("div");s.activate=(E,P,T,U,$)=>{const J=E.component;d(E,P,T,0,c),l(J.vnode,E,P,T,J,c,U,E.slotScopeIds,$),ie(()=>{J.isDeactivated=!1,J.a&&Mt(J.a);const se=E.props&&E.props.onVnodeMounted;se&&Ee(se,J.parent,E)},c)},s.deactivate=E=>{const P=E.component;d(E,p,null,1,c),ie(()=>{P.da&&Mt(P.da);const T=E.props&&E.props.onVnodeUnmounted;T&&Ee(T,P.parent,E),P.isDeactivated=!0},c)};function b(E){Tn(E),f(E,n,c,!0)}function I(E){r.forEach((P,T)=>{const U=Jn(P.type);U&&(!E||!E(U))&&N(T)})}function N(E){const P=r.get(E);!i||!ht(P,i)?b(P):i&&Tn(i),r.delete(E),o.delete(E)}Ft(()=>[e.include,e.exclude],([E,P])=>{E&&I(T=>Ot(E,T)),P&&I(T=>!Ot(P,T))},{flush:"post",deep:!0});let j=null;const F=()=>{j!=null&&r.set(j,In(n.subTree))};return ao(F),ho(F),po(()=>{r.forEach(E=>{const{subTree:P,suspense:T}=n,U=In(P);if(E.type===U.type&&E.key===U.key){Tn(U);const $=U.component.da;$&&ie($,T);return}b(E)})}),()=>{if(j=null,!t.default)return null;const E=t.default(),P=E[0];if(E.length>1)return i=null,E;if(!fn(P)||!(P.shapeFlag&4)&&!(P.shapeFlag&128))return i=null,P;let T=In(P);const U=T.type,$=Jn(Lt(T)?T.type.__asyncResolved||{}:U),{include:J,exclude:se,max:Ae}=e;if(J&&(!$||!Ot(J,$))||se&&$&&Ot(se,$))return i=T,P;const ue=T.key==null?U:T.key,ve=r.get(ue);return T.el&&(T=it(T),P.shapeFlag&128&&(P.ssContent=T)),j=ue,ve?(T.el=ve.el,T.component=ve.component,T.transition&&lo(T,T.transition),T.shapeFlag|=512,o.delete(ue),o.add(ue)):(o.add(ue),Ae&&o.size>parseInt(Ae,10)&&N(o.values().next().value)),T.shapeFlag|=256,i=T,ro(P.type)?P:T}}},Ou=Wi;function Ot(e,t){return k(e)?e.some(n=>Ot(n,t)):ne(e)?e.split(",").includes(t):qo(e)?e.test(t):!1}function qi(e,t){fo(e,"a",t)}function zi(e,t){fo(e,"da",t)}function fo(e,t,n=le){const s=e.__wdc||(e.__wdc=()=>{let r=n;for(;r;){if(r.isDeactivated)return;r=r.parent}return e()});if(En(t,s,n),n){let r=n.parent;for(;r&&r.parent;)uo(r.parent.vnode)&&Gi(s,t,n,r),r=r.parent}}function Gi(e,t,n,s){const r=En(t,e,s,!0);go(()=>{ss(s[t],r)},n)}function Tn(e){e.shapeFlag&=-257,e.shapeFlag&=-513}function In(e){return e.shapeFlag&128?e.ssContent:e}function En(e,t,n=le,s=!1){if(n){const r=n[e]||(n[e]=[]),o=t.__weh||(t.__weh=(...i)=>{if(n.isUnmounted)return;lt();const c=zt(n),l=Ce(t,n,e,i);return c(),ct(),l});return s?r.unshift(o):r.push(o),o}}const Be=e=>(t,n=le)=>(!Rn||e==="sp")&&En(e,(...s)=>t(...s),n),Qi=Be("bm"),ao=Be("m"),Yi=Be("bu"),ho=Be("u"),po=Be("bum"),go=Be("um"),Ji=Be("sp"),Xi=Be("rtg"),Zi=Be("rtc");function el(e,t=le){En("ec",e,t)}function Tu(e,t,n,s){let r;const o=n&&n[s];if(k(e)||ne(e)){r=new Array(e.length);for(let i=0,c=e.length;it(i,c,void 0,o&&o[c]));else{const i=Object.keys(e);r=new Array(i.length);for(let c=0,l=i.length;ce?Oo(e)?Sn(e)||e.proxy:Wn(e.parent):null,Nt=ce(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Wn(e.parent),$root:e=>Wn(e.root),$emit:e=>e.emit,$options:e=>ys(e),$forceUpdate:e=>e.f||(e.f=()=>{e.effect.dirty=!0,_s(e.update)}),$nextTick:e=>e.n||(e.n=Jr.bind(e.proxy)),$watch:e=>Di.bind(e)}),Mn=(e,t)=>e!==X&&!e.__isScriptSetup&&D(e,t),tl={get({_:e},t){const{ctx:n,setupState:s,data:r,props:o,accessCache:i,type:c,appContext:l}=e;let d;if(t[0]!=="$"){const b=i[t];if(b!==void 0)switch(b){case 1:return s[t];case 2:return r[t];case 4:return n[t];case 3:return o[t]}else{if(Mn(s,t))return i[t]=1,s[t];if(r!==X&&D(r,t))return i[t]=2,r[t];if((d=e.propsOptions[0])&&D(d,t))return i[t]=3,o[t];if(n!==X&&D(n,t))return i[t]=4,n[t];qn&&(i[t]=0)}}const f=Nt[t];let h,p;if(f)return t==="$attrs"&&me(e,"get",t),f(e);if((h=c.__cssModules)&&(h=h[t]))return h;if(n!==X&&D(n,t))return i[t]=4,n[t];if(p=l.config.globalProperties,D(p,t))return p[t]},set({_:e},t,n){const{data:s,setupState:r,ctx:o}=e;return Mn(r,t)?(r[t]=n,!0):s!==X&&D(s,t)?(s[t]=n,!0):D(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(o[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:s,appContext:r,propsOptions:o}},i){let c;return!!n[i]||e!==X&&D(e,i)||Mn(t,i)||(c=o[0])&&D(c,i)||D(s,i)||D(Nt,i)||D(r.config.globalProperties,i)},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:D(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function ks(e){return k(e)?e.reduce((t,n)=>(t[n]=null,t),{}):e}let qn=!0;function nl(e){const t=ys(e),n=e.proxy,s=e.ctx;qn=!1,t.beforeCreate&&Bs(t.beforeCreate,e,"bc");const{data:r,computed:o,methods:i,watch:c,provide:l,inject:d,created:f,beforeMount:h,mounted:p,beforeUpdate:b,updated:I,activated:N,deactivated:j,beforeDestroy:F,beforeUnmount:E,destroyed:P,unmounted:T,render:U,renderTracked:$,renderTriggered:J,errorCaptured:se,serverPrefetch:Ae,expose:ue,inheritAttrs:ve,components:Xe,directives:Oe,filters:St}=t;if(d&&sl(d,s,null),i)for(const Q in i){const q=i[Q];K(q)&&(s[Q]=q.bind(n))}if(r){const Q=r.call(n,n);te(Q)&&(e.data=_n(Q))}if(qn=!0,o)for(const Q in o){const q=o[Q],Ne=K(q)?q.bind(n,n):K(q.get)?q.get.bind(n,n):be,Ke=!K(q)&&K(q.set)?q.set.bind(n):be,Te=Re({get:Ne,set:Ke});Object.defineProperty(s,Q,{enumerable:!0,configurable:!0,get:()=>Te.value,set:ge=>Te.value=ge})}if(c)for(const Q in c)mo(c[Q],s,n,Q);if(l){const Q=K(l)?l.call(n):l;Reflect.ownKeys(Q).forEach(q=>{nn(q,Q[q])})}f&&Bs(f,e,"c");function re(Q,q){k(q)?q.forEach(Ne=>Q(Ne.bind(n))):q&&Q(q.bind(n))}if(re(Qi,h),re(ao,p),re(Yi,b),re(ho,I),re(qi,N),re(zi,j),re(el,se),re(Zi,$),re(Xi,J),re(po,E),re(go,T),re(Ji,Ae),k(ue))if(ue.length){const Q=e.exposed||(e.exposed={});ue.forEach(q=>{Object.defineProperty(Q,q,{get:()=>n[q],set:Ne=>n[q]=Ne})})}else e.exposed||(e.exposed={});U&&e.render===be&&(e.render=U),ve!=null&&(e.inheritAttrs=ve),Xe&&(e.components=Xe),Oe&&(e.directives=Oe)}function sl(e,t,n=be){k(e)&&(e=zn(e));for(const s in e){const r=e[s];let o;te(r)?"default"in r?o=ke(r.from||s,r.default,!0):o=ke(r.from||s):o=ke(r),_e(o)?Object.defineProperty(t,s,{enumerable:!0,configurable:!0,get:()=>o.value,set:i=>o.value=i}):t[s]=o}}function Bs(e,t,n){Ce(k(e)?e.map(s=>s.bind(t.proxy)):e.bind(t.proxy),t,n)}function mo(e,t,n,s){const r=s.includes(".")?io(n,s):()=>n[s];if(ne(e)){const o=t[e];K(o)&&Ft(r,o)}else if(K(e))Ft(r,e.bind(n));else if(te(e))if(k(e))e.forEach(o=>mo(o,t,n,s));else{const o=K(e.handler)?e.handler.bind(n):t[e.handler];K(o)&&Ft(r,o,e)}}function ys(e){const t=e.type,{mixins:n,extends:s}=t,{mixins:r,optionsCache:o,config:{optionMergeStrategies:i}}=e.appContext,c=o.get(t);let l;return c?l=c:!r.length&&!n&&!s?l=t:(l={},r.length&&r.forEach(d=>un(l,d,i,!0)),un(l,t,i)),te(t)&&o.set(t,l),l}function un(e,t,n,s=!1){const{mixins:r,extends:o}=t;o&&un(e,o,n,!0),r&&r.forEach(i=>un(e,i,n,!0));for(const i in t)if(!(s&&i==="expose")){const c=rl[i]||n&&n[i];e[i]=c?c(e[i],t[i]):t[i]}return e}const rl={data:Ks,props:Vs,emits:Vs,methods:Tt,computed:Tt,beforeCreate:de,created:de,beforeMount:de,mounted:de,beforeUpdate:de,updated:de,beforeDestroy:de,beforeUnmount:de,destroyed:de,unmounted:de,activated:de,deactivated:de,errorCaptured:de,serverPrefetch:de,components:Tt,directives:Tt,watch:il,provide:Ks,inject:ol};function Ks(e,t){return t?e?function(){return ce(K(e)?e.call(this,this):e,K(t)?t.call(this,this):t)}:t:e}function ol(e,t){return Tt(zn(e),zn(t))}function zn(e){if(k(e)){const t={};for(let n=0;n1)return n&&K(t)?t.call(s&&s.proxy):t}}function ul(e,t,n,s=!1){const r={},o={};on(o,wn,1),e.propsDefaults=Object.create(null),yo(e,t,r,o);for(const i in e.propsOptions[0])i in r||(r[i]=void 0);n?e.props=s?r:Vr(r):e.type.props?e.props=r:e.props=o,e.attrs=o}function fl(e,t,n,s){const{props:r,attrs:o,vnode:{patchFlag:i}}=e,c=W(r),[l]=e.propsOptions;let d=!1;if((s||i>0)&&!(i&16)){if(i&8){const f=e.vnode.dynamicProps;for(let h=0;h{l=!0;const[p,b]=bo(h,t,!0);ce(i,p),b&&c.push(...b)};!n&&t.mixins.length&&t.mixins.forEach(f),e.extends&&f(e.extends),e.mixins&&e.mixins.forEach(f)}if(!o&&!l)return te(e)&&s.set(e,gt),gt;if(k(o))for(let f=0;f-1,b[1]=N<0||I-1||D(b,"default"))&&c.push(h)}}}const d=[i,c];return te(e)&&s.set(e,d),d}function Us(e){return e[0]!=="$"&&!It(e)}function Ds(e){return e===null?"null":typeof e=="function"?e.name||"":typeof e=="object"&&e.constructor&&e.constructor.name||""}function Ws(e,t){return Ds(e)===Ds(t)}function qs(e,t){return k(t)?t.findIndex(n=>Ws(n,e)):K(t)&&Ws(t,e)?0:-1}const vo=e=>e[0]==="_"||e==="$stable",bs=e=>k(e)?e.map(Me):[Me(e)],al=(e,t,n)=>{if(t._n)return t;const s=no((...r)=>bs(t(...r)),n);return s._c=!1,s},Eo=(e,t,n)=>{const s=e._ctx;for(const r in e){if(vo(r))continue;const o=e[r];if(K(o))t[r]=al(r,o,s);else if(o!=null){const i=bs(o);t[r]=()=>i}}},xo=(e,t)=>{const n=bs(t);e.slots.default=()=>n},dl=(e,t)=>{if(e.vnode.shapeFlag&32){const n=t._;n?(e.slots=W(t),on(t,"_",n)):Eo(t,e.slots={})}else e.slots={},t&&xo(e,t);on(e.slots,wn,1)},hl=(e,t,n)=>{const{vnode:s,slots:r}=e;let o=!0,i=X;if(s.shapeFlag&32){const c=t._;c?n&&c===1?o=!1:(ce(r,t),!n&&c===1&&delete r._):(o=!t.$stable,Eo(t,r)),i=t}else t&&(xo(e,t),i={default:1});if(o)for(const c in r)!vo(c)&&i[c]==null&&delete r[c]};function Qn(e,t,n,s,r=!1){if(k(e)){e.forEach((p,b)=>Qn(p,t&&(k(t)?t[b]:t),n,s,r));return}if(Lt(s)&&!r)return;const o=s.shapeFlag&4?Sn(s.component)||s.component.proxy:s.el,i=r?null:o,{i:c,r:l}=e,d=t&&t.r,f=c.refs===X?c.refs={}:c.refs,h=c.setupState;if(d!=null&&d!==l&&(ne(d)?(f[d]=null,D(h,d)&&(h[d]=null)):_e(d)&&(d.value=null)),K(l))Ye(l,c,12,[i,f]);else{const p=ne(l),b=_e(l);if(p||b){const I=()=>{if(e.f){const N=p?D(h,l)?h[l]:f[l]:l.value;r?k(N)&&ss(N,o):k(N)?N.includes(o)||N.push(o):p?(f[l]=[o],D(h,l)&&(h[l]=f[l])):(l.value=[o],e.k&&(f[e.k]=l.value))}else p?(f[l]=i,D(h,l)&&(h[l]=i)):b&&(l.value=i,e.k&&(f[e.k]=i))};i?(I.id=-1,ie(I,n)):I()}}}function pl(){typeof __VUE_PROD_HYDRATION_MISMATCH_DETAILS__!="boolean"&&(os().__VUE_PROD_HYDRATION_MISMATCH_DETAILS__=!1)}const ie=Ki;function gl(e){return ml(e)}function ml(e,t){pl();const n=os();n.__VUE__=!0;const{insert:s,remove:r,patchProp:o,createElement:i,createText:c,createComment:l,setText:d,setElementText:f,parentNode:h,nextSibling:p,setScopeId:b=be,insertStaticContent:I}=e,N=(u,a,g,y=null,m=null,w=null,C=void 0,x=null,R=!!a.dynamicChildren)=>{if(u===a)return;u&&!ht(u,a)&&(y=_(u),ge(u,m,w,!0),u=null),a.patchFlag===-2&&(R=!1,a.dynamicChildren=null);const{type:v,ref:O,shapeFlag:H}=a;switch(v){case xn:j(u,a,g,y);break;case ot:F(u,a,g,y);break;case Ln:u==null&&E(a,g,y,C);break;case He:Xe(u,a,g,y,m,w,C,x,R);break;default:H&1?U(u,a,g,y,m,w,C,x,R):H&6?Oe(u,a,g,y,m,w,C,x,R):(H&64||H&128)&&v.process(u,a,g,y,m,w,C,x,R,M)}O!=null&&m&&Qn(O,u&&u.ref,w,a||u,!a)},j=(u,a,g,y)=>{if(u==null)s(a.el=c(a.children),g,y);else{const m=a.el=u.el;a.children!==u.children&&d(m,a.children)}},F=(u,a,g,y)=>{u==null?s(a.el=l(a.children||""),g,y):a.el=u.el},E=(u,a,g,y)=>{[u.el,u.anchor]=I(u.children,a,g,y,u.el,u.anchor)},P=({el:u,anchor:a},g,y)=>{let m;for(;u&&u!==a;)m=p(u),s(u,g,y),u=m;s(a,g,y)},T=({el:u,anchor:a})=>{let g;for(;u&&u!==a;)g=p(u),r(u),u=g;r(a)},U=(u,a,g,y,m,w,C,x,R)=>{a.type==="svg"?C="svg":a.type==="math"&&(C="mathml"),u==null?$(a,g,y,m,w,C,x,R):Ae(u,a,m,w,C,x,R)},$=(u,a,g,y,m,w,C,x)=>{let R,v;const{props:O,shapeFlag:H,transition:L,dirs:B}=u;if(R=u.el=i(u.type,w,O&&O.is,O),H&8?f(R,u.children):H&16&&se(u.children,R,null,y,m,Fn(u,w),C,x),B&&Ze(u,null,y,"created"),J(R,u,u.scopeId,C,y),O){for(const Y in O)Y!=="value"&&!It(Y)&&o(R,Y,null,O[Y],w,u.children,y,m,fe);"value"in O&&o(R,"value",null,O.value,w),(v=O.onVnodeBeforeMount)&&Ee(v,y,u)}B&&Ze(u,null,y,"beforeMount");const V=_l(m,L);V&&L.beforeEnter(R),s(R,a,g),((v=O&&O.onVnodeMounted)||V||B)&&ie(()=>{v&&Ee(v,y,u),V&&L.enter(R),B&&Ze(u,null,y,"mounted")},m)},J=(u,a,g,y,m)=>{if(g&&b(u,g),y)for(let w=0;w{for(let v=R;v{const x=a.el=u.el;let{patchFlag:R,dynamicChildren:v,dirs:O}=a;R|=u.patchFlag&16;const H=u.props||X,L=a.props||X;let B;if(g&&et(g,!1),(B=L.onVnodeBeforeUpdate)&&Ee(B,g,a,u),O&&Ze(a,u,g,"beforeUpdate"),g&&et(g,!0),v?ue(u.dynamicChildren,v,x,g,y,Fn(a,m),w):C||q(u,a,x,null,g,y,Fn(a,m),w,!1),R>0){if(R&16)ve(x,a,H,L,g,y,m);else if(R&2&&H.class!==L.class&&o(x,"class",null,L.class,m),R&4&&o(x,"style",H.style,L.style,m),R&8){const V=a.dynamicProps;for(let Y=0;Y{B&&Ee(B,g,a,u),O&&Ze(a,u,g,"updated")},y)},ue=(u,a,g,y,m,w,C)=>{for(let x=0;x{if(g!==y){if(g!==X)for(const x in g)!It(x)&&!(x in y)&&o(u,x,g[x],null,C,a.children,m,w,fe);for(const x in y){if(It(x))continue;const R=y[x],v=g[x];R!==v&&x!=="value"&&o(u,x,v,R,C,a.children,m,w,fe)}"value"in y&&o(u,"value",g.value,y.value,C)}},Xe=(u,a,g,y,m,w,C,x,R)=>{const v=a.el=u?u.el:c(""),O=a.anchor=u?u.anchor:c("");let{patchFlag:H,dynamicChildren:L,slotScopeIds:B}=a;B&&(x=x?x.concat(B):B),u==null?(s(v,g,y),s(O,g,y),se(a.children||[],g,O,m,w,C,x,R)):H>0&&H&64&&L&&u.dynamicChildren?(ue(u.dynamicChildren,L,g,m,w,C,x),(a.key!=null||m&&a===m.subTree)&&wo(u,a,!0)):q(u,a,g,O,m,w,C,x,R)},Oe=(u,a,g,y,m,w,C,x,R)=>{a.slotScopeIds=x,u==null?a.shapeFlag&512?m.ctx.activate(a,g,y,C,R):St(a,g,y,m,w,C,R):ut(u,a,R)},St=(u,a,g,y,m,w,C)=>{const x=u.component=Al(u,y,m);if(uo(u)&&(x.ctx.renderer=M),Tl(x),x.asyncDep){if(m&&m.registerDep(x,re),!u.el){const R=x.subTree=pe(ot);F(null,R,a,g)}}else re(x,u,a,g,m,w,C)},ut=(u,a,g)=>{const y=a.component=u.component;if(Hi(u,a,g))if(y.asyncDep&&!y.asyncResolved){Q(y,a,g);return}else y.next=a,Ii(y.update),y.effect.dirty=!0,y.update();else a.el=u.el,y.vnode=a},re=(u,a,g,y,m,w,C)=>{const x=()=>{if(u.isMounted){let{next:O,bu:H,u:L,parent:B,vnode:V}=u;{const dt=Ro(u);if(dt){O&&(O.el=V.el,Q(u,O,C)),dt.asyncDep.then(()=>{u.isUnmounted||x()});return}}let Y=O,ee;et(u,!1),O?(O.el=V.el,Q(u,O,C)):O=V,H&&Mt(H),(ee=O.props&&O.props.onVnodeBeforeUpdate)&&Ee(ee,B,O,V),et(u,!0);const oe=On(u),xe=u.subTree;u.subTree=oe,N(xe,oe,h(xe.el),_(xe),u,m,w),O.el=oe.el,Y===null&&ji(u,oe.el),L&&ie(L,m),(ee=O.props&&O.props.onVnodeUpdated)&&ie(()=>Ee(ee,B,O,V),m)}else{let O;const{el:H,props:L}=a,{bm:B,m:V,parent:Y}=u,ee=Lt(a);if(et(u,!1),B&&Mt(B),!ee&&(O=L&&L.onVnodeBeforeMount)&&Ee(O,Y,a),et(u,!0),H&&Z){const oe=()=>{u.subTree=On(u),Z(H,u.subTree,u,m,null)};ee?a.type.__asyncLoader().then(()=>!u.isUnmounted&&oe()):oe()}else{const oe=u.subTree=On(u);N(null,oe,g,y,u,m,w),a.el=oe.el}if(V&&ie(V,m),!ee&&(O=L&&L.onVnodeMounted)){const oe=a;ie(()=>Ee(O,Y,oe),m)}(a.shapeFlag&256||Y&&Lt(Y.vnode)&&Y.vnode.shapeFlag&256)&&u.a&&ie(u.a,m),u.isMounted=!0,a=g=y=null}},R=u.effect=new cs(x,be,()=>_s(v),u.scope),v=u.update=()=>{R.dirty&&R.run()};v.id=u.uid,et(u,!0),v()},Q=(u,a,g)=>{a.component=u;const y=u.vnode.props;u.vnode=a,u.next=null,fl(u,a.props,y,g),hl(u,a.children,g),lt(),Ns(u),ct()},q=(u,a,g,y,m,w,C,x,R=!1)=>{const v=u&&u.children,O=u?u.shapeFlag:0,H=a.children,{patchFlag:L,shapeFlag:B}=a;if(L>0){if(L&128){Ke(v,H,g,y,m,w,C,x,R);return}else if(L&256){Ne(v,H,g,y,m,w,C,x,R);return}}B&8?(O&16&&fe(v,m,w),H!==v&&f(g,H)):O&16?B&16?Ke(v,H,g,y,m,w,C,x,R):fe(v,m,w,!0):(O&8&&f(g,""),B&16&&se(H,g,y,m,w,C,x,R))},Ne=(u,a,g,y,m,w,C,x,R)=>{u=u||gt,a=a||gt;const v=u.length,O=a.length,H=Math.min(v,O);let L;for(L=0;LO?fe(u,m,w,!0,!1,H):se(a,g,y,m,w,C,x,R,H)},Ke=(u,a,g,y,m,w,C,x,R)=>{let v=0;const O=a.length;let H=u.length-1,L=O-1;for(;v<=H&&v<=L;){const B=u[v],V=a[v]=R?We(a[v]):Me(a[v]);if(ht(B,V))N(B,V,g,null,m,w,C,x,R);else break;v++}for(;v<=H&&v<=L;){const B=u[H],V=a[L]=R?We(a[L]):Me(a[L]);if(ht(B,V))N(B,V,g,null,m,w,C,x,R);else break;H--,L--}if(v>H){if(v<=L){const B=L+1,V=BL)for(;v<=H;)ge(u[v],m,w,!0),v++;else{const B=v,V=v,Y=new Map;for(v=V;v<=L;v++){const ye=a[v]=R?We(a[v]):Me(a[v]);ye.key!=null&&Y.set(ye.key,v)}let ee,oe=0;const xe=L-V+1;let dt=!1,Rs=0;const Ct=new Array(xe);for(v=0;v=xe){ge(ye,m,w,!0);continue}let Ie;if(ye.key!=null)Ie=Y.get(ye.key);else for(ee=V;ee<=L;ee++)if(Ct[ee-V]===0&&ht(ye,a[ee])){Ie=ee;break}Ie===void 0?ge(ye,m,w,!0):(Ct[Ie-V]=v+1,Ie>=Rs?Rs=Ie:dt=!0,N(ye,a[Ie],g,null,m,w,C,x,R),oe++)}const Ss=dt?yl(Ct):gt;for(ee=Ss.length-1,v=xe-1;v>=0;v--){const ye=V+v,Ie=a[ye],Cs=ye+1{const{el:w,type:C,transition:x,children:R,shapeFlag:v}=u;if(v&6){Te(u.component.subTree,a,g,y);return}if(v&128){u.suspense.move(a,g,y);return}if(v&64){C.move(u,a,g,M);return}if(C===He){s(w,a,g);for(let H=0;Hx.enter(w),m);else{const{leave:H,delayLeave:L,afterLeave:B}=x,V=()=>s(w,a,g),Y=()=>{H(w,()=>{V(),B&&B()})};L?L(w,V,Y):Y()}else s(w,a,g)},ge=(u,a,g,y=!1,m=!1)=>{const{type:w,props:C,ref:x,children:R,dynamicChildren:v,shapeFlag:O,patchFlag:H,dirs:L}=u;if(x!=null&&Qn(x,null,g,u,!0),O&256){a.ctx.deactivate(u);return}const B=O&1&&L,V=!Lt(u);let Y;if(V&&(Y=C&&C.onVnodeBeforeUnmount)&&Ee(Y,a,u),O&6)Gt(u.component,g,y);else{if(O&128){u.suspense.unmount(g,y);return}B&&Ze(u,null,a,"beforeUnmount"),O&64?u.type.remove(u,a,g,m,M,y):v&&(w!==He||H>0&&H&64)?fe(v,a,g,!1,!0):(w===He&&H&384||!m&&O&16)&&fe(R,a,g),y&&ft(u)}(V&&(Y=C&&C.onVnodeUnmounted)||B)&&ie(()=>{Y&&Ee(Y,a,u),B&&Ze(u,null,a,"unmounted")},g)},ft=u=>{const{type:a,el:g,anchor:y,transition:m}=u;if(a===He){at(g,y);return}if(a===Ln){T(u);return}const w=()=>{r(g),m&&!m.persisted&&m.afterLeave&&m.afterLeave()};if(u.shapeFlag&1&&m&&!m.persisted){const{leave:C,delayLeave:x}=m,R=()=>C(g,w);x?x(u.el,w,R):R()}else w()},at=(u,a)=>{let g;for(;u!==a;)g=p(u),r(u),u=g;r(a)},Gt=(u,a,g)=>{const{bum:y,scope:m,update:w,subTree:C,um:x}=u;y&&Mt(y),m.stop(),w&&(w.active=!1,ge(C,u,a,g)),x&&ie(x,a),ie(()=>{u.isUnmounted=!0},a),a&&a.pendingBranch&&!a.isUnmounted&&u.asyncDep&&!u.asyncResolved&&u.suspenseId===a.pendingId&&(a.deps--,a.deps===0&&a.resolve())},fe=(u,a,g,y=!1,m=!1,w=0)=>{for(let C=w;Cu.shapeFlag&6?_(u.component.subTree):u.shapeFlag&128?u.suspense.next():p(u.anchor||u.el);let A=!1;const S=(u,a,g)=>{u==null?a._vnode&&ge(a._vnode,null,null,!0):N(a._vnode||null,u,a,null,null,null,g),A||(A=!0,Ns(),Zr(),A=!1),a._vnode=u},M={p:N,um:ge,m:Te,r:ft,mt:St,mc:se,pc:q,pbc:ue,n:_,o:e};let z,Z;return t&&([z,Z]=t(M)),{render:S,hydrate:z,createApp:cl(S,z)}}function Fn({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function et({effect:e,update:t},n){e.allowRecurse=t.allowRecurse=n}function _l(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function wo(e,t,n=!1){const s=e.children,r=t.children;if(k(s)&&k(r))for(let o=0;o>1,e[n[c]]0&&(t[s]=n[o-1]),n[o]=s)}}for(o=n.length,i=n[o-1];o-- >0;)n[o]=i,i=t[i];return n}function Ro(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:Ro(t)}const bl=e=>e.__isTeleport,He=Symbol.for("v-fgt"),xn=Symbol.for("v-txt"),ot=Symbol.for("v-cmt"),Ln=Symbol.for("v-stc"),Ht=[];let Se=null;function So(e=!1){Ht.push(Se=e?null:[])}function vl(){Ht.pop(),Se=Ht[Ht.length-1]||null}let Ut=1;function zs(e){Ut+=e}function Co(e){return e.dynamicChildren=Ut>0?Se||gt:null,vl(),Ut>0&&Se&&Se.push(e),e}function El(e,t,n,s,r,o){return Co(Ge(e,t,n,s,r,o,!0))}function xl(e,t,n,s,r){return Co(pe(e,t,n,s,r,!0))}function fn(e){return e?e.__v_isVNode===!0:!1}function ht(e,t){return e.type===t.type&&e.key===t.key}const wn="__vInternal",Po=({key:e})=>e!=null?e:null,sn=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?ne(e)||_e(e)||K(e)?{i:he,r:e,k:t,f:!!n}:e:null);function Ge(e,t=null,n=null,s=0,r=null,o=e===He?0:1,i=!1,c=!1){const l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Po(t),ref:t&&sn(t),scopeId:vn,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetAnchor:null,staticCount:0,shapeFlag:o,patchFlag:s,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:he};return c?(vs(l,n),o&128&&e.normalize(l)):n&&(l.shapeFlag|=ne(n)?8:16),Ut>0&&!i&&Se&&(l.patchFlag>0||o&6)&&l.patchFlag!==32&&Se.push(l),l}const pe=wl;function wl(e,t=null,n=null,s=0,r=null,o=!1){if((!e||e===ki)&&(e=ot),fn(e)){const c=it(e,t,!0);return n&&vs(c,n),Ut>0&&!o&&Se&&(c.shapeFlag&6?Se[Se.indexOf(e)]=c:Se.push(c)),c.patchFlag|=-2,c}if(Ll(e)&&(e=e.__vccOpts),t){t=Rl(t);let{class:c,style:l}=t;c&&!ne(c)&&(t.class=ls(c)),te(l)&&(Dr(l)&&!k(l)&&(l=ce({},l)),t.style=is(l))}const i=ne(e)?1:ro(e)?128:bl(e)?64:te(e)?4:K(e)?2:0;return Ge(e,t,n,s,r,i,o,!0)}function Rl(e){return e?Dr(e)||wn in e?ce({},e):e:null}function it(e,t,n=!1){const{props:s,ref:r,patchFlag:o,children:i}=e,c=t?Sl(s||{},t):s;return{__v_isVNode:!0,__v_skip:!0,type:e.type,props:c,key:c&&Po(c),ref:t&&t.ref?n&&r?k(r)?r.concat(sn(t)):[r,sn(t)]:sn(t):r,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:i,target:e.target,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==He?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:e.transition,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&it(e.ssContent),ssFallback:e.ssFallback&&it(e.ssFallback),el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce}}function Ao(e=" ",t=0){return pe(xn,null,e,t)}function Iu(e="",t=!1){return t?(So(),xl(ot,null,e)):pe(ot,null,e)}function Me(e){return e==null||typeof e=="boolean"?pe(ot):k(e)?pe(He,null,e.slice()):typeof e=="object"?We(e):pe(xn,null,String(e))}function We(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:it(e)}function vs(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(k(t))n=16;else if(typeof t=="object")if(s&65){const r=t.default;r&&(r._c&&(r._d=!1),vs(e,r()),r._c&&(r._d=!0));return}else{n=32;const r=t._;!r&&!(wn in t)?t._ctx=he:r===3&&he&&(he.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else K(t)?(t={default:t,_ctx:he},n=32):(t=String(t),s&64?(n=16,t=[Ao(t)]):n=8);e.children=t,e.shapeFlag|=n}function Sl(...e){const t={};for(let n=0;nle||he;let an,Yn;{const e=os(),t=(n,s)=>{let r;return(r=e[n])||(r=e[n]=[]),r.push(s),o=>{r.length>1?r.forEach(i=>i(o)):r[0](o)}};an=t("__VUE_INSTANCE_SETTERS__",n=>le=n),Yn=t("__VUE_SSR_SETTERS__",n=>Rn=n)}const zt=e=>{const t=le;return an(e),e.scope.on(),()=>{e.scope.off(),an(t)}},Gs=()=>{le&&le.scope.off(),an(null)};function Oo(e){return e.vnode.shapeFlag&4}let Rn=!1;function Tl(e,t=!1){t&&Yn(t);const{props:n,children:s}=e.vnode,r=Oo(e);ul(e,n,r,t),dl(e,s);const o=r?Il(e,t):void 0;return t&&Yn(!1),o}function Il(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=ps(new Proxy(e.ctx,tl));const{setup:s}=n;if(s){const r=e.setupContext=s.length>1?Fl(e):null,o=zt(e);lt();const i=Ye(s,e,0,[e.props,r]);if(ct(),o(),Sr(i)){if(i.then(Gs,Gs),t)return i.then(c=>{Qs(e,c,t)}).catch(c=>{yn(c,e,0)});e.asyncDep=i}else Qs(e,i,t)}else To(e,t)}function Qs(e,t,n){K(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:te(t)&&(e.setupState=Qr(t)),To(e,n)}let Ys;function To(e,t,n){const s=e.type;if(!e.render){if(!t&&Ys&&!s.render){const r=s.template||ys(e).template;if(r){const{isCustomElement:o,compilerOptions:i}=e.appContext.config,{delimiters:c,compilerOptions:l}=s,d=ce(ce({isCustomElement:o,delimiters:c},i),l);s.render=Ys(r,d)}}e.render=s.render||be}{const r=zt(e);lt();try{nl(e)}finally{ct(),r()}}}function Ml(e){return e.attrsProxy||(e.attrsProxy=new Proxy(e.attrs,{get(t,n){return me(e,"get","$attrs"),t[n]}}))}function Fl(e){const t=n=>{e.exposed=n||{}};return{get attrs(){return Ml(e)},slots:e.slots,emit:e.emit,expose:t}}function Sn(e){if(e.exposed)return e.exposeProxy||(e.exposeProxy=new Proxy(Qr(ps(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Nt)return Nt[n](e)},has(t,n){return n in t||n in Nt}}))}function Jn(e,t=!0){return K(e)?e.displayName||e.name:e.name||t&&e.__name}function Ll(e){return K(e)&&"__vccOpts"in e}const Re=(e,t)=>Si(e,t,Rn);function Io(e,t,n){const s=arguments.length;return s===2?te(t)&&!k(t)?fn(t)?pe(e,null,[t]):pe(e,t):pe(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&fn(n)&&(n=[n]),pe(e,t,n))}const Nl="3.4.20";/** +* @vue/runtime-dom v3.4.20 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/const $l="http://www.w3.org/2000/svg",Hl="http://www.w3.org/1998/Math/MathML",qe=typeof document<"u"?document:null,Js=qe&&qe.createElement("template"),jl={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const r=t==="svg"?qe.createElementNS($l,e):t==="mathml"?qe.createElementNS(Hl,e):qe.createElement(e,n?{is:n}:void 0);return e==="select"&&s&&s.multiple!=null&&r.setAttribute("multiple",s.multiple),r},createText:e=>qe.createTextNode(e),createComment:e=>qe.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>qe.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,r,o){const i=n?n.previousSibling:t.lastChild;if(r&&(r===o||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),n),!(r===o||!(r=r.nextSibling)););else{Js.innerHTML=s==="svg"?`${e}`:s==="mathml"?`${e}`:e;const c=Js.content;if(s==="svg"||s==="mathml"){const l=c.firstChild;for(;l.firstChild;)c.appendChild(l.firstChild);c.removeChild(l)}t.insertBefore(c,n)}return[i?i.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},kl=Symbol("_vtc");function Bl(e,t,n){const s=e[kl];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const dn=Symbol("_vod"),Mo=Symbol("_vsh"),Mu={beforeMount(e,{value:t},{transition:n}){e[dn]=e.style.display==="none"?"":e.style.display,n&&t?n.beforeEnter(e):Pt(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:s}){!t!=!n&&(s?t?(s.beforeEnter(e),Pt(e,!0),s.enter(e)):s.leave(e,()=>{Pt(e,!1)}):Pt(e,t))},beforeUnmount(e,{value:t}){Pt(e,t)}};function Pt(e,t){e.style.display=t?e[dn]:"none",e[Mo]=!t}const Kl=Symbol(""),Vl=/(^|;)\s*display\s*:/;function Ul(e,t,n){const s=e.style,r=ne(n);let o=!1;if(n&&!r){if(t)if(ne(t))for(const i of t.split(";")){const c=i.slice(0,i.indexOf(":")).trim();n[c]==null&&rn(s,c,"")}else for(const i in t)n[i]==null&&rn(s,i,"");for(const i in n)i==="display"&&(o=!0),rn(s,i,n[i])}else if(r){if(t!==n){const i=s[Kl];i&&(n+=";"+i),s.cssText=n,o=Vl.test(n)}}else t&&e.removeAttribute("style");dn in e&&(e[dn]=o?s.display:"",e[Mo]&&(s.display="none"))}const Xs=/\s*!important$/;function rn(e,t,n){if(k(n))n.forEach(s=>rn(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))e.setProperty(t,n);else{const s=Dl(e,t);Xs.test(n)?e.setProperty(Rt(s),n.replace(Xs,""),"important"):e[s]=n}}const Zs=["Webkit","Moz","ms"],Nn={};function Dl(e,t){const n=Nn[t];if(n)return n;let s=Le(t);if(s!=="filter"&&s in e)return Nn[t]=s;s=gn(s);for(let r=0;r$n||(Jl.then(()=>$n=0),$n=Date.now());function Zl(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;Ce(ec(s,n.value),t,5,[s])};return n.value=e,n.attached=Xl(),n}function ec(e,t){if(k(t)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},t.map(s=>r=>!r._stopped&&s&&s(r))}else return t}const sr=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,tc=(e,t,n,s,r,o,i,c,l)=>{const d=r==="svg";t==="class"?Bl(e,s,d):t==="style"?Ul(e,n,s):hn(t)?ns(t)||Ql(e,t,n,s,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):nc(e,t,s,d))?ql(e,t,s,o,i,c,l):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),Wl(e,t,s,d))};function nc(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&sr(t)&&K(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return sr(t)&&ne(n)?!1:t in e}const sc=["ctrl","shift","alt","meta"],rc={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>sc.some(n=>e[`${n}Key`]&&!t.includes(n))},Fu=(e,t)=>{const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=(r,...o)=>{for(let i=0;i{const t=ic().createApp(...e),{mount:n}=t;return t.mount=s=>{const r=uc(s);if(!r)return;const o=t._component;!K(o)&&!o.render&&!o.template&&(o.template=r.innerHTML),r.innerHTML="";const i=n(r,!1,cc(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),i},t};function cc(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function uc(e){return ne(e)?document.querySelector(e):e}var fc=!1;/*! + * pinia v2.1.7 + * (c) 2023 Eduardo San Martin Morote + * @license MIT + */const ac=Symbol();var or;(function(e){e.direct="direct",e.patchObject="patch object",e.patchFunction="patch function"})(or||(or={}));function dc(){const e=si(!0),t=e.run(()=>zr({}));let n=[],s=[];const r=ps({install(o){r._a=o,o.provide(ac,r),o.config.globalProperties.$pinia=r,s.forEach(i=>n.push(i)),s=[]},use(o){return!this._a&&!fc?s.push(o):n.push(o),this},_p:n,_a:null,_e:e,_s:new Map,state:t});return r}const hc=(e,t)=>{const n=e.__vccOpts||e;for(const[s,r]of t)n[s]=r;return n},pc={},gc={class:"site-container"},mc=Ge("footer",null,[Ge("a",{href:"https://twitter.com/ngohquocbao1010",target:"_blank",class:"twitter"}," @NgoQuocBao "),Ge("a",{href:"https://github.com/NgoQuocBao1010/Exercise-Correction",target:"_blank",class:"github"},[Ge("i",{class:"fa-brands fa-github"})])],-1);function _c(e,t){const n=Hs("RouterLink"),s=Hs("RouterView");return So(),El("div",gc,[Ge("nav",null,[pe(n,{to:{name:"Home"},class:"nav__header"},{default:no(()=>[Ao(" Exercise Correction ")]),_:1})]),Ge("main",null,[pe(s)]),mc])}const yc=hc(pc,[["render",_c]]),bc="modulepreload",vc=function(e){return"/"+e},ir={},lr=function(t,n,s){if(!n||n.length===0)return t();const r=document.getElementsByTagName("link");return Promise.all(n.map(o=>{if(o=vc(o),o in ir)return;ir[o]=!0;const i=o.endsWith(".css"),c=i?'[rel="stylesheet"]':"";if(!!s)for(let f=r.length-1;f>=0;f--){const h=r[f];if(h.href===o&&(!i||h.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${o}"]${c}`))return;const d=document.createElement("link");if(d.rel=i?"stylesheet":bc,i||(d.as="script",d.crossOrigin=""),d.href=o,document.head.appendChild(d),i)return new Promise((f,h)=>{d.addEventListener("load",f),d.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${o}`)))})})).then(()=>t())};/*! + * vue-router v4.3.0 + * (c) 2024 Eduardo San Martin Morote + * @license MIT + */const pt=typeof document<"u";function Ec(e){return e.__esModule||e[Symbol.toStringTag]==="Module"}const G=Object.assign;function Hn(e,t){const n={};for(const s in t){const r=t[s];n[s]=Pe(r)?r.map(e):e(r)}return n}const jt=()=>{},Pe=Array.isArray,Fo=/#/g,xc=/&/g,wc=/\//g,Rc=/=/g,Sc=/\?/g,Lo=/\+/g,Cc=/%5B/g,Pc=/%5D/g,No=/%5E/g,Ac=/%60/g,$o=/%7B/g,Oc=/%7C/g,Ho=/%7D/g,Tc=/%20/g;function Es(e){return encodeURI(""+e).replace(Oc,"|").replace(Cc,"[").replace(Pc,"]")}function Ic(e){return Es(e).replace($o,"{").replace(Ho,"}").replace(No,"^")}function Xn(e){return Es(e).replace(Lo,"%2B").replace(Tc,"+").replace(Fo,"%23").replace(xc,"%26").replace(Ac,"`").replace($o,"{").replace(Ho,"}").replace(No,"^")}function Mc(e){return Xn(e).replace(Rc,"%3D")}function Fc(e){return Es(e).replace(Fo,"%23").replace(Sc,"%3F")}function Lc(e){return e==null?"":Fc(e).replace(wc,"%2F")}function Dt(e){try{return decodeURIComponent(""+e)}catch{}return""+e}const Nc=/\/$/,$c=e=>e.replace(Nc,"");function jn(e,t,n="/"){let s,r={},o="",i="";const c=t.indexOf("#");let l=t.indexOf("?");return c=0&&(l=-1),l>-1&&(s=t.slice(0,l),o=t.slice(l+1,c>-1?c:t.length),r=e(o)),c>-1&&(s=s||t.slice(0,c),i=t.slice(c,t.length)),s=Bc(s!=null?s:t,n),{fullPath:s+(o&&"?")+o+i,path:s,query:r,hash:Dt(i)}}function Hc(e,t){const n=t.query?e(t.query):"";return t.path+(n&&"?")+n+(t.hash||"")}function cr(e,t){return!t||!e.toLowerCase().startsWith(t.toLowerCase())?e:e.slice(t.length)||"/"}function jc(e,t,n){const s=t.matched.length-1,r=n.matched.length-1;return s>-1&&s===r&&Et(t.matched[s],n.matched[r])&&jo(t.params,n.params)&&e(t.query)===e(n.query)&&t.hash===n.hash}function Et(e,t){return(e.aliasOf||e)===(t.aliasOf||t)}function jo(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(!kc(e[n],t[n]))return!1;return!0}function kc(e,t){return Pe(e)?ur(e,t):Pe(t)?ur(t,e):e===t}function ur(e,t){return Pe(t)?e.length===t.length&&e.every((n,s)=>n===t[s]):e.length===1&&e[0]===t}function Bc(e,t){if(e.startsWith("/"))return e;if(!e)return t;const n=t.split("/"),s=e.split("/"),r=s[s.length-1];(r===".."||r===".")&&s.push("");let o=n.length-1,i,c;for(i=0;i1&&o--;else break;return n.slice(0,o).join("/")+"/"+s.slice(i).join("/")}var Wt;(function(e){e.pop="pop",e.push="push"})(Wt||(Wt={}));var kt;(function(e){e.back="back",e.forward="forward",e.unknown=""})(kt||(kt={}));function Kc(e){if(!e)if(pt){const t=document.querySelector("base");e=t&&t.getAttribute("href")||"/",e=e.replace(/^\w+:\/\/[^\/]+/,"")}else e="/";return e[0]!=="/"&&e[0]!=="#"&&(e="/"+e),$c(e)}const Vc=/^[^#]+#/;function Uc(e,t){return e.replace(Vc,"#")+t}function Dc(e,t){const n=document.documentElement.getBoundingClientRect(),s=e.getBoundingClientRect();return{behavior:t.behavior,left:s.left-n.left-(t.left||0),top:s.top-n.top-(t.top||0)}}const Cn=()=>({left:window.scrollX,top:window.scrollY});function Wc(e){let t;if("el"in e){const n=e.el,s=typeof n=="string"&&n.startsWith("#"),r=typeof n=="string"?s?document.getElementById(n.slice(1)):document.querySelector(n):n;if(!r)return;t=Dc(r,e)}else t=e;"scrollBehavior"in document.documentElement.style?window.scrollTo(t):window.scrollTo(t.left!=null?t.left:window.scrollX,t.top!=null?t.top:window.scrollY)}function fr(e,t){return(history.state?history.state.position-t:-1)+e}const Zn=new Map;function qc(e,t){Zn.set(e,t)}function zc(e){const t=Zn.get(e);return Zn.delete(e),t}let Gc=()=>location.protocol+"//"+location.host;function ko(e,t){const{pathname:n,search:s,hash:r}=t,o=e.indexOf("#");if(o>-1){let c=r.includes(e.slice(o))?e.slice(o).length:1,l=r.slice(c);return l[0]!=="/"&&(l="/"+l),cr(l,"")}return cr(n,e)+s+r}function Qc(e,t,n,s){let r=[],o=[],i=null;const c=({state:p})=>{const b=ko(e,location),I=n.value,N=t.value;let j=0;if(p){if(n.value=b,t.value=p,i&&i===I){i=null;return}j=N?p.position-N.position:0}else s(b);r.forEach(F=>{F(n.value,I,{delta:j,type:Wt.pop,direction:j?j>0?kt.forward:kt.back:kt.unknown})})};function l(){i=n.value}function d(p){r.push(p);const b=()=>{const I=r.indexOf(p);I>-1&&r.splice(I,1)};return o.push(b),b}function f(){const{history:p}=window;!p.state||p.replaceState(G({},p.state,{scroll:Cn()}),"")}function h(){for(const p of o)p();o=[],window.removeEventListener("popstate",c),window.removeEventListener("beforeunload",f)}return window.addEventListener("popstate",c),window.addEventListener("beforeunload",f,{passive:!0}),{pauseListeners:l,listen:d,destroy:h}}function ar(e,t,n,s=!1,r=!1){return{back:e,current:t,forward:n,replaced:s,position:window.history.length,scroll:r?Cn():null}}function Yc(e){const{history:t,location:n}=window,s={value:ko(e,n)},r={value:t.state};r.value||o(s.value,{back:null,current:s.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0);function o(l,d,f){const h=e.indexOf("#"),p=h>-1?(n.host&&document.querySelector("base")?e:e.slice(h))+l:Gc()+e+l;try{t[f?"replaceState":"pushState"](d,"",p),r.value=d}catch(b){console.error(b),n[f?"replace":"assign"](p)}}function i(l,d){const f=G({},t.state,ar(r.value.back,l,r.value.forward,!0),d,{position:r.value.position});o(l,f,!0),s.value=l}function c(l,d){const f=G({},r.value,t.state,{forward:l,scroll:Cn()});o(f.current,f,!0);const h=G({},ar(s.value,l,null),{position:f.position+1},d);o(l,h,!1),s.value=l}return{location:s,state:r,push:c,replace:i}}function Jc(e){e=Kc(e);const t=Yc(e),n=Qc(e,t.state,t.location,t.replace);function s(o,i=!0){i||n.pauseListeners(),history.go(o)}const r=G({location:"",base:e,go:s,createHref:Uc.bind(null,e)},t,n);return Object.defineProperty(r,"location",{enumerable:!0,get:()=>t.location.value}),Object.defineProperty(r,"state",{enumerable:!0,get:()=>t.state.value}),r}function Xc(e){return typeof e=="string"||e&&typeof e=="object"}function Bo(e){return typeof e=="string"||typeof e=="symbol"}const Ue={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0},Ko=Symbol("");var dr;(function(e){e[e.aborted=4]="aborted",e[e.cancelled=8]="cancelled",e[e.duplicated=16]="duplicated"})(dr||(dr={}));function xt(e,t){return G(new Error,{type:e,[Ko]:!0},t)}function $e(e,t){return e instanceof Error&&Ko in e&&(t==null||!!(e.type&t))}const hr="[^/]+?",Zc={sensitive:!1,strict:!1,start:!0,end:!0},eu=/[.+*?^${}()[\]/\\]/g;function tu(e,t){const n=G({},Zc,t),s=[];let r=n.start?"^":"";const o=[];for(const d of e){const f=d.length?[]:[90];n.strict&&!d.length&&(r+="/");for(let h=0;ht.length?t.length===1&&t[0]===40+40?1:-1:0}function su(e,t){let n=0;const s=e.score,r=t.score;for(;n0&&t[t.length-1]<0}const ru={type:0,value:""},ou=/[a-zA-Z0-9_]/;function iu(e){if(!e)return[[]];if(e==="/")return[[ru]];if(!e.startsWith("/"))throw new Error(`Invalid path "${e}"`);function t(b){throw new Error(`ERR (${n})/"${d}": ${b}`)}let n=0,s=n;const r=[];let o;function i(){o&&r.push(o),o=[]}let c=0,l,d="",f="";function h(){!d||(n===0?o.push({type:0,value:d}):n===1||n===2||n===3?(o.length>1&&(l==="*"||l==="+")&&t(`A repeatable param (${d}) must be alone in its segment. eg: '/:ids+.`),o.push({type:1,value:d,regexp:f,repeatable:l==="*"||l==="+",optional:l==="*"||l==="?"})):t("Invalid state to consume buffer"),d="")}function p(){d+=l}for(;c{i(E)}:jt}function i(f){if(Bo(f)){const h=s.get(f);h&&(s.delete(f),n.splice(n.indexOf(h),1),h.children.forEach(i),h.alias.forEach(i))}else{const h=n.indexOf(f);h>-1&&(n.splice(h,1),f.record.name&&s.delete(f.record.name),f.children.forEach(i),f.alias.forEach(i))}}function c(){return n}function l(f){let h=0;for(;h=0&&(f.record.path!==n[h].record.path||!Vo(f,n[h]));)h++;n.splice(h,0,f),f.record.name&&!mr(f)&&s.set(f.record.name,f)}function d(f,h){let p,b={},I,N;if("name"in f&&f.name){if(p=s.get(f.name),!p)throw xt(1,{location:f});N=p.record.name,b=G(gr(h.params,p.keys.filter(E=>!E.optional).concat(p.parent?p.parent.keys.filter(E=>E.optional):[]).map(E=>E.name)),f.params&&gr(f.params,p.keys.map(E=>E.name))),I=p.stringify(b)}else if(f.path!=null)I=f.path,p=n.find(E=>E.re.test(I)),p&&(b=p.parse(I),N=p.record.name);else{if(p=h.name?s.get(h.name):n.find(E=>E.re.test(h.path)),!p)throw xt(1,{location:f,currentLocation:h});N=p.record.name,b=G({},h.params,f.params),I=p.stringify(b)}const j=[];let F=p;for(;F;)j.unshift(F.record),F=F.parent;return{name:N,path:I,params:b,matched:j,meta:au(j)}}return e.forEach(f=>o(f)),{addRoute:o,resolve:d,removeRoute:i,getRoutes:c,getRecordMatcher:r}}function gr(e,t){const n={};for(const s of t)s in e&&(n[s]=e[s]);return n}function uu(e){return{path:e.path,redirect:e.redirect,name:e.name,meta:e.meta||{},aliasOf:void 0,beforeEnter:e.beforeEnter,props:fu(e),children:e.children||[],instances:{},leaveGuards:new Set,updateGuards:new Set,enterCallbacks:{},components:"components"in e?e.components||null:e.component&&{default:e.component}}}function fu(e){const t={},n=e.props||!1;if("component"in e)t.default=n;else for(const s in e.components)t[s]=typeof n=="object"?n[s]:n;return t}function mr(e){for(;e;){if(e.record.aliasOf)return!0;e=e.parent}return!1}function au(e){return e.reduce((t,n)=>G(t,n.meta),{})}function _r(e,t){const n={};for(const s in e)n[s]=s in t?t[s]:e[s];return n}function Vo(e,t){return t.children.some(n=>n===e||Vo(e,n))}function du(e){const t={};if(e===""||e==="?")return t;const s=(e[0]==="?"?e.slice(1):e).split("&");for(let r=0;ro&&Xn(o)):[s&&Xn(s)]).forEach(o=>{o!==void 0&&(t+=(t.length?"&":"")+n,o!=null&&(t+="="+o))})}return t}function hu(e){const t={};for(const n in e){const s=e[n];s!==void 0&&(t[n]=Pe(s)?s.map(r=>r==null?null:""+r):s==null?s:""+s)}return t}const pu=Symbol(""),br=Symbol(""),xs=Symbol(""),Uo=Symbol(""),es=Symbol("");function At(){let e=[];function t(s){return e.push(s),()=>{const r=e.indexOf(s);r>-1&&e.splice(r,1)}}function n(){e=[]}return{add:t,list:()=>e.slice(),reset:n}}function ze(e,t,n,s,r,o=i=>i()){const i=s&&(s.enterCallbacks[r]=s.enterCallbacks[r]||[]);return()=>new Promise((c,l)=>{const d=p=>{p===!1?l(xt(4,{from:n,to:t})):p instanceof Error?l(p):Xc(p)?l(xt(2,{from:t,to:p})):(i&&s.enterCallbacks[r]===i&&typeof p=="function"&&i.push(p),c())},f=o(()=>e.call(s&&s.instances[r],t,n,d));let h=Promise.resolve(f);e.length<3&&(h=h.then(d)),h.catch(p=>l(p))})}function kn(e,t,n,s,r=o=>o()){const o=[];for(const i of e)for(const c in i.components){let l=i.components[c];if(!(t!=="beforeRouteEnter"&&!i.instances[c]))if(gu(l)){const f=(l.__vccOpts||l)[t];f&&o.push(ze(f,n,s,i,c,r))}else{let d=l();o.push(()=>d.then(f=>{if(!f)return Promise.reject(new Error(`Couldn't resolve component "${c}" at "${i.path}"`));const h=Ec(f)?f.default:f;i.components[c]=h;const b=(h.__vccOpts||h)[t];return b&&ze(b,n,s,i,c,r)()}))}}return o}function gu(e){return typeof e=="object"||"displayName"in e||"props"in e||"__vccOpts"in e}function vr(e){const t=ke(xs),n=ke(Uo),s=Re(()=>t.resolve(yt(e.to))),r=Re(()=>{const{matched:l}=s.value,{length:d}=l,f=l[d-1],h=n.matched;if(!f||!h.length)return-1;const p=h.findIndex(Et.bind(null,f));if(p>-1)return p;const b=Er(l[d-2]);return d>1&&Er(f)===b&&h[h.length-1].path!==b?h.findIndex(Et.bind(null,l[d-2])):p}),o=Re(()=>r.value>-1&&bu(n.params,s.value.params)),i=Re(()=>r.value>-1&&r.value===n.matched.length-1&&jo(n.params,s.value.params));function c(l={}){return yu(l)?t[yt(e.replace)?"replace":"push"](yt(e.to)).catch(jt):Promise.resolve()}return{route:s,href:Re(()=>s.value.href),isActive:o,isExactActive:i,navigate:c}}const mu=co({name:"RouterLink",compatConfig:{MODE:3},props:{to:{type:[String,Object],required:!0},replace:Boolean,activeClass:String,exactActiveClass:String,custom:Boolean,ariaCurrentValue:{type:String,default:"page"}},useLink:vr,setup(e,{slots:t}){const n=_n(vr(e)),{options:s}=ke(xs),r=Re(()=>({[xr(e.activeClass,s.linkActiveClass,"router-link-active")]:n.isActive,[xr(e.exactActiveClass,s.linkExactActiveClass,"router-link-exact-active")]:n.isExactActive}));return()=>{const o=t.default&&t.default(n);return e.custom?o:Io("a",{"aria-current":n.isExactActive?e.ariaCurrentValue:null,href:n.href,onClick:n.navigate,class:r.value},o)}}}),_u=mu;function yu(e){if(!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)&&!e.defaultPrevented&&!(e.button!==void 0&&e.button!==0)){if(e.currentTarget&&e.currentTarget.getAttribute){const t=e.currentTarget.getAttribute("target");if(/\b_blank\b/i.test(t))return}return e.preventDefault&&e.preventDefault(),!0}}function bu(e,t){for(const n in t){const s=t[n],r=e[n];if(typeof s=="string"){if(s!==r)return!1}else if(!Pe(r)||r.length!==s.length||s.some((o,i)=>o!==r[i]))return!1}return!0}function Er(e){return e?e.aliasOf?e.aliasOf.path:e.path:""}const xr=(e,t,n)=>e!=null?e:t!=null?t:n,vu=co({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(e,{attrs:t,slots:n}){const s=ke(es),r=Re(()=>e.route||s.value),o=ke(br,0),i=Re(()=>{let d=yt(o);const{matched:f}=r.value;let h;for(;(h=f[d])&&!h.components;)d++;return d}),c=Re(()=>r.value.matched[i.value]);nn(br,Re(()=>i.value+1)),nn(pu,c),nn(es,r);const l=zr();return Ft(()=>[l.value,c.value,e.name],([d,f,h],[p,b,I])=>{f&&(f.instances[h]=d,b&&b!==f&&d&&d===p&&(f.leaveGuards.size||(f.leaveGuards=b.leaveGuards),f.updateGuards.size||(f.updateGuards=b.updateGuards))),d&&f&&(!b||!Et(f,b)||!p)&&(f.enterCallbacks[h]||[]).forEach(N=>N(d))},{flush:"post"}),()=>{const d=r.value,f=e.name,h=c.value,p=h&&h.components[f];if(!p)return wr(n.default,{Component:p,route:d});const b=h.props[f],I=b?b===!0?d.params:typeof b=="function"?b(d):b:null,j=Io(p,G({},I,t,{onVnodeUnmounted:F=>{F.component.isUnmounted&&(h.instances[f]=null)},ref:l}));return wr(n.default,{Component:j,route:d})||j}}});function wr(e,t){if(!e)return null;const n=e(t);return n.length===1?n[0]:n}const Eu=vu;function xu(e){const t=cu(e.routes,e),n=e.parseQuery||du,s=e.stringifyQuery||yr,r=e.history,o=At(),i=At(),c=At(),l=Ci(Ue);let d=Ue;pt&&e.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const f=Hn.bind(null,_=>""+_),h=Hn.bind(null,Lc),p=Hn.bind(null,Dt);function b(_,A){let S,M;return Bo(_)?(S=t.getRecordMatcher(_),M=A):M=_,t.addRoute(M,S)}function I(_){const A=t.getRecordMatcher(_);A&&t.removeRoute(A)}function N(){return t.getRoutes().map(_=>_.record)}function j(_){return!!t.getRecordMatcher(_)}function F(_,A){if(A=G({},A||l.value),typeof _=="string"){const a=jn(n,_,A.path),g=t.resolve({path:a.path},A),y=r.createHref(a.fullPath);return G(a,g,{params:p(g.params),hash:Dt(a.hash),redirectedFrom:void 0,href:y})}let S;if(_.path!=null)S=G({},_,{path:jn(n,_.path,A.path).path});else{const a=G({},_.params);for(const g in a)a[g]==null&&delete a[g];S=G({},_,{params:h(a)}),A.params=h(A.params)}const M=t.resolve(S,A),z=_.hash||"";M.params=f(p(M.params));const Z=Hc(s,G({},_,{hash:Ic(z),path:M.path})),u=r.createHref(Z);return G({fullPath:Z,hash:z,query:s===yr?hu(_.query):_.query||{}},M,{redirectedFrom:void 0,href:u})}function E(_){return typeof _=="string"?jn(n,_,l.value.path):G({},_)}function P(_,A){if(d!==_)return xt(8,{from:A,to:_})}function T(_){return J(_)}function U(_){return T(G(E(_),{replace:!0}))}function $(_){const A=_.matched[_.matched.length-1];if(A&&A.redirect){const{redirect:S}=A;let M=typeof S=="function"?S(_):S;return typeof M=="string"&&(M=M.includes("?")||M.includes("#")?M=E(M):{path:M},M.params={}),G({query:_.query,hash:_.hash,params:M.path!=null?{}:_.params},M)}}function J(_,A){const S=d=F(_),M=l.value,z=_.state,Z=_.force,u=_.replace===!0,a=$(S);if(a)return J(G(E(a),{state:typeof a=="object"?G({},z,a.state):z,force:Z,replace:u}),A||S);const g=S;g.redirectedFrom=A;let y;return!Z&&jc(s,M,S)&&(y=xt(16,{to:g,from:M}),Te(M,M,!0,!1)),(y?Promise.resolve(y):ue(g,M)).catch(m=>$e(m)?$e(m,2)?m:Ke(m):q(m,g,M)).then(m=>{if(m){if($e(m,2))return J(G({replace:u},E(m.to),{state:typeof m.to=="object"?G({},z,m.to.state):z,force:Z}),A||g)}else m=Xe(g,M,!0,u,z);return ve(g,M,m),m})}function se(_,A){const S=P(_,A);return S?Promise.reject(S):Promise.resolve()}function Ae(_){const A=at.values().next().value;return A&&typeof A.runWithContext=="function"?A.runWithContext(_):_()}function ue(_,A){let S;const[M,z,Z]=wu(_,A);S=kn(M.reverse(),"beforeRouteLeave",_,A);for(const a of M)a.leaveGuards.forEach(g=>{S.push(ze(g,_,A))});const u=se.bind(null,_,A);return S.push(u),fe(S).then(()=>{S=[];for(const a of o.list())S.push(ze(a,_,A));return S.push(u),fe(S)}).then(()=>{S=kn(z,"beforeRouteUpdate",_,A);for(const a of z)a.updateGuards.forEach(g=>{S.push(ze(g,_,A))});return S.push(u),fe(S)}).then(()=>{S=[];for(const a of Z)if(a.beforeEnter)if(Pe(a.beforeEnter))for(const g of a.beforeEnter)S.push(ze(g,_,A));else S.push(ze(a.beforeEnter,_,A));return S.push(u),fe(S)}).then(()=>(_.matched.forEach(a=>a.enterCallbacks={}),S=kn(Z,"beforeRouteEnter",_,A,Ae),S.push(u),fe(S))).then(()=>{S=[];for(const a of i.list())S.push(ze(a,_,A));return S.push(u),fe(S)}).catch(a=>$e(a,8)?a:Promise.reject(a))}function ve(_,A,S){c.list().forEach(M=>Ae(()=>M(_,A,S)))}function Xe(_,A,S,M,z){const Z=P(_,A);if(Z)return Z;const u=A===Ue,a=pt?history.state:{};S&&(M||u?r.replace(_.fullPath,G({scroll:u&&a&&a.scroll},z)):r.push(_.fullPath,z)),l.value=_,Te(_,A,S,u),Ke()}let Oe;function St(){Oe||(Oe=r.listen((_,A,S)=>{if(!Gt.listening)return;const M=F(_),z=$(M);if(z){J(G(z,{replace:!0}),M).catch(jt);return}d=M;const Z=l.value;pt&&qc(fr(Z.fullPath,S.delta),Cn()),ue(M,Z).catch(u=>$e(u,12)?u:$e(u,2)?(J(u.to,M).then(a=>{$e(a,20)&&!S.delta&&S.type===Wt.pop&&r.go(-1,!1)}).catch(jt),Promise.reject()):(S.delta&&r.go(-S.delta,!1),q(u,M,Z))).then(u=>{u=u||Xe(M,Z,!1),u&&(S.delta&&!$e(u,8)?r.go(-S.delta,!1):S.type===Wt.pop&&$e(u,20)&&r.go(-1,!1)),ve(M,Z,u)}).catch(jt)}))}let ut=At(),re=At(),Q;function q(_,A,S){Ke(_);const M=re.list();return M.length?M.forEach(z=>z(_,A,S)):console.error(_),Promise.reject(_)}function Ne(){return Q&&l.value!==Ue?Promise.resolve():new Promise((_,A)=>{ut.add([_,A])})}function Ke(_){return Q||(Q=!_,St(),ut.list().forEach(([A,S])=>_?S(_):A()),ut.reset()),_}function Te(_,A,S,M){const{scrollBehavior:z}=e;if(!pt||!z)return Promise.resolve();const Z=!S&&zc(fr(_.fullPath,0))||(M||!S)&&history.state&&history.state.scroll||null;return Jr().then(()=>z(_,A,Z)).then(u=>u&&Wc(u)).catch(u=>q(u,_,A))}const ge=_=>r.go(_);let ft;const at=new Set,Gt={currentRoute:l,listening:!0,addRoute:b,removeRoute:I,hasRoute:j,getRoutes:N,resolve:F,options:e,push:T,replace:U,go:ge,back:()=>ge(-1),forward:()=>ge(1),beforeEach:o.add,beforeResolve:i.add,afterEach:c.add,onError:re.add,isReady:Ne,install(_){const A=this;_.component("RouterLink",_u),_.component("RouterView",Eu),_.config.globalProperties.$router=A,Object.defineProperty(_.config.globalProperties,"$route",{enumerable:!0,get:()=>yt(l)}),pt&&!ft&&l.value===Ue&&(ft=!0,T(r.location).catch(z=>{}));const S={};for(const z in Ue)Object.defineProperty(S,z,{get:()=>l.value[z],enumerable:!0});_.provide(xs,A),_.provide(Uo,Vr(S)),_.provide(es,l);const M=_.unmount;at.add(_),_.unmount=function(){at.delete(_),at.size<1&&(d=Ue,Oe&&Oe(),Oe=null,l.value=Ue,ft=!1,Q=!1),M()}}};function fe(_){return _.reduce((A,S)=>A.then(()=>Ae(S)),Promise.resolve())}return Gt}function wu(e,t){const n=[],s=[],r=[],o=Math.max(t.matched.length,e.matched.length);for(let i=0;iEt(d,c))?s.push(c):n.push(c));const l=e.matched[i];l&&(t.matched.find(d=>Et(d,l))||r.push(l))}return[n,s,r]}const Ru=xu({history:Jc("/"),routes:[{path:"/",name:"Home",component:()=>lr(()=>import("./Home-338d7092.js"),["static/assets/js/Home-338d7092.js","static/css/Home-c744d067.css"])},{path:"/video",name:"VideoStreaming",component:()=>lr(()=>import("./VideoStreaming-c81ea837.js"),["static/assets/js/VideoStreaming-c81ea837.js","static/css/VideoStreaming-ff14bb10.css"])},{path:"/:pathMatch(.*)*",redirect:{name:"Home"}}]}),ws=lc(yc);ws.use(dc());ws.use(Ru);ws.mount("#app");export{He as F,Ou as K,hc as _,pe as a,Pu as b,El as c,Ge as d,zr as e,Re as f,Ft as g,Ao as h,Fu as i,ao as j,Iu as k,Tu as l,xl as m,ls as n,So as o,Cu as p,Au as q,Hs as r,Su as t,Mu as v,no as w}; diff --git a/web/client/dist/static/css/Home-c744d067.css b/web/client/dist/static/css/Home-c744d067.css new file mode 100644 index 0000000000000000000000000000000000000000..c3ae91e7559ad828407c07b4ab161c3fb8c7694b --- /dev/null +++ b/web/client/dist/static/css/Home-c744d067.css @@ -0,0 +1 @@ +.container[data-v-63b73dd0]{margin-top:10rem;width:100%;display:flex;align-items:center;justify-content:center;gap:4rem}.container .box[data-v-63b73dd0]{width:20%;max-width:200px;aspect-ratio:1/1;display:flex;justify-content:center;align-items:center;flex-direction:column;gap:1.2rem;cursor:pointer;border:4px solid var(--primary-color);border-radius:10%;box-shadow:#ffffff1a 0 1px 1px inset,#32325d40 0 50px 100px -20px,#0000004d 0 30px 60px -30px;transition:all .2s ease-in}.container .box i[data-v-63b73dd0]{font-size:3rem;color:var(--primary-color)}.container .box__description[data-v-63b73dd0]{font-size:1.2rem;font-weight:500;text-transform:uppercase;color:var(--secondary-color);transform:translateY(10px)}.container .box[data-v-63b73dd0]:hover{transform:scale(1.05)} diff --git a/web/client/dist/static/css/VideoStreaming-ff14bb10.css b/web/client/dist/static/css/VideoStreaming-ff14bb10.css new file mode 100644 index 0000000000000000000000000000000000000000..2e7550ff9ebafbe9c39731eda15df981a3272717 --- /dev/null +++ b/web/client/dist/static/css/VideoStreaming-ff14bb10.css @@ -0,0 +1 @@ +.dropzone[data-v-f95f1d7c]{display:flex;flex-direction:column;justify-content:center;align-items:center;border:.2rem dashed var(--primary-color);padding:2rem;border-radius:.25rem;background-color:#fff;font-size:1.25rem;text-align:center;transition:.25s background-color ease-in-out;cursor:pointer}.dropzone-dragging[data-v-f95f1d7c],.dropzone[data-v-f95f1d7c]:hover{background-color:#cdeddf}.dropzone-icon[data-v-f95f1d7c]{display:block;font-size:3rem;margin:0 auto 1.5rem;color:var(--primary-color)}.dropzone-input[data-v-f95f1d7c]{display:none}.dropzone[data-v-3efb54fc]{display:flex;flex-direction:column;justify-content:center;align-items:center;border:.2rem dashed var(--primary-color);padding:2rem;border-radius:.25rem;background-color:#fff;font-size:1.25rem;transition:.25s background-color ease-in-out;cursor:pointer}.dropzone-icon[data-v-3efb54fc]{display:block;font-size:3rem;margin:0 auto 1.5rem;color:var(--primary-color)}.dropzone-input[data-v-3efb54fc]{display:none}.loading-animation[data-v-3efb54fc]{display:flex;gap:1rem;margin-bottom:2rem}.loading-animation .dot[data-v-3efb54fc]{display:inline-block;width:20px;aspect-ratio:1/1;border-radius:100%;background-color:var(--primary-color)}.loading-animation .dot[data-v-3efb54fc]:nth-last-child(1){animation:loading-3efb54fc .6s .1s linear infinite}.loading-animation .dot[data-v-3efb54fc]:nth-last-child(2){animation:loading-3efb54fc .6s .2s linear infinite}.loading-animation .dot[data-v-3efb54fc]:nth-last-child(3){animation:loading-3efb54fc .6s .3s linear infinite}@keyframes loading-3efb54fc{0%{transform:translate(0)}50%{transform:translateY(15px)}to{transform:translate(0)}}video[data-v-ea1329c7]{width:100%}.result-section[data-v-e0283d6e]{margin-top:2rem;margin-bottom:5rem}.result-section .tab-links[data-v-e0283d6e]{display:flex}.result-section .tab-links li[data-v-e0283d6e]{width:6em;padding:.75rem 1.2rem .75rem 1rem;background-color:#b4b3b3;border-top-left-radius:1rem;border-top-right-radius:1rem;font-size:1rem;text-transform:uppercase;cursor:pointer;transition:all .2s ease}.result-section .tab-links li.active[data-v-e0283d6e]{background-color:var(--primary-color)}.result-section .tab-links li[data-v-e0283d6e]:hover{background-color:#41b88366}.result-section .tab-container[data-v-e0283d6e]{padding:1rem 2rem;border:3px solid var(--primary-color)}.result-section .tab-container p.main[data-v-e0283d6e]{font-size:1.5rem;margin:1rem 0}.result-section .tab-container p.main i[data-v-e0283d6e]{font-size:1.5rem}.result-section .tab-container ul.errors li[data-v-e0283d6e]{margin:.75rem 0;font-size:1.2rem;text-transform:capitalize}.result-section .tab-container ul.errors li i[data-v-e0283d6e]{margin-right:1rem}.result-section .tab-container .box-error[data-v-e0283d6e]{margin-bottom:2rem}.result-section .tab-container .box-error p[data-v-e0283d6e]{font-size:1.2rem;text-transform:capitalize;margin-bottom:.5rem}.result-section .tab-container .box-error img[data-v-e0283d6e]{width:500px}.result-section .tab-container .box-error span.error-time[data-v-e0283d6e]{color:#5595ab;cursor:pointer}.result-section .tab-container .box-error hr[data-v-e0283d6e]{background-color:var(--primary-color);color:var(--primary-color)}.result-section .tab-container .video-container[data-v-e0283d6e]{width:80%;margin-inline:auto;display:flex;justify-content:center;align-items:center}.result-section .error-color[data-v-e0283d6e]{color:red}.result-section .info-color[data-v-e0283d6e]{color:#37c237}.input-section[data-v-1253291f]{display:flex;gap:1rem}.input-section *[data-v-1253291f]{flex:1}.input-section .right-container[data-v-1253291f]{display:flex;flex-direction:column;width:100%}.input-section .right-container .exercises-container[data-v-1253291f]{display:flex;flex-wrap:wrap;gap:1rem;margin-bottom:1rem}.input-section .right-container .exercises-container .exercise[data-v-1253291f]{display:flex;justify-content:center;align-items:center;padding:1rem 0;flex:45%;color:var(--secondary-color);text-transform:uppercase;border:3px solid var(--primary-color);border-radius:.3rem;cursor:pointer;transition:all .25s ease}.input-section .right-container .exercises-container .exercise[data-v-1253291f]:hover{box-shadow:0 6px 18px #0000001a;transform:translateY(-6px)}.input-section .right-container .exercises-container .exercise.active[data-v-1253291f]{background-color:var(--primary-color);font-weight:700}.input-section .right-container .process-btn[data-v-1253291f]{border:none;background-color:var(--primary-color);padding:1.25rem 0;color:#f5f5f5;font-size:1.25rem;font-weight:700;cursor:pointer;border-radius:8px;transition:all .25s ease}.input-section .right-container .process-btn[data-v-1253291f]:hover{box-shadow:0 6px 18px #0000001a;color:var(--primary-color);border-color:transparent;background-color:transparent} diff --git a/web/client/dist/static/css/index-c3504ec7.css b/web/client/dist/static/css/index-c3504ec7.css new file mode 100644 index 0000000000000000000000000000000000000000..c68c5a7fd898b578a8ce33ce2918f65e214f545b --- /dev/null +++ b/web/client/dist/static/css/index-c3504ec7.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&family=Roboto:wght@400;700;900&display=swap";:root{--primary-color: #41b883;--primary-color-rbg: 65, 184, 131;--primary-color-text: #1e2d50;--secondary-color: #34495e;--font-family: "Poppins", sans-serif;--vn-font-family: "Roboto", sans-serif}*{font-family:var(--font-family)}html{scroll-behavior:smooth}.invisible{visibility:hidden}html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:"";content:none}table{border-collapse:collapse;border-spacing:0}a{text-decoration:none}body .site-container{min-height:100vh;display:flex;flex-direction:column}body nav{margin:3rem 0;text-align:center}body nav .nav__header{font-size:2rem;font-family:var(--font-family);font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--primary-color)}body main{margin-inline:auto;width:90vw}body footer{margin-top:auto;margin-inline:auto;width:90vw;border-top:1px solid var(--primary-color);padding:.3rem 0;text-align:center}body footer a{font-family:var(--font-family);color:var(--primary-color)}body footer .twitter{font-weight:700}body footer .github{font-size:1.2rem;margin-left:1rem} diff --git a/web/client/index.html b/web/client/index.html new file mode 100644 index 0000000000000000000000000000000000000000..2b079b73284a921f5ab2e82e2a863197946382b4 --- /dev/null +++ b/web/client/index.html @@ -0,0 +1,20 @@ + + + + + + + + Exercise Correction + + +
+ + + diff --git a/web/client/node_modules/.bin/acorn b/web/client/node_modules/.bin/acorn new file mode 100644 index 0000000000000000000000000000000000000000..dd631458a838946ee9a6abdf9780cef062956553 --- /dev/null +++ b/web/client/node_modules/.bin/acorn @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:172abb5575ef74185417e36d1df7384fb27720826054f7337bdf26efc2649526 +size 379 diff --git a/web/client/node_modules/.bin/acorn.cmd b/web/client/node_modules/.bin/acorn.cmd new file mode 100644 index 0000000000000000000000000000000000000000..cee74429405188895d24e21a5ab86964bb474a93 --- /dev/null +++ b/web/client/node_modules/.bin/acorn.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d3aecbaf5fc581a03b5d6d0358566cfb3be6babda6e0cd72a1b7b9d6c8ee21f +size 320 diff --git a/web/client/node_modules/.bin/acorn.ps1 b/web/client/node_modules/.bin/acorn.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..e8e600e53f12b6a37936f84396fdbe205a4b6fa6 --- /dev/null +++ b/web/client/node_modules/.bin/acorn.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:264bfc66f8543c5adafaa0e1b01dcc93f94b9480377131c0127c541f53f865f2 +size 785 diff --git a/web/client/node_modules/.bin/css-beautify b/web/client/node_modules/.bin/css-beautify new file mode 100644 index 0000000000000000000000000000000000000000..d9fef9b3d8ec60b9cbfe76df4ccbc63b51b91568 --- /dev/null +++ b/web/client/node_modules/.bin/css-beautify @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e8657da63378af78b03b0aae2f0fe14ee34d5dde36a3a9eec7e1d4574dad27d +size 417 diff --git a/web/client/node_modules/.bin/css-beautify.cmd b/web/client/node_modules/.bin/css-beautify.cmd new file mode 100644 index 0000000000000000000000000000000000000000..5402ab77605947c250eee829aa18a9125f040b4a --- /dev/null +++ b/web/client/node_modules/.bin/css-beautify.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04b47ac516ba158e1b8e070e21fbfc1f1e373496cb7717a8a380cb59712d5def +size 339 diff --git a/web/client/node_modules/.bin/css-beautify.ps1 b/web/client/node_modules/.bin/css-beautify.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..b3ec183527e400b1380d2df62d547250ae0be111 --- /dev/null +++ b/web/client/node_modules/.bin/css-beautify.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c07779a41af4207e236d1ebf462439fbca3ef02c4f7a02b81710d7f79ba45e6 +size 861 diff --git a/web/client/node_modules/.bin/editorconfig b/web/client/node_modules/.bin/editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..d29636c51dd493e7a0079ad78c86969ee74bc6a7 --- /dev/null +++ b/web/client/node_modules/.bin/editorconfig @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76864961ab5ad5f2479ad9161e0c2b1b81c8d9d4c013084d6dd2c4f5bd17b4f2 +size 407 diff --git a/web/client/node_modules/.bin/editorconfig.cmd b/web/client/node_modules/.bin/editorconfig.cmd new file mode 100644 index 0000000000000000000000000000000000000000..b982e1c20e37193ae4804f401fd7bfc483d58767 --- /dev/null +++ b/web/client/node_modules/.bin/editorconfig.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad2d4c964586c46b92d406745749d219782439b4afecd6aad87798c453751024 +size 334 diff --git a/web/client/node_modules/.bin/editorconfig.ps1 b/web/client/node_modules/.bin/editorconfig.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..3379ccb6a649d3f54f32fda0a1f0f7dac7663279 --- /dev/null +++ b/web/client/node_modules/.bin/editorconfig.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7d9353e5bcbf3ac8d32c71ba624b6e2cf9a22136dd21731a7a4c78a07464895 +size 841 diff --git a/web/client/node_modules/.bin/esbuild b/web/client/node_modules/.bin/esbuild new file mode 100644 index 0000000000000000000000000000000000000000..81bbcfc94fa5ec8e93570e2a7e319e5dd22b12ed --- /dev/null +++ b/web/client/node_modules/.bin/esbuild @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:020b954fd13a2c5ee8aabd5a73e24c10a4750099ed5e02f07dc7265c6758a054 +size 387 diff --git a/web/client/node_modules/.bin/esbuild.cmd b/web/client/node_modules/.bin/esbuild.cmd new file mode 100644 index 0000000000000000000000000000000000000000..10fbb313b66ca832e8a17f7e57df17e4b2938e04 --- /dev/null +++ b/web/client/node_modules/.bin/esbuild.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b00afc3761267058834ab0968f58748f0422efe0eb0321540544770cafbf7a69 +size 324 diff --git a/web/client/node_modules/.bin/esbuild.ps1 b/web/client/node_modules/.bin/esbuild.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..0d52719c7a2679420b74600af4c58d5f67214b40 --- /dev/null +++ b/web/client/node_modules/.bin/esbuild.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a24efc13fb6ef9def6c5aaf7787e7203d0982e2ab8627b64a41eb033945b7f5 +size 801 diff --git a/web/client/node_modules/.bin/escodegen b/web/client/node_modules/.bin/escodegen new file mode 100644 index 0000000000000000000000000000000000000000..020ff7f3ee55ed9f2c274473c11126b3351ec0cf --- /dev/null +++ b/web/client/node_modules/.bin/escodegen @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f023e477bf11136581cac3453342fde4a54e624b324cf87e2f3c4be931158bdc +size 401 diff --git a/web/client/node_modules/.bin/escodegen.cmd b/web/client/node_modules/.bin/escodegen.cmd new file mode 100644 index 0000000000000000000000000000000000000000..1209179754dde7d90369c0a6392fb45a2186d75a --- /dev/null +++ b/web/client/node_modules/.bin/escodegen.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c38e08f1d3b0e8caca8ce9e563dbf1d646a5d3368a185ecf697ae7c56473c1fc +size 331 diff --git a/web/client/node_modules/.bin/escodegen.ps1 b/web/client/node_modules/.bin/escodegen.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..2043d8f34660e937ed7e3e0c91a765a706c832bd --- /dev/null +++ b/web/client/node_modules/.bin/escodegen.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf803422fa6579eb22f12c6ed4fce8453d973427887f6ab1849e87b9b3536f74 +size 829 diff --git a/web/client/node_modules/.bin/esgenerate b/web/client/node_modules/.bin/esgenerate new file mode 100644 index 0000000000000000000000000000000000000000..93017f6a4a9804de637e54b194cbbb6c7bf35a0d --- /dev/null +++ b/web/client/node_modules/.bin/esgenerate @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63d5729b11f165028f385d9bc5bcdc1808970e4e62729e323b6b1d5149605296 +size 403 diff --git a/web/client/node_modules/.bin/esgenerate.cmd b/web/client/node_modules/.bin/esgenerate.cmd new file mode 100644 index 0000000000000000000000000000000000000000..26e715b2537a0e611211b87b51478bf4c4a8fb77 --- /dev/null +++ b/web/client/node_modules/.bin/esgenerate.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3559c3bf7cbb021db62b313655983c694ea4d64bb4eca2a2706b8bf3dbb9ec25 +size 332 diff --git a/web/client/node_modules/.bin/esgenerate.ps1 b/web/client/node_modules/.bin/esgenerate.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..b61d3649b7b1ecefd4d8e9911f1230761356b950 --- /dev/null +++ b/web/client/node_modules/.bin/esgenerate.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ae1cd69401074809250f987b4b7ffa6b1dd1e5939d0c29cd5cd2806cbec8898 +size 833 diff --git a/web/client/node_modules/.bin/esparse b/web/client/node_modules/.bin/esparse new file mode 100644 index 0000000000000000000000000000000000000000..e0b8acefc18a195f413c9672b288b76600b97f93 --- /dev/null +++ b/web/client/node_modules/.bin/esparse @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de2ea7a4b2ebecc8aa088e2b26cffacdc36674f0b8a06c8f49e69489a121028f +size 393 diff --git a/web/client/node_modules/.bin/esparse.cmd b/web/client/node_modules/.bin/esparse.cmd new file mode 100644 index 0000000000000000000000000000000000000000..c12d5b9efcdc07e562a0c196779a9cb04f998f58 --- /dev/null +++ b/web/client/node_modules/.bin/esparse.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:524fe1bfee4734c65ba7c337982bb42423360b6265c6a91736807a19a2dbd8ee +size 327 diff --git a/web/client/node_modules/.bin/esparse.ps1 b/web/client/node_modules/.bin/esparse.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..a2338d934a1a3577c8b91cb53414d660db9755a6 --- /dev/null +++ b/web/client/node_modules/.bin/esparse.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b43deae7c89ad5603b2208444201737818db28e10f7aea1fcb51f71be246a9c2 +size 813 diff --git a/web/client/node_modules/.bin/esvalidate b/web/client/node_modules/.bin/esvalidate new file mode 100644 index 0000000000000000000000000000000000000000..609bcab4583da22f48b88ce13c89ccd5fea09eee --- /dev/null +++ b/web/client/node_modules/.bin/esvalidate @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dd54563b564cdeb73b643166ee65169b4a0d136d1b063bfdb55afc528cf630e +size 399 diff --git a/web/client/node_modules/.bin/esvalidate.cmd b/web/client/node_modules/.bin/esvalidate.cmd new file mode 100644 index 0000000000000000000000000000000000000000..ddc6d501c2b34e1504a77318701e1af25a2b768d --- /dev/null +++ b/web/client/node_modules/.bin/esvalidate.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baf9b027eceee99f10d7c4185b5488814aeb5bac5c73793df86c414cb5353a39 +size 330 diff --git a/web/client/node_modules/.bin/esvalidate.ps1 b/web/client/node_modules/.bin/esvalidate.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..081d3d91ed3b9217105783a877dfde4b4c42b1f5 --- /dev/null +++ b/web/client/node_modules/.bin/esvalidate.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f4c00c00c3ed5ed266245818bd992f99ca73b53e24b56679cbad8f93790308b +size 825 diff --git a/web/client/node_modules/.bin/glob b/web/client/node_modules/.bin/glob new file mode 100644 index 0000000000000000000000000000000000000000..8c30ae4d7557d1b061ae38e6588498d41d315c18 --- /dev/null +++ b/web/client/node_modules/.bin/glob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:130747a55febb9be265dba4f9089710e9c07ba271991f6b51cc368ab248e6480 +size 391 diff --git a/web/client/node_modules/.bin/glob.cmd b/web/client/node_modules/.bin/glob.cmd new file mode 100644 index 0000000000000000000000000000000000000000..df83d4a8a34b5100643f8086ac8c396f849588f5 --- /dev/null +++ b/web/client/node_modules/.bin/glob.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df2ccc1e8c6ca43ba5e5b7bcf3b98e1d6af8aab688a6bd089dda07b916f0ca9f +size 326 diff --git a/web/client/node_modules/.bin/glob.ps1 b/web/client/node_modules/.bin/glob.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..d39d4ceed3976217b10bf7048b61fe7dc9c5ac40 --- /dev/null +++ b/web/client/node_modules/.bin/glob.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76d0468f0c2a332cc900218fb3cd3dfff4ba6e836b7cd0d682b298c92b965aeb +size 809 diff --git a/web/client/node_modules/.bin/html-beautify b/web/client/node_modules/.bin/html-beautify new file mode 100644 index 0000000000000000000000000000000000000000..a3858b5a6e1e4711e602cbea4f02607329a3dec5 --- /dev/null +++ b/web/client/node_modules/.bin/html-beautify @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce1a7895c1bd36ad73395de072cd4cdb950bdff6ad6c3ded79224b524aa4da51 +size 419 diff --git a/web/client/node_modules/.bin/html-beautify.cmd b/web/client/node_modules/.bin/html-beautify.cmd new file mode 100644 index 0000000000000000000000000000000000000000..96f34aeb346090ef6f4d3fc47b2d4a7915cbc222 --- /dev/null +++ b/web/client/node_modules/.bin/html-beautify.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b9b8621bd5021ace9c610b78f07bad058104e7bcce506a351a08e395757b031 +size 340 diff --git a/web/client/node_modules/.bin/html-beautify.ps1 b/web/client/node_modules/.bin/html-beautify.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..d30b74e4df202151b975da769a2a6d58d3dd8a74 --- /dev/null +++ b/web/client/node_modules/.bin/html-beautify.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79bac02892cb079cf93cc5ffca72c95e8a5533954dca6fff494542ac62967bcf +size 865 diff --git a/web/client/node_modules/.bin/js-beautify b/web/client/node_modules/.bin/js-beautify new file mode 100644 index 0000000000000000000000000000000000000000..a42efb61e0227bf2310b719333760dc73ddc6468 --- /dev/null +++ b/web/client/node_modules/.bin/js-beautify @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2051d7688effedfba44f2e77c66d87d630ef87b58860c81df3e340bf4b18d5fe +size 415 diff --git a/web/client/node_modules/.bin/js-beautify.cmd b/web/client/node_modules/.bin/js-beautify.cmd new file mode 100644 index 0000000000000000000000000000000000000000..7cc7b60c14e1bf432cf84422df2e068962534092 --- /dev/null +++ b/web/client/node_modules/.bin/js-beautify.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e398abebc8618029dbca6e1a0d818fa1531e189ed8043f9b760cf59faf34388 +size 338 diff --git a/web/client/node_modules/.bin/js-beautify.ps1 b/web/client/node_modules/.bin/js-beautify.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..a8e9f72df060e6f7bfcbcab9ededa3c21bf3d4b2 --- /dev/null +++ b/web/client/node_modules/.bin/js-beautify.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f93e63f1fca253780bfb0f7de07658dbcb6b49c3d0415cad4f273baafb4bf363 +size 857 diff --git a/web/client/node_modules/.bin/nanoid b/web/client/node_modules/.bin/nanoid new file mode 100644 index 0000000000000000000000000000000000000000..e65438e55959a5f84c70cf5404380fef6762b84f --- /dev/null +++ b/web/client/node_modules/.bin/nanoid @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49446fa7e9ea1b36b205bab243f2928f1230d8dbeb09881eef1d039149ad3238 +size 391 diff --git a/web/client/node_modules/.bin/nanoid.cmd b/web/client/node_modules/.bin/nanoid.cmd new file mode 100644 index 0000000000000000000000000000000000000000..88c8582050826e21543577bb6b14d30cccfc2213 --- /dev/null +++ b/web/client/node_modules/.bin/nanoid.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65f7afb9e8bf7fd4ff2087803c18e8818334768bfe92b9c1f28346050678c0ca +size 326 diff --git a/web/client/node_modules/.bin/nanoid.ps1 b/web/client/node_modules/.bin/nanoid.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..bd772037dbf077f81a431b4a2970b2e3e845211a --- /dev/null +++ b/web/client/node_modules/.bin/nanoid.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2b48c0422548661c689493b3249b16f93599ca15fc3af5e821f9e6bccbe2aad +size 809 diff --git a/web/client/node_modules/.bin/node-which b/web/client/node_modules/.bin/node-which new file mode 100644 index 0000000000000000000000000000000000000000..ebd592cb51347db03cb24472fe112d8ce4f03a29 --- /dev/null +++ b/web/client/node_modules/.bin/node-which @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae614137ec19cd41eab2f7a85cc508e6a19042b0dda0a2815c07e5fb43a6e059 +size 389 diff --git a/web/client/node_modules/.bin/node-which.cmd b/web/client/node_modules/.bin/node-which.cmd new file mode 100644 index 0000000000000000000000000000000000000000..6ea5f36a7a47215c9e8d6dc9d430ee2c27076c77 --- /dev/null +++ b/web/client/node_modules/.bin/node-which.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:818856453703b9e61de47223e7505ad77cb4f40f456e348dae2ca9cd501abad0 +size 325 diff --git a/web/client/node_modules/.bin/node-which.ps1 b/web/client/node_modules/.bin/node-which.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..98e5154312add05735d7bdb12ee1c362fc99f21a --- /dev/null +++ b/web/client/node_modules/.bin/node-which.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d293014f7b06fffc145f94cd02bd82b53c2dbbc3eba99ff62dedf882adcc1711 +size 805 diff --git a/web/client/node_modules/.bin/nopt b/web/client/node_modules/.bin/nopt new file mode 100644 index 0000000000000000000000000000000000000000..ef188eabd36cdc6f684019a96758ca88c41e17b4 --- /dev/null +++ b/web/client/node_modules/.bin/nopt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15fa23344f314e078f77dcbd572cdbe956aade7a71eeaf8cba188207f17154d0 +size 381 diff --git a/web/client/node_modules/.bin/nopt.cmd b/web/client/node_modules/.bin/nopt.cmd new file mode 100644 index 0000000000000000000000000000000000000000..29b3d79f53da688008d297a5dd09fdace077606e --- /dev/null +++ b/web/client/node_modules/.bin/nopt.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa055caaf19e1f3bfa5311c31b216b522298ce7be1327e5f5d0f300b0d30a443 +size 321 diff --git a/web/client/node_modules/.bin/nopt.ps1 b/web/client/node_modules/.bin/nopt.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..1856271854ab53d489448d274e0b6a971d2f1844 --- /dev/null +++ b/web/client/node_modules/.bin/nopt.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08b2e0c384c9feb9d17908fdab0c583f5f3455884f0702a96ef7ed870b508eba +size 789 diff --git a/web/client/node_modules/.bin/parser b/web/client/node_modules/.bin/parser new file mode 100644 index 0000000000000000000000000000000000000000..e67f484bc9f6e6daf338d2ef7550c312a7401975 --- /dev/null +++ b/web/client/node_modules/.bin/parser @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed60a2b4f36fdf4d46331006ab1323a4c4098ce63a14b254e04dbbe92b579986 +size 415 diff --git a/web/client/node_modules/.bin/parser.cmd b/web/client/node_modules/.bin/parser.cmd new file mode 100644 index 0000000000000000000000000000000000000000..55c0806a265566ffa82d52c4d638b6bb44f8a275 --- /dev/null +++ b/web/client/node_modules/.bin/parser.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18aa582d6ce7a028ddb85a01ef6f5caa997e62744f86a5d1dcf56672890ee2e8 +size 338 diff --git a/web/client/node_modules/.bin/parser.ps1 b/web/client/node_modules/.bin/parser.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..c1c6b83b247ff727e82afcf8d7a835c7252df062 --- /dev/null +++ b/web/client/node_modules/.bin/parser.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65bf583f795bc6f3458e7f332deab74b979d410645c65ec6b8d21894f9277413 +size 857 diff --git a/web/client/node_modules/.bin/resolve b/web/client/node_modules/.bin/resolve new file mode 100644 index 0000000000000000000000000000000000000000..c1d68074af3034f5888c654fa46e83e00ad718e1 --- /dev/null +++ b/web/client/node_modules/.bin/resolve @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff5b354487e931da1b9c345b69fc645171767767863741e16433202a48234805 +size 387 diff --git a/web/client/node_modules/.bin/resolve.cmd b/web/client/node_modules/.bin/resolve.cmd new file mode 100644 index 0000000000000000000000000000000000000000..3c0ffe37a8b9a8ac0dc8af4caf0606c14f194682 --- /dev/null +++ b/web/client/node_modules/.bin/resolve.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85098bc212a2502f131e973a046be744b6c4a964852a8f09aca6222b8385f2e1 +size 324 diff --git a/web/client/node_modules/.bin/resolve.ps1 b/web/client/node_modules/.bin/resolve.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..3169611877a459f5caf206f7c60d70525bcb287e --- /dev/null +++ b/web/client/node_modules/.bin/resolve.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc0bcab59997f2fe5940bb357c67882c7a5d364dedb28242fa64ac9f10567f82 +size 801 diff --git a/web/client/node_modules/.bin/rollup b/web/client/node_modules/.bin/rollup new file mode 100644 index 0000000000000000000000000000000000000000..9913bb57a96cb107ec572676e7c2718ebc67c742 --- /dev/null +++ b/web/client/node_modules/.bin/rollup @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc55c2746b1a59c588127263b254384b08dd08de5b170c52796453f8a762b46 +size 393 diff --git a/web/client/node_modules/.bin/rollup.cmd b/web/client/node_modules/.bin/rollup.cmd new file mode 100644 index 0000000000000000000000000000000000000000..659848b7e66d44cb187416e8ebb9d059b0842c8e --- /dev/null +++ b/web/client/node_modules/.bin/rollup.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3a19226bedbf80c0cdfe75eeaadc21c74c7a58e04bff23a134f809f71ae2210 +size 327 diff --git a/web/client/node_modules/.bin/rollup.ps1 b/web/client/node_modules/.bin/rollup.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..12792954b8d43b125eba3b6021285dd788b85d7f --- /dev/null +++ b/web/client/node_modules/.bin/rollup.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:095ea547e7dba18c0f9679b21c8237d776916d61cc56967b34cef1cea7bc592b +size 813 diff --git a/web/client/node_modules/.bin/sass b/web/client/node_modules/.bin/sass new file mode 100644 index 0000000000000000000000000000000000000000..852531bab45a42b1be71afbda899e0e39e220c13 --- /dev/null +++ b/web/client/node_modules/.bin/sass @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:860f65d973781389b7685371723cdbb9b40c19a2ff4eec2ccff6febe59de74a1 +size 373 diff --git a/web/client/node_modules/.bin/sass.cmd b/web/client/node_modules/.bin/sass.cmd new file mode 100644 index 0000000000000000000000000000000000000000..9324e3a191cb94b05b4300be700ad778f76d95ad --- /dev/null +++ b/web/client/node_modules/.bin/sass.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:097f5ecd7b5b50429e7204298846496515ee36157d47e15b9bf53f3cbcd9d4f4 +size 317 diff --git a/web/client/node_modules/.bin/sass.ps1 b/web/client/node_modules/.bin/sass.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..d43b30d81b854710057fba60e94a5bd088760512 --- /dev/null +++ b/web/client/node_modules/.bin/sass.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48520a32aaa8807ba3dbd48b5dc32e53a48be3cf0ff10f262ca65e6b09315d07 +size 773 diff --git a/web/client/node_modules/.bin/semver b/web/client/node_modules/.bin/semver new file mode 100644 index 0000000000000000000000000000000000000000..ca0824fb9723b18a56c0f8e3e511b2b7347aa446 --- /dev/null +++ b/web/client/node_modules/.bin/semver @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77ef070b2790156c37dd77efd5d0cf54fbff85d9c1adabc890948192cd2b2639 +size 389 diff --git a/web/client/node_modules/.bin/semver.cmd b/web/client/node_modules/.bin/semver.cmd new file mode 100644 index 0000000000000000000000000000000000000000..b3a393f6a015e12534274c125266babe668b9d9a --- /dev/null +++ b/web/client/node_modules/.bin/semver.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fa2710c6522669c2253edbd465ccf4c58d0d29e0eff3337d7900cd4e5cec7ac +size 325 diff --git a/web/client/node_modules/.bin/semver.ps1 b/web/client/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..ef28e6b83ae3c58170e7a4a3ad6c1ade9eb644ea --- /dev/null +++ b/web/client/node_modules/.bin/semver.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e1355d1aaf2a75275f9d884dbcd2f1c713d4ada1782fe8370bc21db6aedbc31 +size 805 diff --git a/web/client/node_modules/.bin/vite b/web/client/node_modules/.bin/vite new file mode 100644 index 0000000000000000000000000000000000000000..31aefb21ea2f2ea01a3bfda142013159cc2be0d9 --- /dev/null +++ b/web/client/node_modules/.bin/vite @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdf31cf5e7b6cbfa65c2111d4fec53a7484c038aeac028f3718ab565c171b7ed +size 381 diff --git a/web/client/node_modules/.bin/vite.cmd b/web/client/node_modules/.bin/vite.cmd new file mode 100644 index 0000000000000000000000000000000000000000..5578d603594bd8fa47390f549db4c738c1464c57 --- /dev/null +++ b/web/client/node_modules/.bin/vite.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e865893c8f57ff153c66cf80aac687f436b457922d9585495becee81c927e910 +size 321 diff --git a/web/client/node_modules/.bin/vite.ps1 b/web/client/node_modules/.bin/vite.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..a28aa41bfadb3e6eb1c0d27c52300e7d8319c2d3 --- /dev/null +++ b/web/client/node_modules/.bin/vite.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb22a675c5bf414d459a8b07172d5cc073c7d51520bed1d7d6f1652e3fd1f3ea +size 789 diff --git a/web/client/node_modules/.bin/vitest b/web/client/node_modules/.bin/vitest new file mode 100644 index 0000000000000000000000000000000000000000..feb9deb6a1fbfb65a1adeb1c89d71736600db907 --- /dev/null +++ b/web/client/node_modules/.bin/vitest @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1bbe582a2450cca0708096f3fcc060280aa09d85b487dc3549201a64f6590a4 +size 383 diff --git a/web/client/node_modules/.bin/vitest.cmd b/web/client/node_modules/.bin/vitest.cmd new file mode 100644 index 0000000000000000000000000000000000000000..cd67fe119537d64c2cd0548f76b1133384df7d88 --- /dev/null +++ b/web/client/node_modules/.bin/vitest.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5959ce11885ed044bf1883d9a991d4db2a4690c255681d2e635991d34b393f1 +size 322 diff --git a/web/client/node_modules/.bin/vitest.ps1 b/web/client/node_modules/.bin/vitest.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..4133f4e5a2e9a9250b36207cb08ead72ee77311c --- /dev/null +++ b/web/client/node_modules/.bin/vitest.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b361a4204b5a5fc98974019e0f082389c835db3b6d0b78951e13728fcb830d07 +size 793 diff --git a/web/client/node_modules/.package-lock.json b/web/client/node_modules/.package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..8fa45983eb98af5ef5a5a70817698180707106e1 --- /dev/null +++ b/web/client/node_modules/.package-lock.json @@ -0,0 +1,2123 @@ +{ + "name": "exercise-correction", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@babel/parser": { + "version": "7.23.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.9.tgz", + "integrity": "sha512-9tcKgqKbs3xGJ+NtKF2ndOBBLVwPjl1SHxPQkd36r3Dlirw3xWUeGaTbqr7uGZcTaxkVNwc+03SVP7aCdWrTlA==", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "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/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@one-ini/wasm": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@one-ini/wasm/-/wasm-0.1.1.tgz", + "integrity": "sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==", + "dev": true + }, + "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, + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/@types/chai": { + "version": "4.3.12", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.12.tgz", + "integrity": "sha512-zNKDHG/1yxm8Il6uCCVsm+dRdEsJlFoDu73X17y09bId6UwoYww+vFBsAcRzl8knM1sab3Dp1VRikFQwDOtDDw==", + "dev": true + }, + "node_modules/@types/chai-subset": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.5.tgz", + "integrity": "sha512-c2mPnw+xHtXDoHmdtcCXGwyLMiauiAyxWMzhGpqHC4nqI/Y5G2XhTampslK2rb59kpcuHon03UH8W6iYUzw88A==", + "dev": true, + "dependencies": { + "@types/chai": "*" + } + }, + "node_modules/@types/node": { + "version": "20.11.20", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.20.tgz", + "integrity": "sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==", + "dev": true, + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@vitejs/plugin-vue": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-3.2.0.tgz", + "integrity": "sha512-E0tnaL4fr+qkdCNxJ+Xd0yM31UwMkQje76fsDVBBUCoGOUPexu2VDUYHL8P4CwV+zMvWw6nlRw19OnRKmYAJpw==", + "dev": true, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^3.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.20.tgz", + "integrity": "sha512-l7M+xUuL8hrGtRLkrf+62d9zucAdgqNBTbJ/NufCOIuJQhauhfyAKH9ra/qUctCXcULwmclGAVpvmxjbBO30qg==", + "dependencies": { + "@babel/parser": "^7.23.9", + "@vue/shared": "3.4.20", + "entities": "^4.5.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.0.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.20.tgz", + "integrity": "sha512-/cSBGL79HFBYgDnqCNKErOav3bPde3n0sJwJM2Z09rXlkiowV/2SG1tgDAiWS1CatS4Cvo0o74e1vNeCK1R3RA==", + "dependencies": { + "@vue/compiler-core": "3.4.20", + "@vue/shared": "3.4.20" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.4.20.tgz", + "integrity": "sha512-nPuTZz0yxTPzjyYe+9nQQsFYImcz/57UX8N3jyhl5oIUUs2jqqAMaULsAlJwve3qNYfjQzq0bwy3pqJrN9ecZw==", + "dependencies": { + "@babel/parser": "^7.23.9", + "@vue/compiler-core": "3.4.20", + "@vue/compiler-dom": "3.4.20", + "@vue/compiler-ssr": "3.4.20", + "@vue/shared": "3.4.20", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.7", + "postcss": "^8.4.35", + "source-map-js": "^1.0.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.20.tgz", + "integrity": "sha512-b3gFQPiHLvI12C56otzBPpQhZ5kgkJ5RMv/zpLjLC2BIFwX5GktDqYQ7xg0Q2grP6uFI8al3beVKvAVxFtXmIg==", + "dependencies": { + "@vue/compiler-dom": "3.4.20", + "@vue/shared": "3.4.20" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.1.tgz", + "integrity": "sha512-LgPscpE3Vs0x96PzSSB4IGVSZXZBZHpfxs+ZA1d+VEPwHdOXowy/Y2CsvCAIFrf+ssVU1pD1jidj505EpUnfbA==" + }, + "node_modules/@vue/reactivity": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.4.20.tgz", + "integrity": "sha512-P5LJcxUkG6inlHr6MHVA4AVFAmRYJQ7ONGWJILNjMjoYuEXFhYviSCb9BEMyszSG/1kWCZbtWQlKSLasFRpThw==", + "dependencies": { + "@vue/shared": "3.4.20" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.4.20.tgz", + "integrity": "sha512-MPvsQpGAxoBqLHjqopt4YPtUYBpq0K6oAWDTwIR1CTNZ3y9O/J2ZVh+i2JpxKNYwANJBiZ20O99NE20uisB7xw==", + "dependencies": { + "@vue/reactivity": "3.4.20", + "@vue/shared": "3.4.20" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.4.20.tgz", + "integrity": "sha512-OkbPVP69H+8m74543zMAAx/LIkajxufYyow41gc0s5iF0uplT5uTQ4llDYu1GeJZEI8wjL5ueiPQruk4qwOMmA==", + "dependencies": { + "@vue/runtime-core": "3.4.20", + "@vue/shared": "3.4.20", + "csstype": "^3.1.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.4.20.tgz", + "integrity": "sha512-w3VH2GuwxQHA6pJo/HCV22OfVC8Mw4oeHQM+vKeqtRK0OPE1Wilnh+P/SDVGGxPjJsGmyfphi0dbw8UKZQJH9w==", + "dependencies": { + "@vue/compiler-ssr": "3.4.20", + "@vue/shared": "3.4.20" + }, + "peerDependencies": { + "vue": "3.4.20" + } + }, + "node_modules/@vue/shared": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.20.tgz", + "integrity": "sha512-KTEngal0aiUvNJ6I1Chk5Ew5XqChsFsxP4GKAYXWb99zKJWjNU72p2FWEOmZWHxHcqtniOJsgnpd3zizdpfEag==" + }, + "node_modules/@vue/test-utils": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@vue/test-utils/-/test-utils-2.4.4.tgz", + "integrity": "sha512-8jkRxz8pNhClAf4Co4ZrpAoFISdvT3nuSkUlY6Ys6rmTpw3DMWG/X3mw3gQ7QJzgCZO9f+zuE2kW57fi09MW7Q==", + "dev": true, + "dependencies": { + "js-beautify": "^1.14.9", + "vue-component-type-helpers": "^1.8.21" + }, + "peerDependencies": { + "@vue/server-renderer": "^3.0.1", + "vue": "^3.0.1" + }, + "peerDependenciesMeta": { + "@vue/server-renderer": { + "optional": true + } + } + }, + "node_modules/abab": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", + "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", + "deprecated": "Use your platform's native atob() and btoa() methods instead", + "dev": true + }, + "node_modules/abbrev": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz", + "integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==", + "dev": true, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/acorn": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-globals": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-7.0.1.tgz", + "integrity": "sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==", + "dev": true, + "dependencies": { + "acorn": "^8.1.0", + "acorn-walk": "^8.0.2" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz", + "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "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==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", + "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", + "dependencies": { + "follow-redirects": "^1.15.4", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", + "integrity": "sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==", + "dev": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.0.8" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "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/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/config-chain": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", + "integrity": "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==", + "dev": true, + "dependencies": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssom": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", + "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", + "dev": true + }, + "node_modules/cssstyle": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", + "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", + "dev": true, + "dependencies": { + "cssom": "~0.3.6" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cssstyle/node_modules/cssom": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", + "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", + "dev": true + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==" + }, + "node_modules/data-urls": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz", + "integrity": "sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==", + "dev": true, + "dependencies": { + "abab": "^2.0.6", + "whatwg-mimetype": "^3.0.0", + "whatwg-url": "^11.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", + "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", + "dev": true + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/domexception": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz", + "integrity": "sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==", + "deprecated": "Use your platform's native DOMException instead", + "dev": true, + "dependencies": { + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "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 + }, + "node_modules/editorconfig": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.4.tgz", + "integrity": "sha512-L9Qe08KWTlqYMVvMcTIvMAdl1cDUubzRNYL+WfA4bLDMHe4nemKkpmYzkznE1FwLKu0EEmy6obgQKzMJrg4x9Q==", + "dev": true, + "dependencies": { + "@one-ini/wasm": "0.1.1", + "commander": "^10.0.0", + "minimatch": "9.0.1", + "semver": "^7.5.3" + }, + "bin": { + "editorconfig": "bin/editorconfig" + }, + "engines": { + "node": ">=14" + } + }, + "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 + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.18.tgz", + "integrity": "sha512-x/R72SmW3sSFRm5zrrIjAhCeQSAWoni3CmHEqfQrZIQTM3lVCdehdwuIqaOtfC2slvpdlLa62GYoN8SxT23m6Q==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.15.18", + "@esbuild/linux-loong64": "0.15.18", + "esbuild-android-64": "0.15.18", + "esbuild-android-arm64": "0.15.18", + "esbuild-darwin-64": "0.15.18", + "esbuild-darwin-arm64": "0.15.18", + "esbuild-freebsd-64": "0.15.18", + "esbuild-freebsd-arm64": "0.15.18", + "esbuild-linux-32": "0.15.18", + "esbuild-linux-64": "0.15.18", + "esbuild-linux-arm": "0.15.18", + "esbuild-linux-arm64": "0.15.18", + "esbuild-linux-mips64le": "0.15.18", + "esbuild-linux-ppc64le": "0.15.18", + "esbuild-linux-riscv64": "0.15.18", + "esbuild-linux-s390x": "0.15.18", + "esbuild-netbsd-64": "0.15.18", + "esbuild-openbsd-64": "0.15.18", + "esbuild-sunos-64": "0.15.18", + "esbuild-windows-32": "0.15.18", + "esbuild-windows-64": "0.15.18", + "esbuild-windows-arm64": "0.15.18" + } + }, + "node_modules/esbuild-windows-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.18.tgz", + "integrity": "sha512-qinug1iTTaIIrCorAUjR0fcBk24fjzEedFYhhispP8Oc7SFvs+XeW3YpAKiKp8dRpizl4YYAhxMjlftAMJiaUw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/escodegen": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", + "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", + "dev": true, + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/foreground-child": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.1.1.tgz", + "integrity": "sha512-TMKDUnIte6bfb5nWv7V/caI169OHgvwjb7V4WkeUvbQQdjr5rWKqHFiKWb/fcOwB+CzBT+qbWjvj+DVwRskpIg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "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, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/glob": { + "version": "10.3.10", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.10.tgz", + "integrity": "sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g==", + "dev": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^2.3.5", + "minimatch": "^9.0.1", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", + "path-scurry": "^1.10.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "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==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/hasown": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz", + "integrity": "sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", + "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", + "dev": true, + "dependencies": { + "whatwg-encoding": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "dev": true, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/immutable": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.5.tgz", + "integrity": "sha512-8eabxkth9gZatlwl5TBuJnCsoTADlL6ftEr7A4qgdaTsPyreilDSnUk57SO+jfKcNtxPa22U5KK6DSeAYhpBJw==" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true + }, + "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==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", + "dev": true, + "dependencies": { + "hasown": "^2.0.0" + }, + "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==", + "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", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "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==", + "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==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/jackspeak": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-2.3.6.tgz", + "integrity": "sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ==", + "dev": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/js-beautify": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.15.1.tgz", + "integrity": "sha512-ESjNzSlt/sWE8sciZH8kBF8BPlwXPwhR6pWKAw8bw4Bwj+iZcnKW6ONWUutJ7eObuBZQpiIb8S7OYspWrKt7rA==", + "dev": true, + "dependencies": { + "config-chain": "^1.1.13", + "editorconfig": "^1.0.4", + "glob": "^10.3.3", + "js-cookie": "^3.0.5", + "nopt": "^7.2.0" + }, + "bin": { + "css-beautify": "js/bin/css-beautify.js", + "html-beautify": "js/bin/html-beautify.js", + "js-beautify": "js/bin/js-beautify.js" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/js-cookie": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz", + "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==", + "dev": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/jsdom": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", + "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", + "dev": true, + "dependencies": { + "abab": "^2.0.6", + "acorn": "^8.8.1", + "acorn-globals": "^7.0.0", + "cssom": "^0.5.0", + "cssstyle": "^2.3.0", + "data-urls": "^3.0.2", + "decimal.js": "^10.4.2", + "domexception": "^4.0.0", + "escodegen": "^2.0.0", + "form-data": "^4.0.0", + "html-encoding-sniffer": "^3.0.0", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.1", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.2", + "parse5": "^7.1.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^4.1.2", + "w3c-xmlserializer": "^4.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^2.0.0", + "whatwg-mimetype": "^3.0.0", + "whatwg-url": "^11.0.0", + "ws": "^8.11.0", + "xml-name-validator": "^4.0.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "canvas": "^2.5.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/local-pkg": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.4.3.tgz", + "integrity": "sha512-SFppqq5p42fe2qcZQqqEOiVRXl+WCP1MdT6k7BDEW1j++sp5fIY+/fdRQitvKgB5BrBcmrs5m/L0v2FrU5MY1g==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/lru-cache": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.0.tgz", + "integrity": "sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q==", + "dev": true, + "engines": { + "node": "14 || >=16.14" + } + }, + "node_modules/magic-string": { + "version": "0.30.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.7.tgz", + "integrity": "sha512-8vBuFF/I/+OSLRmdf2wwFCJCz+nSn0m6DPvGH1fS/KiQoSaR+sETbov0eIk9KhEKy8CYqIkIAnbohxT/4H0kuA==", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.1.tgz", + "integrity": "sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.0.4.tgz", + "integrity": "sha512-jYofLM5Dam9279rdkWzqHozUo4ybjdZmCsDHePy5V/PbBcVMiSZR97gmAy45aqi8CK1lG2ECd356FU86avfwUQ==", + "dev": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nopt": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.0.tgz", + "integrity": "sha512-CVDtwCdhYIvnAzFoJ6NJ6dX3oga9/HyciQDnG1vQDjSLMeKLJ4A93ZqYKDrgYSr1FBY5/hMYC+2VCi24pgpkGA==", + "dev": true, + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "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==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nwsapi": { + "version": "2.2.7", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.7.tgz", + "integrity": "sha512-ub5E4+FBPKwAZx0UwIQOjYWGHTEq5sPqHQNRN8Z9e4A7u3Tj1weLJsL59yH9vmvqEtBHaOmT6cYQKIZOxp35FQ==", + "dev": true + }, + "node_modules/parse5": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", + "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", + "dev": true, + "dependencies": { + "entities": "^4.4.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "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, + "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 + }, + "node_modules/path-scurry": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.10.1.tgz", + "integrity": "sha512-MkhCqzzBEpPvxxQ71Md0b1Kk51W01lrYvlMzSUaIzNsODdd7mqhiimSZlr+VegAz5Z6Vzt9Xg2ttE//XBhH3EQ==", + "dev": true, + "dependencies": { + "lru-cache": "^9.1.1 || ^10.0.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pinia": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/pinia/-/pinia-2.1.7.tgz", + "integrity": "sha512-+C2AHFtcFqjPih0zpYuvof37SFxMQ7OEG2zV9jRI12i9BOy3YQVAHwdKtyyc8pDcDyIc33WCIsZaCFWU7WWxGQ==", + "dependencies": { + "@vue/devtools-api": "^6.5.0", + "vue-demi": ">=0.14.5" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "@vue/composition-api": "^1.4.0", + "typescript": ">=4.4.4", + "vue": "^2.6.14 || ^3.3.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/pinia/node_modules/vue-demi": { + "version": "0.14.7", + "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.7.tgz", + "integrity": "sha512-EOG8KXDQNwkJILkx/gPcoL/7vH+hORoBaKgGe+6W7VFMvCYJfmF2dGbvgDroVnI8LU7/kTu8mbjRZGBU1z9NTA==", + "hasInstallScript": true, + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/postcss": { + "version": "8.4.35", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.35.tgz", + "integrity": "sha512-u5U8qYpBCpN13BsiEB0CbR1Hhh4Gc0zLFuedrHJKMctHCHAGrMdG0PRM/KErzAL3CU6/eckEtmHNB3x6e3c0vA==", + "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" + } + ], + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proto-list": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz", + "integrity": "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==", + "dev": true + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", + "dev": true + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "dev": true + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "dev": true + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "2.79.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.1.tgz", + "integrity": "sha512-uKxbd0IhMZOhjAiD5oAFp7BqvkA4Dv47qpOCtaNvng4HBwdbWtdOh8f5nZNuk2rp51PMGk3bzfWu5oayNEuYnw==", + "dev": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "node_modules/sass": { + "version": "1.71.1", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.71.1.tgz", + "integrity": "sha512-wovtnV2PxzteLlfNzbgm1tFXPLoZILYAMJtvoXXkD7/+1uP41eKkIt1ypWq5/q2uT94qHjXehEYfmjKOvjL9sg==", + "dependencies": { + "chokidar": ">=3.0.0 <4.0.0", + "immutable": "^4.0.0", + "source-map-js": ">=0.6.2 <2.0.0" + }, + "bin": { + "sass": "sass.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", + "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "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, + "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, + "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, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "engines": { + "node": ">=0.10.0" + } + }, + "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, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-literal": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-0.4.2.tgz", + "integrity": "sha512-pv48ybn4iE1O9RLgCAN0iU4Xv7RlBTiit6DKmMiErbs9x1wH6vXBs45tWc0H5wUIF6TLTrKweqkmYF/iraQKNw==", + "dev": true, + "dependencies": { + "acorn": "^8.8.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "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, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true + }, + "node_modules/tinybench": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.6.0.tgz", + "integrity": "sha512-N8hW3PG/3aOoZAN5V/NSAEDz0ZixDSSt5b/a05iqtpgfLWMSVuCo7w0k2vVvEjdrIoeGqZzweX2WlyioNIHchA==", + "dev": true + }, + "node_modules/tinypool": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.3.1.tgz", + "integrity": "sha512-zLA1ZXlstbU2rlpA4CIeVaqvWq41MTWqLY3FfsAXgC8+f7Pk7zroaJQxDgxn1xNudKW6Kmj4808rPFShUlIRmQ==", + "dev": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-1.1.1.tgz", + "integrity": "sha512-UVq5AXt/gQlti7oxoIg5oi/9r0WpF7DGEVwXgqWSMmyN16+e3tl5lIvTaOpJ3TAtu5xFzWccFRM4R5NaWHF+4g==", + "dev": true, + "engines": { + "node": ">=14.0.0" + } + }, + "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==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tough-cookie": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", + "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", + "dev": true, + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", + "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "dev": true, + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true + }, + "node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "dev": true, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "dev": true, + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/vite": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.8.tgz", + "integrity": "sha512-EtQU16PLIJpAZol2cTLttNP1mX6L0SyI0pgQB1VOoWeQnMSvtiwovV3D6NcjN8CZQWWyESD2v5NGnpz5RvgOZA==", + "dev": true, + "dependencies": { + "esbuild": "^0.15.9", + "postcss": "^8.4.18", + "resolve": "^1.22.1", + "rollup": "^2.79.1" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@types/node": ">= 14", + "less": "*", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "0.23.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.23.4.tgz", + "integrity": "sha512-iukBNWqQAv8EKDBUNntspLp9SfpaVFbmzmM0sNcnTxASQZMzRw3PsM6DMlsHiI+I6GeO5/sYDg3ecpC+SNFLrQ==", + "dev": true, + "dependencies": { + "@types/chai": "^4.3.3", + "@types/chai-subset": "^1.3.3", + "@types/node": "*", + "chai": "^4.3.6", + "debug": "^4.3.4", + "local-pkg": "^0.4.2", + "strip-literal": "^0.4.1", + "tinybench": "^2.1.5", + "tinypool": "^0.3.0", + "tinyspy": "^1.0.2", + "vite": "^2.9.12 || ^3.0.0-0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": ">=v14.16.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@vitest/browser": "*", + "@vitest/ui": "*", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vue": { + "version": "3.4.20", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.4.20.tgz", + "integrity": "sha512-xF4zDKXp67NjgORFX/HOuaiaKYjgxkaToK0KWglFQEYlCw9AqgBlj1yu5xa6YaRek47w2IGiuvpvrGg/XuQFCw==", + "dependencies": { + "@vue/compiler-dom": "3.4.20", + "@vue/compiler-sfc": "3.4.20", + "@vue/runtime-dom": "3.4.20", + "@vue/server-renderer": "3.4.20", + "@vue/shared": "3.4.20" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-component-type-helpers": { + "version": "1.8.27", + "resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-1.8.27.tgz", + "integrity": "sha512-0vOfAtI67UjeO1G6UiX5Kd76CqaQ67wrRZiOe7UAb9Jm6GzlUr/fC7CV90XfwapJRjpCMaZFhv1V0ajWRmE9Dg==", + "dev": true + }, + "node_modules/vue-router": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.3.0.tgz", + "integrity": "sha512-dqUcs8tUeG+ssgWhcPbjHvazML16Oga5w34uCUmsk7i0BcnskoLGwjpa15fqMr2Fa5JgVBrdL2MEgqz6XZ/6IQ==", + "dependencies": { + "@vue/devtools-api": "^6.5.1" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", + "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", + "dev": true, + "dependencies": { + "xml-name-validator": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", + "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", + "dev": true, + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", + "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "dev": true, + "dependencies": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "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, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "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, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", + "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz", + "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + } + } +} diff --git a/web/client/node_modules/.vite/deps/_metadata.json b/web/client/node_modules/.vite/deps/_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..f724037835077ee57d369157354edf99182e933d --- /dev/null +++ b/web/client/node_modules/.vite/deps/_metadata.json @@ -0,0 +1,41 @@ +{ + "hash": "e255bc16", + "browserHash": "56799304", + "optimized": { + "axios": { + "src": "../../axios/index.js", + "file": "axios.js", + "fileHash": "b89dcbd8", + "needsInterop": false + }, + "pinia": { + "src": "../../pinia/dist/pinia.mjs", + "file": "pinia.js", + "fileHash": "f9c61fd9", + "needsInterop": false + }, + "vue": { + "src": "../../vue/dist/vue.runtime.esm-bundler.js", + "file": "vue.js", + "fileHash": "ff5f5fce", + "needsInterop": false + }, + "vue-router": { + "src": "../../vue-router/dist/vue-router.mjs", + "file": "vue-router.js", + "fileHash": "63aaba0f", + "needsInterop": false + } + }, + "chunks": { + "chunk-YGWLVKKF": { + "file": "chunk-YGWLVKKF.js" + }, + "chunk-LL35M65S": { + "file": "chunk-LL35M65S.js" + }, + "chunk-JC4IRQUL": { + "file": "chunk-JC4IRQUL.js" + } + } +} \ No newline at end of file diff --git a/web/client/node_modules/.vite/deps/axios.js b/web/client/node_modules/.vite/deps/axios.js new file mode 100644 index 0000000000000000000000000000000000000000..12dc1b6c251278656face3fa3d62383f691461a4 --- /dev/null +++ b/web/client/node_modules/.vite/deps/axios.js @@ -0,0 +1,2083 @@ +import { + __export +} from "./chunk-JC4IRQUL.js"; + +// node_modules/axios/lib/helpers/bind.js +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} + +// node_modules/axios/lib/utils.js +var { toString } = Object.prototype; +var { getPrototypeOf } = Object; +var kindOf = ((cache) => (thing) => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(/* @__PURE__ */ Object.create(null)); +var kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type; +}; +var typeOfTest = (type) => (thing) => typeof thing === type; +var { isArray } = Array; +var isUndefined = typeOfTest("undefined"); +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} +var isArrayBuffer = kindOfTest("ArrayBuffer"); +function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; +} +var isString = typeOfTest("string"); +var isFunction = typeOfTest("function"); +var isNumber = typeOfTest("number"); +var isObject = (thing) => thing !== null && typeof thing === "object"; +var isBoolean = (thing) => thing === true || thing === false; +var isPlainObject = (val) => { + if (kindOf(val) !== "object") { + return false; + } + const prototype3 = getPrototypeOf(val); + return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +}; +var isDate = kindOfTest("Date"); +var isFile = kindOfTest("File"); +var isBlob = kindOfTest("Blob"); +var isFileList = kindOfTest("FileList"); +var isStream = (val) => isObject(val) && isFunction(val.pipe); +var isFormData = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); +}; +var isURLSearchParams = kindOfTest("URLSearchParams"); +var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); +function forEach(obj, fn, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i; + let l; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray(obj)) { + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} +var _global = (() => { + if (typeof globalThis !== "undefined") + return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; +})(); +var isContextDefined = (context) => !isUndefined(context) && context !== _global; +function merge() { + const { caseless } = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} +var extend = (a, b, thisArg, { allOwnKeys } = {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, { allOwnKeys }); + return a; +}; +var stripBOM = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); + } + return content; +}; +var inherits = (constructor, superConstructor, props, descriptors2) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors2); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; +var toFlatObject = (sourceObj, destObj, filter2, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) + return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter2 !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; +}; +var endsWith = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; +var toArray = (thing) => { + if (!thing) + return null; + if (isArray(thing)) + return thing; + let i = thing.length; + if (!isNumber(i)) + return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; +var isTypedArray = ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); +var forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + const iterator = generator.call(obj); + let result; + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; +var matchAll = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; +}; +var isHTMLForm = kindOfTest("HTMLFormElement"); +var toCamelCase = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; +var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); +var isRegExp = kindOfTest("RegExp"); +var reduceDescriptors = (obj, reducer) => { + const descriptors2 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach(descriptors2, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); +}; +var freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { + return false; + } + const value = obj[name]; + if (!isFunction(value)) + return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name + "'"); + }; + } + }); +}; +var toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + const define = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + return obj; +}; +var noop = () => { +}; +var toFiniteNumber = (value, defaultValue) => { + value = +value; + return Number.isFinite(value) ? value : defaultValue; +}; +var ALPHA = "abcdefghijklmnopqrstuvwxyz"; +var DIGIT = "0123456789"; +var ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; +var generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ""; + const { length } = alphabet; + while (size--) { + str += alphabet[Math.random() * length | 0]; + } + return str; +}; +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); +} +var toJSONObject = (obj) => { + const stack = new Array(10); + const visit = (source, i) => { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = void 0; + return target; + } + } + return source; + }; + return visit(obj, 0); +}; +var isAsyncFn = kindOfTest("AsyncFunction"); +var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); +var utils_default = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable +}; + +// node_modules/axios/lib/core/AxiosError.js +function AxiosError(message, code, config, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = "AxiosError"; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); +} +utils_default.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + message: this.message, + name: this.name, + description: this.description, + number: this.number, + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + config: utils_default.toJSONObject(this.config), + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; + } +}); +var prototype = AxiosError.prototype; +var descriptors = {}; +[ + "ERR_BAD_OPTION_VALUE", + "ERR_BAD_OPTION", + "ECONNABORTED", + "ETIMEDOUT", + "ERR_NETWORK", + "ERR_FR_TOO_MANY_REDIRECTS", + "ERR_DEPRECATED", + "ERR_BAD_RESPONSE", + "ERR_BAD_REQUEST", + "ERR_CANCELED", + "ERR_NOT_SUPPORT", + "ERR_INVALID_URL" +].forEach((code) => { + descriptors[code] = { value: code }; +}); +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, "isAxiosError", { value: true }); +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(prototype); + utils_default.toFlatObject(error, axiosError, function filter2(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError.call(axiosError, error.message, code, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; +}; +var AxiosError_default = AxiosError; + +// node_modules/axios/lib/helpers/null.js +var null_default = null; + +// node_modules/axios/lib/helpers/toFormData.js +function isVisitable(thing) { + return utils_default.isPlainObject(thing) || utils_default.isArray(thing); +} +function removeBrackets(key) { + return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; +} +function renderKey(path, key, dots) { + if (!path) + return key; + return path.concat(key).map(function each(token, i) { + token = removeBrackets(token); + return !dots && i ? "[" + token + "]" : token; + }).join(dots ? "." : ""); +} +function isFlatArray(arr) { + return utils_default.isArray(arr) && !arr.some(isVisitable); +} +var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); +function toFormData(obj, formData, options) { + if (!utils_default.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new (null_default || FormData)(); + options = utils_default.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils_default.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); + if (!utils_default.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) + return ""; + if (utils_default.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils_default.isBlob(value)) { + throw new AxiosError_default("Blob is not supported. Use a Buffer instead."); + } + if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils_default.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { + key = removeBrackets(key); + arr.forEach(function each(el, index) { + !(utils_default.isUndefined(el) || el === null) && formData.append( + indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", + convertValue(el) + ); + }); + return false; + } + } + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils_default.isUndefined(value)) + return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils_default.forEach(value, function each(el, key) { + const result = !(utils_default.isUndefined(el) || el === null) && visitor.call( + formData, + el, + utils_default.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils_default.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; +} +var toFormData_default = toFormData; + +// node_modules/axios/lib/helpers/AxiosURLSearchParams.js +function encode(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} +function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData_default(params, this, options); +} +var prototype2 = AxiosURLSearchParams.prototype; +prototype2.append = function append(name, value) { + this._pairs.push([name, value]); +}; +prototype2.toString = function toString2(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode); + } : encode; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); +}; +var AxiosURLSearchParams_default = AxiosURLSearchParams; + +// node_modules/axios/lib/helpers/buildURL.js +function encode2(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); +} +function buildURL(url, params, options) { + if (!params) { + return url; + } + const _encode = options && options.encode || encode2; + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url; +} + +// node_modules/axios/lib/core/InterceptorManager.js +var InterceptorManager = class { + constructor() { + this.handlers = []; + } + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + clear() { + if (this.handlers) { + this.handlers = []; + } + } + forEach(fn) { + utils_default.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +}; +var InterceptorManager_default = InterceptorManager; + +// node_modules/axios/lib/defaults/transitional.js +var transitional_default = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + +// node_modules/axios/lib/platform/browser/classes/URLSearchParams.js +var URLSearchParams_default = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams_default; + +// node_modules/axios/lib/platform/browser/classes/FormData.js +var FormData_default = typeof FormData !== "undefined" ? FormData : null; + +// node_modules/axios/lib/platform/browser/classes/Blob.js +var Blob_default = typeof Blob !== "undefined" ? Blob : null; + +// node_modules/axios/lib/platform/browser/index.js +var browser_default = { + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams_default, + FormData: FormData_default, + Blob: Blob_default + }, + protocols: ["http", "https", "file", "blob", "url", "data"] +}; + +// node_modules/axios/lib/platform/common/utils.js +var utils_exports = {}; +__export(utils_exports, { + hasBrowserEnv: () => hasBrowserEnv, + hasStandardBrowserEnv: () => hasStandardBrowserEnv, + hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv +}); +var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; +var hasStandardBrowserEnv = ((product) => { + return hasBrowserEnv && ["ReactNative", "NativeScript", "NS"].indexOf(product) < 0; +})(typeof navigator !== "undefined" && navigator.product); +var hasStandardBrowserWebWorkerEnv = (() => { + return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; +})(); + +// node_modules/axios/lib/platform/index.js +var platform_default = { + ...utils_exports, + ...browser_default +}; + +// node_modules/axios/lib/helpers/toURLEncodedForm.js +function toURLEncodedForm(data, options) { + return toFormData_default(data, new platform_default.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform_default.isNode && utils_default.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +// node_modules/axios/lib/helpers/formDataToJSON.js +function parsePropPath(name) { + return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); +} +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + if (name === "__proto__") + return true; + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils_default.isArray(target) ? target.length : name; + if (isLast) { + if (utils_default.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + return !isNumericKey; + } + if (!target[name] || !utils_default.isObject(target[name])) { + target[name] = []; + } + const result = buildPath(path, value, target[name], index); + if (result && utils_default.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + return !isNumericKey; + } + if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { + const obj = {}; + utils_default.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + return obj; + } + return null; +} +var formDataToJSON_default = formDataToJSON; + +// node_modules/axios/lib/defaults/index.js +function stringifySafely(rawValue, parser, encoder) { + if (utils_default.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils_default.trim(rawValue); + } catch (e) { + if (e.name !== "SyntaxError") { + throw e; + } + } + } + return (encoder || JSON.stringify)(rawValue); +} +var defaults = { + transitional: transitional_default, + adapter: ["xhr", "http"], + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils_default.isObject(data); + if (isObjectPayload && utils_default.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData2 = utils_default.isFormData(data); + if (isFormData2) { + return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data; + } + if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data)) { + return data; + } + if (utils_default.isArrayBufferView(data)) { + return data.buffer; + } + if (utils_default.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList2; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData_default( + isFileList2 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely(data); + } + return data; + }], + transformResponse: [function transformResponse(data) { + const transitional2 = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === "SyntaxError") { + throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + return data; + }], + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform_default.classes.FormData, + Blob: platform_default.classes.Blob + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 + } + } +}; +utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults.headers[method] = {}; +}); +var defaults_default = defaults; + +// node_modules/axios/lib/helpers/parseHeaders.js +var ignoreDuplicateOf = utils_default.toObjectSet([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "user-agent" +]); +var parseHeaders_default = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i = line.indexOf(":"); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; +}; + +// node_modules/axios/lib/core/AxiosHeaders.js +var $internals = Symbol("internals"); +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils_default.isArray(value) ? value.map(normalizeValue) : String(value); +} +function parseTokens(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; +} +var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); +function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { + if (utils_default.isFunction(filter2)) { + return filter2.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils_default.isString(value)) + return; + if (utils_default.isString(filter2)) { + return value.indexOf(filter2) !== -1; + } + if (utils_default.isRegExp(filter2)) { + return filter2.test(value); + } +} +function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} +function buildAccessors(obj, header) { + const accessorName = utils_default.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} +var AxiosHeaders = class { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils_default.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue(_value); + } + } + const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils_default.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders_default(header), valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader(header); + if (header) { + const key = utils_default.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils_default.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils_default.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); + } + } + } + has(header, matcher) { + header = normalizeHeader(header); + if (header) { + const key = utils_default.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + const key = utils_default.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils_default.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + while (i--) { + const key = keys[i]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils_default.forEach(this, (value, header) => { + const key = utils_default.findKey(headers, header); + if (key) { + self2[key] = normalizeValue(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils_default.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals] = this[$internals] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype3 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype3, _header); + accessors[lHeader] = true; + } + } + utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } +}; +AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); +utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; +}); +utils_default.freezeMethods(AxiosHeaders); +var AxiosHeaders_default = AxiosHeaders; + +// node_modules/axios/lib/core/transformData.js +function transformData(fns, response) { + const config = this || defaults_default; + const context = response || config; + const headers = AxiosHeaders_default.from(context.headers); + let data = context.data; + utils_default.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; +} + +// node_modules/axios/lib/cancel/isCancel.js +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + +// node_modules/axios/lib/cancel/CanceledError.js +function CanceledError(message, config, request) { + AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config, request); + this.name = "CanceledError"; +} +utils_default.inherits(CanceledError, AxiosError_default, { + __CANCEL__: true +}); +var CanceledError_default = CanceledError; + +// node_modules/axios/lib/core/settle.js +function settle(resolve, reject, response) { + const validateStatus2 = response.config.validateStatus; + if (!response.status || !validateStatus2 || validateStatus2(response.status)) { + resolve(response); + } else { + reject(new AxiosError_default( + "Request failed with status code " + response.status, + [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +// node_modules/axios/lib/helpers/cookies.js +var cookies_default = platform_default.hasStandardBrowserEnv ? { + write(name, value, expires, path, domain, secure) { + const cookie = [name + "=" + encodeURIComponent(value)]; + utils_default.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils_default.isString(path) && cookie.push("path=" + path); + utils_default.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name) { + this.write(name, "", Date.now() - 864e5); + } +} : { + write() { + }, + read() { + return null; + }, + remove() { + } +}; + +// node_modules/axios/lib/helpers/isAbsoluteURL.js +function isAbsoluteURL(url) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +// node_modules/axios/lib/helpers/combineURLs.js +function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; +} + +// node_modules/axios/lib/core/buildFullPath.js +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +// node_modules/axios/lib/helpers/isURLSameOrigin.js +var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? function standardBrowserEnv() { + const msie = /(msie|trident)/i.test(navigator.userAgent); + const urlParsingNode = document.createElement("a"); + let originURL; + function resolveURL(url) { + let href = url; + if (msie) { + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } + urlParsingNode.setAttribute("href", href); + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname + }; + } + originURL = resolveURL(window.location.href); + return function isURLSameOrigin(requestURL) { + const parsed = utils_default.isString(requestURL) ? resolveURL(requestURL) : requestURL; + return parsed.protocol === originURL.protocol && parsed.host === originURL.host; + }; +}() : function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; +}(); + +// node_modules/axios/lib/helpers/parseProtocol.js +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ""; +} + +// node_modules/axios/lib/helpers/speedometer.js +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; +} +var speedometer_default = speedometer; + +// node_modules/axios/lib/adapters/xhr.js +function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer_default(50, 250); + return (e) => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange ? (total - loaded) / rate : void 0, + event: e + }; + data[isDownloadStream ? "download" : "upload"] = true; + listener(data); + }; +} +var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; +var xhr_default = isXHRAdapterSupported && function(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + let requestData = config.data; + const requestHeaders = AxiosHeaders_default.from(config.headers).normalize(); + let { responseType, withXSRFToken } = config; + let onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + if (config.signal) { + config.signal.removeEventListener("abort", onCanceled); + } + } + let contentType; + if (utils_default.isFormData(requestData)) { + if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); + } else if ((contentType = requestHeaders.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + requestHeaders.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + let request = new XMLHttpRequest(); + if (config.auth) { + const username = config.auth.username || ""; + const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; + requestHeaders.set("Authorization", "Basic " + btoa(username + ":" + password)); + } + const fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + request.timeout = config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders_default.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request)); + request = null; + }; + request.onerror = function handleError() { + reject(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request)); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = config.transitional || transitional_default; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError_default( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, + config, + request + )); + request = null; + }; + if (platform_default.hasStandardBrowserEnv) { + withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(fullPath)) { + const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies_default.read(config.xsrfCookieName); + if (xsrfValue) { + requestHeaders.set(config.xsrfHeaderName, xsrfValue); + } + } + } + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils_default.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = config.responseType; + } + if (typeof config.onDownloadProgress === "function") { + request.addEventListener("progress", progressEventReducer(config.onDownloadProgress, true)); + } + if (typeof config.onUploadProgress === "function" && request.upload) { + request.upload.addEventListener("progress", progressEventReducer(config.onUploadProgress)); + } + if (config.cancelToken || config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError_default(null, config, request) : cancel); + request.abort(); + request = null; + }; + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol(fullPath); + if (protocol && platform_default.protocols.indexOf(protocol) === -1) { + reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config)); + return; + } + request.send(requestData || null); + }); +}; + +// node_modules/axios/lib/adapters/adapters.js +var knownAdapters = { + http: null_default, + xhr: xhr_default +}; +utils_default.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, "name", { value }); + } catch (e) { + } + Object.defineProperty(fn, "adapterName", { value }); + } +}); +var renderReason = (reason) => `- ${reason}`; +var isResolvedHandle = (adapter) => utils_default.isFunction(adapter) || adapter === null || adapter === false; +var adapters_default = { + getAdapter: (adapters) => { + adapters = utils_default.isArray(adapters) ? adapters : [adapters]; + const { length } = adapters; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError_default(`Unknown adapter '${id}'`); + } + } + if (adapter) { + break; + } + rejectedReasons[id || "#" + i] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; + throw new AxiosError_default( + `There is no suitable adapter to dispatch the request ` + s, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters +}; + +// node_modules/axios/lib/core/dispatchRequest.js +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + if (config.signal && config.signal.aborted) { + throw new CanceledError_default(null, config); + } +} +function dispatchRequest(config) { + throwIfCancellationRequested(config); + config.headers = AxiosHeaders_default.from(config.headers); + config.data = transformData.call( + config, + config.transformRequest + ); + if (["post", "put", "patch"].indexOf(config.method) !== -1) { + config.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters_default.getAdapter(config.adapter || defaults_default.adapter); + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + response.data = transformData.call( + config, + config.transformResponse, + response + ); + response.headers = AxiosHeaders_default.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders_default.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); +} + +// node_modules/axios/lib/core/mergeConfig.js +var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? thing.toJSON() : thing; +function mergeConfig(config1, config2) { + config2 = config2 || {}; + const config = {}; + function getMergedValue(target, source, caseless) { + if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { + return utils_default.merge.call({ caseless }, target, source); + } else if (utils_default.isPlainObject(source)) { + return utils_default.merge({}, source); + } else if (utils_default.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a, b, caseless) { + if (!utils_default.isUndefined(b)) { + return getMergedValue(a, b, caseless); + } else if (!utils_default.isUndefined(a)) { + return getMergedValue(void 0, a, caseless); + } + } + function valueFromConfig2(a, b) { + if (!utils_default.isUndefined(b)) { + return getMergedValue(void 0, b); + } + } + function defaultToConfig2(a, b) { + if (!utils_default.isUndefined(b)) { + return getMergedValue(void 0, b); + } else if (!utils_default.isUndefined(a)) { + return getMergedValue(void 0, a); + } + } + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(void 0, a); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) + }; + utils_default.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge2 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge2(config1[prop], config2[prop], prop); + utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); + }); + return config; +} + +// node_modules/axios/lib/env/data.js +var VERSION = "1.6.7"; + +// node_modules/axios/lib/helpers/validator.js +var validators = {}; +["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; + }; +}); +var deprecatedWarnings = {}; +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError_default( + formatMessage(opt, " has been removed" + (version ? " in " + version : "")), + AxiosError_default.ERR_DEPRECATED + ); + } + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version + " and will be removed in the near future" + ) + ); + } + return validator ? validator(value, opt, opts) : true; + }; +}; +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === void 0 || validator(value, opt, options); + if (result !== true) { + throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION); + } + } +} +var validator_default = { + assertOptions, + validators +}; + +// node_modules/axios/lib/core/Axios.js +var validators2 = validator_default.validators; +var Axios = class { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager_default(), + response: new InterceptorManager_default() + }; + } + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy; + Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } + throw err; + } + } + _request(configOrUrl, config) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + config = mergeConfig(this.defaults, config); + const { transitional: transitional2, paramsSerializer, headers } = config; + if (transitional2 !== void 0) { + validator_default.assertOptions(transitional2, { + silentJSONParsing: validators2.transitional(validators2.boolean), + forcedJSONParsing: validators2.transitional(validators2.boolean), + clarifyTimeoutError: validators2.transitional(validators2.boolean) + }, false); + } + if (paramsSerializer != null) { + if (utils_default.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator_default.assertOptions(paramsSerializer, { + encode: validators2.function, + serialize: validators2.function + }, true); + } + } + config.method = (config.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils_default.merge( + headers.common, + headers[config.method] + ); + headers && utils_default.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; + } + ); + config.headers = AxiosHeaders_default.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config; + i = 0; + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; + } + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +}; +utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); +utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url, + data + })); + }; + } + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + "Form"] = generateHTTPMethod(true); +}); +var Axios_default = Axios; + +// node_modules/axios/lib/cancel/CancelToken.js +var CancelToken = class { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) + return; + let i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError_default(message, config, request); + resolvePromise(token.reason); + }); + } + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +}; +var CancelToken_default = CancelToken; + +// node_modules/axios/lib/helpers/spread.js +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +// node_modules/axios/lib/helpers/isAxiosError.js +function isAxiosError(payload) { + return utils_default.isObject(payload) && payload.isAxiosError === true; +} + +// node_modules/axios/lib/helpers/HttpStatusCode.js +var HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511 +}; +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); +var HttpStatusCode_default = HttpStatusCode; + +// node_modules/axios/lib/axios.js +function createInstance(defaultConfig) { + const context = new Axios_default(defaultConfig); + const instance = bind(Axios_default.prototype.request, context); + utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true }); + utils_default.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + return instance; +} +var axios = createInstance(defaults_default); +axios.Axios = Axios_default; +axios.CanceledError = CanceledError_default; +axios.CancelToken = CancelToken_default; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData_default; +axios.AxiosError = AxiosError_default; +axios.Cancel = axios.CanceledError; +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = spread; +axios.isAxiosError = isAxiosError; +axios.mergeConfig = mergeConfig; +axios.AxiosHeaders = AxiosHeaders_default; +axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.getAdapter = adapters_default.getAdapter; +axios.HttpStatusCode = HttpStatusCode_default; +axios.default = axios; +var axios_default = axios; + +// node_modules/axios/index.js +var { + Axios: Axios2, + AxiosError: AxiosError2, + CanceledError: CanceledError2, + isCancel: isCancel2, + CancelToken: CancelToken2, + VERSION: VERSION2, + all: all2, + Cancel, + isAxiosError: isAxiosError2, + spread: spread2, + toFormData: toFormData2, + AxiosHeaders: AxiosHeaders2, + HttpStatusCode: HttpStatusCode2, + formToJSON, + getAdapter, + mergeConfig: mergeConfig2 +} = axios_default; +export { + Axios2 as Axios, + AxiosError2 as AxiosError, + AxiosHeaders2 as AxiosHeaders, + Cancel, + CancelToken2 as CancelToken, + CanceledError2 as CanceledError, + HttpStatusCode2 as HttpStatusCode, + VERSION2 as VERSION, + all2 as all, + axios_default as default, + formToJSON, + getAdapter, + isAxiosError2 as isAxiosError, + isCancel2 as isCancel, + mergeConfig2 as mergeConfig, + spread2 as spread, + toFormData2 as toFormData +}; +//# sourceMappingURL=axios.js.map diff --git a/web/client/node_modules/.vite/deps/axios.js.map b/web/client/node_modules/.vite/deps/axios.js.map new file mode 100644 index 0000000000000000000000000000000000000000..47a1c3f76e7e11b6867a2038ce2e4f76e5c17a1e --- /dev/null +++ b/web/client/node_modules/.vite/deps/axios.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../axios/lib/helpers/bind.js", "../../axios/lib/utils.js", "../../axios/lib/core/AxiosError.js", "../../axios/lib/helpers/null.js", "../../axios/lib/helpers/toFormData.js", "../../axios/lib/helpers/AxiosURLSearchParams.js", "../../axios/lib/helpers/buildURL.js", "../../axios/lib/core/InterceptorManager.js", "../../axios/lib/defaults/transitional.js", "../../axios/lib/platform/browser/classes/URLSearchParams.js", "../../axios/lib/platform/browser/classes/FormData.js", "../../axios/lib/platform/browser/classes/Blob.js", "../../axios/lib/platform/browser/index.js", "../../axios/lib/platform/common/utils.js", "../../axios/lib/platform/index.js", "../../axios/lib/helpers/toURLEncodedForm.js", "../../axios/lib/helpers/formDataToJSON.js", "../../axios/lib/defaults/index.js", "../../axios/lib/helpers/parseHeaders.js", "../../axios/lib/core/AxiosHeaders.js", "../../axios/lib/core/transformData.js", "../../axios/lib/cancel/isCancel.js", "../../axios/lib/cancel/CanceledError.js", "../../axios/lib/core/settle.js", "../../axios/lib/helpers/cookies.js", "../../axios/lib/helpers/isAbsoluteURL.js", "../../axios/lib/helpers/combineURLs.js", "../../axios/lib/core/buildFullPath.js", "../../axios/lib/helpers/isURLSameOrigin.js", "../../axios/lib/helpers/parseProtocol.js", "../../axios/lib/helpers/speedometer.js", "../../axios/lib/adapters/xhr.js", "../../axios/lib/adapters/adapters.js", "../../axios/lib/core/dispatchRequest.js", "../../axios/lib/core/mergeConfig.js", "../../axios/lib/env/data.js", "../../axios/lib/helpers/validator.js", "../../axios/lib/core/Axios.js", "../../axios/lib/cancel/CancelToken.js", "../../axios/lib/helpers/spread.js", "../../axios/lib/helpers/isAxiosError.js", "../../axios/lib/helpers/HttpStatusCode.js", "../../axios/lib/axios.js", "../../axios/index.js"], + "sourcesContent": ["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n", "'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n value = +value;\n return Number.isFinite(value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable\n};\n", "'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n response && (this.response = response);\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n", "// eslint-disable-next-line strict\nexport default null;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n", "'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?object} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n", "'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n", "'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n", "'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n", "'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n", "'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n", "import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n", "const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = (\n (product) => {\n return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0\n })(typeof navigator !== 'undefined' && navigator.product);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv\n}\n", "import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n", "'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n", "'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n", "'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n", "'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n", "'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n", "'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n", "'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n", "'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n", "import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n", "'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n", "'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n", "'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n", "'use strict';\n\nimport utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n// Standard browser envs have full support of the APIs needed to test\n// whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n const msie = /(msie|trident)/i.test(navigator.userAgent);\n const urlParsingNode = document.createElement('a');\n let originURL;\n\n /**\n * Parse a URL to discover its components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n let href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })();\n", "'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n", "'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n", "'use strict';\n\nimport utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport cookies from './../helpers/cookies.js';\nimport buildURL from './../helpers/buildURL.js';\nimport buildFullPath from '../core/buildFullPath.js';\nimport isURLSameOrigin from './../helpers/isURLSameOrigin.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport speedometer from '../helpers/speedometer.js';\n\nfunction progressEventReducer(listener, isDownloadStream) {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e\n };\n\n data[isDownloadStream ? 'download' : 'upload'] = true;\n\n listener(data);\n };\n}\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n let requestData = config.data;\n const requestHeaders = AxiosHeaders.from(config.headers).normalize();\n let {responseType, withXSRFToken} = config;\n let onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n let contentType;\n\n if (utils.isFormData(requestData)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n requestHeaders.setContentType(false); // Let the browser set it\n } else if ((contentType = requestHeaders.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n let request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n const username = config.auth.username || '';\n const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));\n }\n\n const fullPath = buildFullPath(config.baseURL, config.url);\n\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = config.transitional || transitionalDefaults;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if(platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) {\n // Add xsrf header\n const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName);\n\n if (xsrfValue) {\n requestHeaders.set(config.xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(fullPath);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n", "import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n", "'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? thing.toJSON() : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n", "export const VERSION = \"1.6.7\";", "'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n", "'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy;\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n", "'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n", "'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n", "'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n", "const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n", "'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n", "import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n} = axios;\n\nexport {\n axios as default,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n}\n"], + "mappings": ";;;;;AAEe,SAAR,KAAsB,IAAI,SAAS;AACxC,SAAO,SAAS,OAAO;AACrB,WAAO,GAAG,MAAM,SAAS,SAAS;AAAA,EACpC;AACF;;;ACAA,IAAM,EAAC,SAAQ,IAAI,OAAO;AAC1B,IAAM,EAAC,eAAc,IAAI;AAEzB,IAAM,UAAU,WAAS,WAAS;AAC9B,QAAM,MAAM,SAAS,KAAK,KAAK;AAC/B,SAAO,MAAM,SAAS,MAAM,OAAO,IAAI,MAAM,GAAG,EAAE,EAAE,YAAY;AACpE,GAAG,uBAAO,OAAO,IAAI,CAAC;AAEtB,IAAM,aAAa,CAAC,SAAS;AAC3B,SAAO,KAAK,YAAY;AACxB,SAAO,CAAC,UAAU,OAAO,KAAK,MAAM;AACtC;AAEA,IAAM,aAAa,UAAQ,WAAS,OAAO,UAAU;AASrD,IAAM,EAAC,QAAO,IAAI;AASlB,IAAM,cAAc,WAAW,WAAW;AAS1C,SAAS,SAAS,KAAK;AACrB,SAAO,QAAQ,QAAQ,CAAC,YAAY,GAAG,KAAK,IAAI,gBAAgB,QAAQ,CAAC,YAAY,IAAI,WAAW,KAC/F,WAAW,IAAI,YAAY,QAAQ,KAAK,IAAI,YAAY,SAAS,GAAG;AAC3E;AASA,IAAM,gBAAgB,WAAW,aAAa;AAU9C,SAAS,kBAAkB,KAAK;AAC9B,MAAI;AACJ,MAAK,OAAO,gBAAgB,eAAiB,YAAY,QAAS;AAChE,aAAS,YAAY,OAAO,GAAG;AAAA,EACjC,OAAO;AACL,aAAU,OAAS,IAAI,UAAY,cAAc,IAAI,MAAM;AAAA,EAC7D;AACA,SAAO;AACT;AASA,IAAM,WAAW,WAAW,QAAQ;AAQpC,IAAM,aAAa,WAAW,UAAU;AASxC,IAAM,WAAW,WAAW,QAAQ;AASpC,IAAM,WAAW,CAAC,UAAU,UAAU,QAAQ,OAAO,UAAU;AAQ/D,IAAM,YAAY,WAAS,UAAU,QAAQ,UAAU;AASvD,IAAM,gBAAgB,CAAC,QAAQ;AAC7B,MAAI,OAAO,GAAG,MAAM,UAAU;AAC5B,WAAO;AAAA,EACT;AAEA,QAAMA,aAAY,eAAe,GAAG;AACpC,UAAQA,eAAc,QAAQA,eAAc,OAAO,aAAa,OAAO,eAAeA,UAAS,MAAM,SAAS,EAAE,OAAO,eAAe,QAAQ,EAAE,OAAO,YAAY;AACrK;AASA,IAAM,SAAS,WAAW,MAAM;AAShC,IAAM,SAAS,WAAW,MAAM;AAShC,IAAM,SAAS,WAAW,MAAM;AAShC,IAAM,aAAa,WAAW,UAAU;AASxC,IAAM,WAAW,CAAC,QAAQ,SAAS,GAAG,KAAK,WAAW,IAAI,IAAI;AAS9D,IAAM,aAAa,CAAC,UAAU;AAC5B,MAAI;AACJ,SAAO,UACJ,OAAO,aAAa,cAAc,iBAAiB,YAClD,WAAW,MAAM,MAAM,OACpB,OAAO,OAAO,KAAK,OAAO,cAE1B,SAAS,YAAY,WAAW,MAAM,QAAQ,KAAK,MAAM,SAAS,MAAM;AAIjF;AASA,IAAM,oBAAoB,WAAW,iBAAiB;AAStD,IAAM,OAAO,CAAC,QAAQ,IAAI,OACxB,IAAI,KAAK,IAAI,IAAI,QAAQ,sCAAsC,EAAE;AAiBnE,SAAS,QAAQ,KAAK,IAAI,EAAC,aAAa,MAAK,IAAI,CAAC,GAAG;AAEnD,MAAI,QAAQ,QAAQ,OAAO,QAAQ,aAAa;AAC9C;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AAGJ,MAAI,OAAO,QAAQ,UAAU;AAE3B,UAAM,CAAC,GAAG;AAAA,EACZ;AAEA,MAAI,QAAQ,GAAG,GAAG;AAEhB,SAAK,IAAI,GAAG,IAAI,IAAI,QAAQ,IAAI,GAAG,KAAK;AACtC,SAAG,KAAK,MAAM,IAAI,IAAI,GAAG,GAAG;AAAA,IAC9B;AAAA,EACF,OAAO;AAEL,UAAM,OAAO,aAAa,OAAO,oBAAoB,GAAG,IAAI,OAAO,KAAK,GAAG;AAC3E,UAAM,MAAM,KAAK;AACjB,QAAI;AAEJ,SAAK,IAAI,GAAG,IAAI,KAAK,KAAK;AACxB,YAAM,KAAK;AACX,SAAG,KAAK,MAAM,IAAI,MAAM,KAAK,GAAG;AAAA,IAClC;AAAA,EACF;AACF;AAEA,SAAS,QAAQ,KAAK,KAAK;AACzB,QAAM,IAAI,YAAY;AACtB,QAAM,OAAO,OAAO,KAAK,GAAG;AAC5B,MAAI,IAAI,KAAK;AACb,MAAI;AACJ,SAAO,MAAM,GAAG;AACd,WAAO,KAAK;AACZ,QAAI,QAAQ,KAAK,YAAY,GAAG;AAC9B,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAM,WAAW,MAAM;AAErB,MAAI,OAAO,eAAe;AAAa,WAAO;AAC9C,SAAO,OAAO,SAAS,cAAc,OAAQ,OAAO,WAAW,cAAc,SAAS;AACxF,GAAG;AAEH,IAAM,mBAAmB,CAAC,YAAY,CAAC,YAAY,OAAO,KAAK,YAAY;AAoB3E,SAAS,QAAmC;AAC1C,QAAM,EAAC,SAAQ,IAAI,iBAAiB,IAAI,KAAK,QAAQ,CAAC;AACtD,QAAM,SAAS,CAAC;AAChB,QAAM,cAAc,CAAC,KAAK,QAAQ;AAChC,UAAM,YAAY,YAAY,QAAQ,QAAQ,GAAG,KAAK;AACtD,QAAI,cAAc,OAAO,UAAU,KAAK,cAAc,GAAG,GAAG;AAC1D,aAAO,aAAa,MAAM,OAAO,YAAY,GAAG;AAAA,IAClD,WAAW,cAAc,GAAG,GAAG;AAC7B,aAAO,aAAa,MAAM,CAAC,GAAG,GAAG;AAAA,IACnC,WAAW,QAAQ,GAAG,GAAG;AACvB,aAAO,aAAa,IAAI,MAAM;AAAA,IAChC,OAAO;AACL,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,IAAI,GAAG,KAAK;AAChD,cAAU,MAAM,QAAQ,UAAU,IAAI,WAAW;AAAA,EACnD;AACA,SAAO;AACT;AAYA,IAAM,SAAS,CAAC,GAAG,GAAG,SAAS,EAAC,WAAU,IAAG,CAAC,MAAM;AAClD,UAAQ,GAAG,CAAC,KAAK,QAAQ;AACvB,QAAI,WAAW,WAAW,GAAG,GAAG;AAC9B,QAAE,OAAO,KAAK,KAAK,OAAO;AAAA,IAC5B,OAAO;AACL,QAAE,OAAO;AAAA,IACX;AAAA,EACF,GAAG,EAAC,WAAU,CAAC;AACf,SAAO;AACT;AASA,IAAM,WAAW,CAAC,YAAY;AAC5B,MAAI,QAAQ,WAAW,CAAC,MAAM,OAAQ;AACpC,cAAU,QAAQ,MAAM,CAAC;AAAA,EAC3B;AACA,SAAO;AACT;AAWA,IAAM,WAAW,CAAC,aAAa,kBAAkB,OAAOC,iBAAgB;AACtE,cAAY,YAAY,OAAO,OAAO,iBAAiB,WAAWA,YAAW;AAC7E,cAAY,UAAU,cAAc;AACpC,SAAO,eAAe,aAAa,SAAS;AAAA,IAC1C,OAAO,iBAAiB;AAAA,EAC1B,CAAC;AACD,WAAS,OAAO,OAAO,YAAY,WAAW,KAAK;AACrD;AAWA,IAAM,eAAe,CAAC,WAAW,SAASC,SAAQ,eAAe;AAC/D,MAAI;AACJ,MAAI;AACJ,MAAI;AACJ,QAAM,SAAS,CAAC;AAEhB,YAAU,WAAW,CAAC;AAEtB,MAAI,aAAa;AAAM,WAAO;AAE9B,KAAG;AACD,YAAQ,OAAO,oBAAoB,SAAS;AAC5C,QAAI,MAAM;AACV,WAAO,MAAM,GAAG;AACd,aAAO,MAAM;AACb,WAAK,CAAC,cAAc,WAAW,MAAM,WAAW,OAAO,MAAM,CAAC,OAAO,OAAO;AAC1E,gBAAQ,QAAQ,UAAU;AAC1B,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF;AACA,gBAAYA,YAAW,SAAS,eAAe,SAAS;AAAA,EAC1D,SAAS,cAAc,CAACA,WAAUA,QAAO,WAAW,OAAO,MAAM,cAAc,OAAO;AAEtF,SAAO;AACT;AAWA,IAAM,WAAW,CAAC,KAAK,cAAc,aAAa;AAChD,QAAM,OAAO,GAAG;AAChB,MAAI,aAAa,UAAa,WAAW,IAAI,QAAQ;AACnD,eAAW,IAAI;AAAA,EACjB;AACA,cAAY,aAAa;AACzB,QAAM,YAAY,IAAI,QAAQ,cAAc,QAAQ;AACpD,SAAO,cAAc,MAAM,cAAc;AAC3C;AAUA,IAAM,UAAU,CAAC,UAAU;AACzB,MAAI,CAAC;AAAO,WAAO;AACnB,MAAI,QAAQ,KAAK;AAAG,WAAO;AAC3B,MAAI,IAAI,MAAM;AACd,MAAI,CAAC,SAAS,CAAC;AAAG,WAAO;AACzB,QAAM,MAAM,IAAI,MAAM,CAAC;AACvB,SAAO,MAAM,GAAG;AACd,QAAI,KAAK,MAAM;AAAA,EACjB;AACA,SAAO;AACT;AAWA,IAAM,gBAAgB,gBAAc;AAElC,SAAO,WAAS;AACd,WAAO,cAAc,iBAAiB;AAAA,EACxC;AACF,GAAG,OAAO,eAAe,eAAe,eAAe,UAAU,CAAC;AAUlE,IAAM,eAAe,CAAC,KAAK,OAAO;AAChC,QAAM,YAAY,OAAO,IAAI,OAAO;AAEpC,QAAM,WAAW,UAAU,KAAK,GAAG;AAEnC,MAAI;AAEJ,UAAQ,SAAS,SAAS,KAAK,MAAM,CAAC,OAAO,MAAM;AACjD,UAAM,OAAO,OAAO;AACpB,OAAG,KAAK,KAAK,KAAK,IAAI,KAAK,EAAE;AAAA,EAC/B;AACF;AAUA,IAAM,WAAW,CAAC,QAAQ,QAAQ;AAChC,MAAI;AACJ,QAAM,MAAM,CAAC;AAEb,UAAQ,UAAU,OAAO,KAAK,GAAG,OAAO,MAAM;AAC5C,QAAI,KAAK,OAAO;AAAA,EAClB;AAEA,SAAO;AACT;AAGA,IAAM,aAAa,WAAW,iBAAiB;AAE/C,IAAM,cAAc,SAAO;AACzB,SAAO,IAAI,YAAY,EAAE;AAAA,IAAQ;AAAA,IAC/B,SAAS,SAAS,GAAG,IAAI,IAAI;AAC3B,aAAO,GAAG,YAAY,IAAI;AAAA,IAC5B;AAAA,EACF;AACF;AAGA,IAAM,kBAAkB,CAAC,EAAC,gBAAAC,gBAAc,MAAM,CAAC,KAAK,SAASA,gBAAe,KAAK,KAAK,IAAI,GAAG,OAAO,SAAS;AAS7G,IAAM,WAAW,WAAW,QAAQ;AAEpC,IAAM,oBAAoB,CAAC,KAAK,YAAY;AAC1C,QAAMF,eAAc,OAAO,0BAA0B,GAAG;AACxD,QAAM,qBAAqB,CAAC;AAE5B,UAAQA,cAAa,CAAC,YAAY,SAAS;AACzC,QAAI;AACJ,SAAK,MAAM,QAAQ,YAAY,MAAM,GAAG,OAAO,OAAO;AACpD,yBAAmB,QAAQ,OAAO;AAAA,IACpC;AAAA,EACF,CAAC;AAED,SAAO,iBAAiB,KAAK,kBAAkB;AACjD;AAOA,IAAM,gBAAgB,CAAC,QAAQ;AAC7B,oBAAkB,KAAK,CAAC,YAAY,SAAS;AAE3C,QAAI,WAAW,GAAG,KAAK,CAAC,aAAa,UAAU,QAAQ,EAAE,QAAQ,IAAI,MAAM,IAAI;AAC7E,aAAO;AAAA,IACT;AAEA,UAAM,QAAQ,IAAI;AAElB,QAAI,CAAC,WAAW,KAAK;AAAG;AAExB,eAAW,aAAa;AAExB,QAAI,cAAc,YAAY;AAC5B,iBAAW,WAAW;AACtB;AAAA,IACF;AAEA,QAAI,CAAC,WAAW,KAAK;AACnB,iBAAW,MAAM,MAAM;AACrB,cAAM,MAAM,uCAAwC,OAAO,GAAI;AAAA,MACjE;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEA,IAAM,cAAc,CAAC,eAAe,cAAc;AAChD,QAAM,MAAM,CAAC;AAEb,QAAM,SAAS,CAAC,QAAQ;AACtB,QAAI,QAAQ,WAAS;AACnB,UAAI,SAAS;AAAA,IACf,CAAC;AAAA,EACH;AAEA,UAAQ,aAAa,IAAI,OAAO,aAAa,IAAI,OAAO,OAAO,aAAa,EAAE,MAAM,SAAS,CAAC;AAE9F,SAAO;AACT;AAEA,IAAM,OAAO,MAAM;AAAC;AAEpB,IAAM,iBAAiB,CAAC,OAAO,iBAAiB;AAC9C,UAAQ,CAAC;AACT,SAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;AAEA,IAAM,QAAQ;AAEd,IAAM,QAAQ;AAEd,IAAM,WAAW;AAAA,EACf;AAAA,EACA;AAAA,EACA,aAAa,QAAQ,MAAM,YAAY,IAAI;AAC7C;AAEA,IAAM,iBAAiB,CAAC,OAAO,IAAI,WAAW,SAAS,gBAAgB;AACrE,MAAI,MAAM;AACV,QAAM,EAAC,OAAM,IAAI;AACjB,SAAO,QAAQ;AACb,WAAO,SAAS,KAAK,OAAO,IAAI,SAAO;AAAA,EACzC;AAEA,SAAO;AACT;AASA,SAAS,oBAAoB,OAAO;AAClC,SAAO,CAAC,EAAE,SAAS,WAAW,MAAM,MAAM,KAAK,MAAM,OAAO,iBAAiB,cAAc,MAAM,OAAO;AAC1G;AAEA,IAAM,eAAe,CAAC,QAAQ;AAC5B,QAAM,QAAQ,IAAI,MAAM,EAAE;AAE1B,QAAM,QAAQ,CAAC,QAAQ,MAAM;AAE3B,QAAI,SAAS,MAAM,GAAG;AACpB,UAAI,MAAM,QAAQ,MAAM,KAAK,GAAG;AAC9B;AAAA,MACF;AAEA,UAAG,EAAE,YAAY,SAAS;AACxB,cAAM,KAAK;AACX,cAAM,SAAS,QAAQ,MAAM,IAAI,CAAC,IAAI,CAAC;AAEvC,gBAAQ,QAAQ,CAAC,OAAO,QAAQ;AAC9B,gBAAM,eAAe,MAAM,OAAO,IAAI,CAAC;AACvC,WAAC,YAAY,YAAY,MAAM,OAAO,OAAO;AAAA,QAC/C,CAAC;AAED,cAAM,KAAK;AAEX,eAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,MAAM,KAAK,CAAC;AACrB;AAEA,IAAM,YAAY,WAAW,eAAe;AAE5C,IAAM,aAAa,CAAC,UAClB,UAAU,SAAS,KAAK,KAAK,WAAW,KAAK,MAAM,WAAW,MAAM,IAAI,KAAK,WAAW,MAAM,KAAK;AAErG,IAAO,gBAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACnsBA,SAAS,WAAW,SAAS,MAAM,QAAQ,SAAS,UAAU;AAC5D,QAAM,KAAK,IAAI;AAEf,MAAI,MAAM,mBAAmB;AAC3B,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD,OAAO;AACL,SAAK,QAAS,IAAI,MAAM,EAAG;AAAA,EAC7B;AAEA,OAAK,UAAU;AACf,OAAK,OAAO;AACZ,WAAS,KAAK,OAAO;AACrB,aAAW,KAAK,SAAS;AACzB,cAAY,KAAK,UAAU;AAC3B,eAAa,KAAK,WAAW;AAC/B;AAEA,cAAM,SAAS,YAAY,OAAO;AAAA,EAChC,QAAQ,SAAS,SAAS;AACxB,WAAO;AAAA,MAEL,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MAEX,aAAa,KAAK;AAAA,MAClB,QAAQ,KAAK;AAAA,MAEb,UAAU,KAAK;AAAA,MACf,YAAY,KAAK;AAAA,MACjB,cAAc,KAAK;AAAA,MACnB,OAAO,KAAK;AAAA,MAEZ,QAAQ,cAAM,aAAa,KAAK,MAAM;AAAA,MACtC,MAAM,KAAK;AAAA,MACX,QAAQ,KAAK,YAAY,KAAK,SAAS,SAAS,KAAK,SAAS,SAAS;AAAA,IACzE;AAAA,EACF;AACF,CAAC;AAED,IAAM,YAAY,WAAW;AAC7B,IAAM,cAAc,CAAC;AAErB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAEF,EAAE,QAAQ,UAAQ;AAChB,cAAY,QAAQ,EAAC,OAAO,KAAI;AAClC,CAAC;AAED,OAAO,iBAAiB,YAAY,WAAW;AAC/C,OAAO,eAAe,WAAW,gBAAgB,EAAC,OAAO,KAAI,CAAC;AAG9D,WAAW,OAAO,CAAC,OAAO,MAAM,QAAQ,SAAS,UAAU,gBAAgB;AACzE,QAAM,aAAa,OAAO,OAAO,SAAS;AAE1C,gBAAM,aAAa,OAAO,YAAY,SAASG,QAAO,KAAK;AACzD,WAAO,QAAQ,MAAM;AAAA,EACvB,GAAG,UAAQ;AACT,WAAO,SAAS;AAAA,EAClB,CAAC;AAED,aAAW,KAAK,YAAY,MAAM,SAAS,MAAM,QAAQ,SAAS,QAAQ;AAE1E,aAAW,QAAQ;AAEnB,aAAW,OAAO,MAAM;AAExB,iBAAe,OAAO,OAAO,YAAY,WAAW;AAEpD,SAAO;AACT;AAEA,IAAO,qBAAQ;;;AClGf,IAAO,eAAQ;;;ACaf,SAAS,YAAY,OAAO;AAC1B,SAAO,cAAM,cAAc,KAAK,KAAK,cAAM,QAAQ,KAAK;AAC1D;AASA,SAAS,eAAe,KAAK;AAC3B,SAAO,cAAM,SAAS,KAAK,IAAI,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AACxD;AAWA,SAAS,UAAU,MAAM,KAAK,MAAM;AAClC,MAAI,CAAC;AAAM,WAAO;AAClB,SAAO,KAAK,OAAO,GAAG,EAAE,IAAI,SAAS,KAAK,OAAO,GAAG;AAElD,YAAQ,eAAe,KAAK;AAC5B,WAAO,CAAC,QAAQ,IAAI,MAAM,QAAQ,MAAM;AAAA,EAC1C,CAAC,EAAE,KAAK,OAAO,MAAM,EAAE;AACzB;AASA,SAAS,YAAY,KAAK;AACxB,SAAO,cAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,KAAK,WAAW;AACpD;AAEA,IAAM,aAAa,cAAM,aAAa,eAAO,CAAC,GAAG,MAAM,SAAS,OAAO,MAAM;AAC3E,SAAO,WAAW,KAAK,IAAI;AAC7B,CAAC;AAyBD,SAAS,WAAW,KAAK,UAAU,SAAS;AAC1C,MAAI,CAAC,cAAM,SAAS,GAAG,GAAG;AACxB,UAAM,IAAI,UAAU,0BAA0B;AAAA,EAChD;AAGA,aAAW,YAAY,KAAK,gBAAoB,UAAU;AAG1D,YAAU,cAAM,aAAa,SAAS;AAAA,IACpC,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,SAAS;AAAA,EACX,GAAG,OAAO,SAAS,QAAQ,QAAQ,QAAQ;AAEzC,WAAO,CAAC,cAAM,YAAY,OAAO,OAAO;AAAA,EAC1C,CAAC;AAED,QAAM,aAAa,QAAQ;AAE3B,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,OAAO,QAAQ;AACrB,QAAM,UAAU,QAAQ;AACxB,QAAM,QAAQ,QAAQ,QAAQ,OAAO,SAAS,eAAe;AAC7D,QAAM,UAAU,SAAS,cAAM,oBAAoB,QAAQ;AAE3D,MAAI,CAAC,cAAM,WAAW,OAAO,GAAG;AAC9B,UAAM,IAAI,UAAU,4BAA4B;AAAA,EAClD;AAEA,WAAS,aAAa,OAAO;AAC3B,QAAI,UAAU;AAAM,aAAO;AAE3B,QAAI,cAAM,OAAO,KAAK,GAAG;AACvB,aAAO,MAAM,YAAY;AAAA,IAC3B;AAEA,QAAI,CAAC,WAAW,cAAM,OAAO,KAAK,GAAG;AACnC,YAAM,IAAI,mBAAW,8CAA8C;AAAA,IACrE;AAEA,QAAI,cAAM,cAAc,KAAK,KAAK,cAAM,aAAa,KAAK,GAAG;AAC3D,aAAO,WAAW,OAAO,SAAS,aAAa,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK;AAAA,IACtF;AAEA,WAAO;AAAA,EACT;AAYA,WAAS,eAAe,OAAO,KAAK,MAAM;AACxC,QAAI,MAAM;AAEV,QAAI,SAAS,CAAC,QAAQ,OAAO,UAAU,UAAU;AAC/C,UAAI,cAAM,SAAS,KAAK,IAAI,GAAG;AAE7B,cAAM,aAAa,MAAM,IAAI,MAAM,GAAG,EAAE;AAExC,gBAAQ,KAAK,UAAU,KAAK;AAAA,MAC9B,WACG,cAAM,QAAQ,KAAK,KAAK,YAAY,KAAK,MACxC,cAAM,WAAW,KAAK,KAAK,cAAM,SAAS,KAAK,IAAI,OAAO,MAAM,cAAM,QAAQ,KAAK,IAClF;AAEH,cAAM,eAAe,GAAG;AAExB,YAAI,QAAQ,SAAS,KAAK,IAAI,OAAO;AACnC,YAAE,cAAM,YAAY,EAAE,KAAK,OAAO,SAAS,SAAS;AAAA,YAElD,YAAY,OAAO,UAAU,CAAC,GAAG,GAAG,OAAO,IAAI,IAAK,YAAY,OAAO,MAAM,MAAM;AAAA,YACnF,aAAa,EAAE;AAAA,UACjB;AAAA,QACF,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,QAAI,YAAY,KAAK,GAAG;AACtB,aAAO;AAAA,IACT;AAEA,aAAS,OAAO,UAAU,MAAM,KAAK,IAAI,GAAG,aAAa,KAAK,CAAC;AAE/D,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,CAAC;AAEf,QAAM,iBAAiB,OAAO,OAAO,YAAY;AAAA,IAC/C;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,WAAS,MAAM,OAAO,MAAM;AAC1B,QAAI,cAAM,YAAY,KAAK;AAAG;AAE9B,QAAI,MAAM,QAAQ,KAAK,MAAM,IAAI;AAC/B,YAAM,MAAM,oCAAoC,KAAK,KAAK,GAAG,CAAC;AAAA,IAChE;AAEA,UAAM,KAAK,KAAK;AAEhB,kBAAM,QAAQ,OAAO,SAAS,KAAK,IAAI,KAAK;AAC1C,YAAM,SAAS,EAAE,cAAM,YAAY,EAAE,KAAK,OAAO,SAAS,QAAQ;AAAA,QAChE;AAAA,QAAU;AAAA,QAAI,cAAM,SAAS,GAAG,IAAI,IAAI,KAAK,IAAI;AAAA,QAAK;AAAA,QAAM;AAAA,MAC9D;AAEA,UAAI,WAAW,MAAM;AACnB,cAAM,IAAI,OAAO,KAAK,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC;AAAA,MAC3C;AAAA,IACF,CAAC;AAED,UAAM,IAAI;AAAA,EACZ;AAEA,MAAI,CAAC,cAAM,SAAS,GAAG,GAAG;AACxB,UAAM,IAAI,UAAU,wBAAwB;AAAA,EAC9C;AAEA,QAAM,GAAG;AAET,SAAO;AACT;AAEA,IAAO,qBAAQ;;;AC9Mf,SAAS,OAAO,KAAK;AACnB,QAAM,UAAU;AAAA,IACd,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AACA,SAAO,mBAAmB,GAAG,EAAE,QAAQ,oBAAoB,SAAS,SAAS,OAAO;AAClF,WAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAUA,SAAS,qBAAqB,QAAQ,SAAS;AAC7C,OAAK,SAAS,CAAC;AAEf,YAAU,mBAAW,QAAQ,MAAM,OAAO;AAC5C;AAEA,IAAMC,aAAY,qBAAqB;AAEvCA,WAAU,SAAS,SAAS,OAAO,MAAM,OAAO;AAC9C,OAAK,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAChC;AAEAA,WAAU,WAAW,SAASC,UAAS,SAAS;AAC9C,QAAM,UAAU,UAAU,SAAS,OAAO;AACxC,WAAO,QAAQ,KAAK,MAAM,OAAO,MAAM;AAAA,EACzC,IAAI;AAEJ,SAAO,KAAK,OAAO,IAAI,SAAS,KAAK,MAAM;AACzC,WAAO,QAAQ,KAAK,EAAE,IAAI,MAAM,QAAQ,KAAK,EAAE;AAAA,EACjD,GAAG,EAAE,EAAE,KAAK,GAAG;AACjB;AAEA,IAAO,+BAAQ;;;AC5Cf,SAASC,QAAO,KAAK;AACnB,SAAO,mBAAmB,GAAG,EAC3B,QAAQ,SAAS,GAAG,EACpB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,SAAS,GAAG,EACpB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,SAAS,GAAG,EACpB,QAAQ,SAAS,GAAG;AACxB;AAWe,SAAR,SAA0B,KAAK,QAAQ,SAAS;AAErD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,WAAW,QAAQ,UAAUA;AAE7C,QAAM,cAAc,WAAW,QAAQ;AAEvC,MAAI;AAEJ,MAAI,aAAa;AACf,uBAAmB,YAAY,QAAQ,OAAO;AAAA,EAChD,OAAO;AACL,uBAAmB,cAAM,kBAAkB,MAAM,IAC/C,OAAO,SAAS,IAChB,IAAI,6BAAqB,QAAQ,OAAO,EAAE,SAAS,OAAO;AAAA,EAC9D;AAEA,MAAI,kBAAkB;AACpB,UAAM,gBAAgB,IAAI,QAAQ,GAAG;AAErC,QAAI,kBAAkB,IAAI;AACxB,YAAM,IAAI,MAAM,GAAG,aAAa;AAAA,IAClC;AACA,YAAQ,IAAI,QAAQ,GAAG,MAAM,KAAK,MAAM,OAAO;AAAA,EACjD;AAEA,SAAO;AACT;;;AC1DA,IAAM,qBAAN,MAAyB;AAAA,EACvB,cAAc;AACZ,SAAK,WAAW,CAAC;AAAA,EACnB;AAAA,EAUA,IAAI,WAAW,UAAU,SAAS;AAChC,SAAK,SAAS,KAAK;AAAA,MACjB;AAAA,MACA;AAAA,MACA,aAAa,UAAU,QAAQ,cAAc;AAAA,MAC7C,SAAS,UAAU,QAAQ,UAAU;AAAA,IACvC,CAAC;AACD,WAAO,KAAK,SAAS,SAAS;AAAA,EAChC;AAAA,EASA,MAAM,IAAI;AACR,QAAI,KAAK,SAAS,KAAK;AACrB,WAAK,SAAS,MAAM;AAAA,IACtB;AAAA,EACF;AAAA,EAOA,QAAQ;AACN,QAAI,KAAK,UAAU;AACjB,WAAK,WAAW,CAAC;AAAA,IACnB;AAAA,EACF;AAAA,EAYA,QAAQ,IAAI;AACV,kBAAM,QAAQ,KAAK,UAAU,SAAS,eAAe,GAAG;AACtD,UAAI,MAAM,MAAM;AACd,WAAG,CAAC;AAAA,MACN;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAEA,IAAO,6BAAQ;;;ACpEf,IAAO,uBAAQ;AAAA,EACb,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,qBAAqB;AACvB;;;ACHA,IAAO,0BAAQ,OAAO,oBAAoB,cAAc,kBAAkB;;;ACD1E,IAAO,mBAAQ,OAAO,aAAa,cAAc,WAAW;;;ACA5D,IAAO,eAAQ,OAAO,SAAS,cAAc,OAAO;;;ACEpD,IAAO,kBAAQ;AAAA,EACb,WAAW;AAAA,EACX,SAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,WAAW,CAAC,QAAQ,SAAS,QAAQ,QAAQ,OAAO,MAAM;AAC5D;;;ACZA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,gBAAgB,OAAO,WAAW,eAAe,OAAO,aAAa;AAmB3E,IAAM,yBACJ,CAAC,YAAY;AACX,SAAO,iBAAiB,CAAC,eAAe,gBAAgB,IAAI,EAAE,QAAQ,OAAO,IAAI;AACnF,GAAG,OAAO,cAAc,eAAe,UAAU,OAAO;AAW1D,IAAM,kCAAkC,MAAM;AAC5C,SACE,OAAO,sBAAsB,eAE7B,gBAAgB,qBAChB,OAAO,KAAK,kBAAkB;AAElC,GAAG;;;ACrCH,IAAO,mBAAQ;AAAA,EACb,GAAG;AAAA,EACH,GAAG;AACL;;;ACAe,SAAR,iBAAkC,MAAM,SAAS;AACtD,SAAO,mBAAW,MAAM,IAAI,iBAAS,QAAQ,gBAAgB,GAAG,OAAO,OAAO;AAAA,IAC5E,SAAS,SAAS,OAAO,KAAK,MAAM,SAAS;AAC3C,UAAI,iBAAS,UAAU,cAAM,SAAS,KAAK,GAAG;AAC5C,aAAK,OAAO,KAAK,MAAM,SAAS,QAAQ,CAAC;AACzC,eAAO;AAAA,MACT;AAEA,aAAO,QAAQ,eAAe,MAAM,MAAM,SAAS;AAAA,IACrD;AAAA,EACF,GAAG,OAAO,CAAC;AACb;;;ACNA,SAAS,cAAc,MAAM;AAK3B,SAAO,cAAM,SAAS,iBAAiB,IAAI,EAAE,IAAI,WAAS;AACxD,WAAO,MAAM,OAAO,OAAO,KAAK,MAAM,MAAM,MAAM;AAAA,EACpD,CAAC;AACH;AASA,SAAS,cAAc,KAAK;AAC1B,QAAM,MAAM,CAAC;AACb,QAAM,OAAO,OAAO,KAAK,GAAG;AAC5B,MAAI;AACJ,QAAM,MAAM,KAAK;AACjB,MAAI;AACJ,OAAK,IAAI,GAAG,IAAI,KAAK,KAAK;AACxB,UAAM,KAAK;AACX,QAAI,OAAO,IAAI;AAAA,EACjB;AACA,SAAO;AACT;AASA,SAAS,eAAe,UAAU;AAChC,WAAS,UAAU,MAAM,OAAO,QAAQ,OAAO;AAC7C,QAAI,OAAO,KAAK;AAEhB,QAAI,SAAS;AAAa,aAAO;AAEjC,UAAM,eAAe,OAAO,SAAS,CAAC,IAAI;AAC1C,UAAM,SAAS,SAAS,KAAK;AAC7B,WAAO,CAAC,QAAQ,cAAM,QAAQ,MAAM,IAAI,OAAO,SAAS;AAExD,QAAI,QAAQ;AACV,UAAI,cAAM,WAAW,QAAQ,IAAI,GAAG;AAClC,eAAO,QAAQ,CAAC,OAAO,OAAO,KAAK;AAAA,MACrC,OAAO;AACL,eAAO,QAAQ;AAAA,MACjB;AAEA,aAAO,CAAC;AAAA,IACV;AAEA,QAAI,CAAC,OAAO,SAAS,CAAC,cAAM,SAAS,OAAO,KAAK,GAAG;AAClD,aAAO,QAAQ,CAAC;AAAA,IAClB;AAEA,UAAM,SAAS,UAAU,MAAM,OAAO,OAAO,OAAO,KAAK;AAEzD,QAAI,UAAU,cAAM,QAAQ,OAAO,KAAK,GAAG;AACzC,aAAO,QAAQ,cAAc,OAAO,KAAK;AAAA,IAC3C;AAEA,WAAO,CAAC;AAAA,EACV;AAEA,MAAI,cAAM,WAAW,QAAQ,KAAK,cAAM,WAAW,SAAS,OAAO,GAAG;AACpE,UAAM,MAAM,CAAC;AAEb,kBAAM,aAAa,UAAU,CAAC,MAAM,UAAU;AAC5C,gBAAU,cAAc,IAAI,GAAG,OAAO,KAAK,CAAC;AAAA,IAC9C,CAAC;AAED,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEA,IAAO,yBAAQ;;;AC1Ef,SAAS,gBAAgB,UAAU,QAAQ,SAAS;AAClD,MAAI,cAAM,SAAS,QAAQ,GAAG;AAC5B,QAAI;AACF,OAAC,UAAU,KAAK,OAAO,QAAQ;AAC/B,aAAO,cAAM,KAAK,QAAQ;AAAA,IAC5B,SAAS,GAAP;AACA,UAAI,EAAE,SAAS,eAAe;AAC5B,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,UAAQ,WAAW,KAAK,WAAW,QAAQ;AAC7C;AAEA,IAAM,WAAW;AAAA,EAEf,cAAc;AAAA,EAEd,SAAS,CAAC,OAAO,MAAM;AAAA,EAEvB,kBAAkB,CAAC,SAAS,iBAAiB,MAAM,SAAS;AAC1D,UAAM,cAAc,QAAQ,eAAe,KAAK;AAChD,UAAM,qBAAqB,YAAY,QAAQ,kBAAkB,IAAI;AACrE,UAAM,kBAAkB,cAAM,SAAS,IAAI;AAE3C,QAAI,mBAAmB,cAAM,WAAW,IAAI,GAAG;AAC7C,aAAO,IAAI,SAAS,IAAI;AAAA,IAC1B;AAEA,UAAMC,cAAa,cAAM,WAAW,IAAI;AAExC,QAAIA,aAAY;AACd,aAAO,qBAAqB,KAAK,UAAU,uBAAe,IAAI,CAAC,IAAI;AAAA,IACrE;AAEA,QAAI,cAAM,cAAc,IAAI,KAC1B,cAAM,SAAS,IAAI,KACnB,cAAM,SAAS,IAAI,KACnB,cAAM,OAAO,IAAI,KACjB,cAAM,OAAO,IAAI,GACjB;AACA,aAAO;AAAA,IACT;AACA,QAAI,cAAM,kBAAkB,IAAI,GAAG;AACjC,aAAO,KAAK;AAAA,IACd;AACA,QAAI,cAAM,kBAAkB,IAAI,GAAG;AACjC,cAAQ,eAAe,mDAAmD,KAAK;AAC/E,aAAO,KAAK,SAAS;AAAA,IACvB;AAEA,QAAIC;AAEJ,QAAI,iBAAiB;AACnB,UAAI,YAAY,QAAQ,mCAAmC,IAAI,IAAI;AACjE,eAAO,iBAAiB,MAAM,KAAK,cAAc,EAAE,SAAS;AAAA,MAC9D;AAEA,WAAKA,cAAa,cAAM,WAAW,IAAI,MAAM,YAAY,QAAQ,qBAAqB,IAAI,IAAI;AAC5F,cAAM,YAAY,KAAK,OAAO,KAAK,IAAI;AAEvC,eAAO;AAAA,UACLA,cAAa,EAAC,WAAW,KAAI,IAAI;AAAA,UACjC,aAAa,IAAI,UAAU;AAAA,UAC3B,KAAK;AAAA,QACP;AAAA,MACF;AAAA,IACF;AAEA,QAAI,mBAAmB,oBAAqB;AAC1C,cAAQ,eAAe,oBAAoB,KAAK;AAChD,aAAO,gBAAgB,IAAI;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT,CAAC;AAAA,EAED,mBAAmB,CAAC,SAAS,kBAAkB,MAAM;AACnD,UAAMC,gBAAe,KAAK,gBAAgB,SAAS;AACnD,UAAM,oBAAoBA,iBAAgBA,cAAa;AACvD,UAAM,gBAAgB,KAAK,iBAAiB;AAE5C,QAAI,QAAQ,cAAM,SAAS,IAAI,MAAO,qBAAqB,CAAC,KAAK,gBAAiB,gBAAgB;AAChG,YAAM,oBAAoBA,iBAAgBA,cAAa;AACvD,YAAM,oBAAoB,CAAC,qBAAqB;AAEhD,UAAI;AACF,eAAO,KAAK,MAAM,IAAI;AAAA,MACxB,SAAS,GAAP;AACA,YAAI,mBAAmB;AACrB,cAAI,EAAE,SAAS,eAAe;AAC5B,kBAAM,mBAAW,KAAK,GAAG,mBAAW,kBAAkB,MAAM,MAAM,KAAK,QAAQ;AAAA,UACjF;AACA,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT,CAAC;AAAA,EAMD,SAAS;AAAA,EAET,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAEhB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EAEf,KAAK;AAAA,IACH,UAAU,iBAAS,QAAQ;AAAA,IAC3B,MAAM,iBAAS,QAAQ;AAAA,EACzB;AAAA,EAEA,gBAAgB,SAAS,eAAe,QAAQ;AAC9C,WAAO,UAAU,OAAO,SAAS;AAAA,EACnC;AAAA,EAEA,SAAS;AAAA,IACP,QAAQ;AAAA,MACN,UAAU;AAAA,MACV,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAEA,cAAM,QAAQ,CAAC,UAAU,OAAO,QAAQ,QAAQ,OAAO,OAAO,GAAG,CAAC,WAAW;AAC3E,WAAS,QAAQ,UAAU,CAAC;AAC9B,CAAC;AAED,IAAO,mBAAQ;;;ACrJf,IAAM,oBAAoB,cAAM,YAAY;AAAA,EAC1C;AAAA,EAAO;AAAA,EAAiB;AAAA,EAAkB;AAAA,EAAgB;AAAA,EAC1D;AAAA,EAAW;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAqB;AAAA,EAChD;AAAA,EAAiB;AAAA,EAAY;AAAA,EAAgB;AAAA,EAC7C;AAAA,EAAW;AAAA,EAAe;AAC5B,CAAC;AAgBD,IAAO,uBAAQ,gBAAc;AAC3B,QAAM,SAAS,CAAC;AAChB,MAAI;AACJ,MAAI;AACJ,MAAI;AAEJ,gBAAc,WAAW,MAAM,IAAI,EAAE,QAAQ,SAAS,OAAO,MAAM;AACjE,QAAI,KAAK,QAAQ,GAAG;AACpB,UAAM,KAAK,UAAU,GAAG,CAAC,EAAE,KAAK,EAAE,YAAY;AAC9C,UAAM,KAAK,UAAU,IAAI,CAAC,EAAE,KAAK;AAEjC,QAAI,CAAC,OAAQ,OAAO,QAAQ,kBAAkB,MAAO;AACnD;AAAA,IACF;AAEA,QAAI,QAAQ,cAAc;AACxB,UAAI,OAAO,MAAM;AACf,eAAO,KAAK,KAAK,GAAG;AAAA,MACtB,OAAO;AACL,eAAO,OAAO,CAAC,GAAG;AAAA,MACpB;AAAA,IACF,OAAO;AACL,aAAO,OAAO,OAAO,OAAO,OAAO,OAAO,OAAO,MAAM;AAAA,IACzD;AAAA,EACF,CAAC;AAED,SAAO;AACT;;;ACjDA,IAAM,aAAa,OAAO,WAAW;AAErC,SAAS,gBAAgB,QAAQ;AAC/B,SAAO,UAAU,OAAO,MAAM,EAAE,KAAK,EAAE,YAAY;AACrD;AAEA,SAAS,eAAe,OAAO;AAC7B,MAAI,UAAU,SAAS,SAAS,MAAM;AACpC,WAAO;AAAA,EACT;AAEA,SAAO,cAAM,QAAQ,KAAK,IAAI,MAAM,IAAI,cAAc,IAAI,OAAO,KAAK;AACxE;AAEA,SAAS,YAAY,KAAK;AACxB,QAAM,SAAS,uBAAO,OAAO,IAAI;AACjC,QAAM,WAAW;AACjB,MAAI;AAEJ,SAAQ,QAAQ,SAAS,KAAK,GAAG,GAAI;AACnC,WAAO,MAAM,MAAM,MAAM;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,oBAAoB,CAAC,QAAQ,iCAAiC,KAAK,IAAI,KAAK,CAAC;AAEnF,SAAS,iBAAiB,SAAS,OAAO,QAAQC,SAAQ,oBAAoB;AAC5E,MAAI,cAAM,WAAWA,OAAM,GAAG;AAC5B,WAAOA,QAAO,KAAK,MAAM,OAAO,MAAM;AAAA,EACxC;AAEA,MAAI,oBAAoB;AACtB,YAAQ;AAAA,EACV;AAEA,MAAI,CAAC,cAAM,SAAS,KAAK;AAAG;AAE5B,MAAI,cAAM,SAASA,OAAM,GAAG;AAC1B,WAAO,MAAM,QAAQA,OAAM,MAAM;AAAA,EACnC;AAEA,MAAI,cAAM,SAASA,OAAM,GAAG;AAC1B,WAAOA,QAAO,KAAK,KAAK;AAAA,EAC1B;AACF;AAEA,SAAS,aAAa,QAAQ;AAC5B,SAAO,OAAO,KAAK,EAChB,YAAY,EAAE,QAAQ,mBAAmB,CAAC,GAAG,MAAM,QAAQ;AAC1D,WAAO,KAAK,YAAY,IAAI;AAAA,EAC9B,CAAC;AACL;AAEA,SAAS,eAAe,KAAK,QAAQ;AACnC,QAAM,eAAe,cAAM,YAAY,MAAM,MAAM;AAEnD,GAAC,OAAO,OAAO,KAAK,EAAE,QAAQ,gBAAc;AAC1C,WAAO,eAAe,KAAK,aAAa,cAAc;AAAA,MACpD,OAAO,SAAS,MAAM,MAAM,MAAM;AAChC,eAAO,KAAK,YAAY,KAAK,MAAM,QAAQ,MAAM,MAAM,IAAI;AAAA,MAC7D;AAAA,MACA,cAAc;AAAA,IAChB,CAAC;AAAA,EACH,CAAC;AACH;AAEA,IAAM,eAAN,MAAmB;AAAA,EACjB,YAAY,SAAS;AACnB,eAAW,KAAK,IAAI,OAAO;AAAA,EAC7B;AAAA,EAEA,IAAI,QAAQ,gBAAgB,SAAS;AACnC,UAAMC,QAAO;AAEb,aAAS,UAAU,QAAQ,SAAS,UAAU;AAC5C,YAAM,UAAU,gBAAgB,OAAO;AAEvC,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAEA,YAAM,MAAM,cAAM,QAAQA,OAAM,OAAO;AAEvC,UAAG,CAAC,OAAOA,MAAK,SAAS,UAAa,aAAa,QAAS,aAAa,UAAaA,MAAK,SAAS,OAAQ;AAC1G,QAAAA,MAAK,OAAO,WAAW,eAAe,MAAM;AAAA,MAC9C;AAAA,IACF;AAEA,UAAM,aAAa,CAAC,SAAS,aAC3B,cAAM,QAAQ,SAAS,CAAC,QAAQ,YAAY,UAAU,QAAQ,SAAS,QAAQ,CAAC;AAElF,QAAI,cAAM,cAAc,MAAM,KAAK,kBAAkB,KAAK,aAAa;AACrE,iBAAW,QAAQ,cAAc;AAAA,IACnC,WAAU,cAAM,SAAS,MAAM,MAAM,SAAS,OAAO,KAAK,MAAM,CAAC,kBAAkB,MAAM,GAAG;AAC1F,iBAAW,qBAAa,MAAM,GAAG,cAAc;AAAA,IACjD,OAAO;AACL,gBAAU,QAAQ,UAAU,gBAAgB,QAAQ,OAAO;AAAA,IAC7D;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,IAAI,QAAQ,QAAQ;AAClB,aAAS,gBAAgB,MAAM;AAE/B,QAAI,QAAQ;AACV,YAAM,MAAM,cAAM,QAAQ,MAAM,MAAM;AAEtC,UAAI,KAAK;AACP,cAAM,QAAQ,KAAK;AAEnB,YAAI,CAAC,QAAQ;AACX,iBAAO;AAAA,QACT;AAEA,YAAI,WAAW,MAAM;AACnB,iBAAO,YAAY,KAAK;AAAA,QAC1B;AAEA,YAAI,cAAM,WAAW,MAAM,GAAG;AAC5B,iBAAO,OAAO,KAAK,MAAM,OAAO,GAAG;AAAA,QACrC;AAEA,YAAI,cAAM,SAAS,MAAM,GAAG;AAC1B,iBAAO,OAAO,KAAK,KAAK;AAAA,QAC1B;AAEA,cAAM,IAAI,UAAU,wCAAwC;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AAAA,EAEA,IAAI,QAAQ,SAAS;AACnB,aAAS,gBAAgB,MAAM;AAE/B,QAAI,QAAQ;AACV,YAAM,MAAM,cAAM,QAAQ,MAAM,MAAM;AAEtC,aAAO,CAAC,EAAE,OAAO,KAAK,SAAS,WAAc,CAAC,WAAW,iBAAiB,MAAM,KAAK,MAAM,KAAK,OAAO;AAAA,IACzG;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,OAAO,QAAQ,SAAS;AACtB,UAAMA,QAAO;AACb,QAAI,UAAU;AAEd,aAAS,aAAa,SAAS;AAC7B,gBAAU,gBAAgB,OAAO;AAEjC,UAAI,SAAS;AACX,cAAM,MAAM,cAAM,QAAQA,OAAM,OAAO;AAEvC,YAAI,QAAQ,CAAC,WAAW,iBAAiBA,OAAMA,MAAK,MAAM,KAAK,OAAO,IAAI;AACxE,iBAAOA,MAAK;AAEZ,oBAAU;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AAEA,QAAI,cAAM,QAAQ,MAAM,GAAG;AACzB,aAAO,QAAQ,YAAY;AAAA,IAC7B,OAAO;AACL,mBAAa,MAAM;AAAA,IACrB;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,SAAS;AACb,UAAM,OAAO,OAAO,KAAK,IAAI;AAC7B,QAAI,IAAI,KAAK;AACb,QAAI,UAAU;AAEd,WAAO,KAAK;AACV,YAAM,MAAM,KAAK;AACjB,UAAG,CAAC,WAAW,iBAAiB,MAAM,KAAK,MAAM,KAAK,SAAS,IAAI,GAAG;AACpE,eAAO,KAAK;AACZ,kBAAU;AAAA,MACZ;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,UAAU,QAAQ;AAChB,UAAMA,QAAO;AACb,UAAM,UAAU,CAAC;AAEjB,kBAAM,QAAQ,MAAM,CAAC,OAAO,WAAW;AACrC,YAAM,MAAM,cAAM,QAAQ,SAAS,MAAM;AAEzC,UAAI,KAAK;AACP,QAAAA,MAAK,OAAO,eAAe,KAAK;AAChC,eAAOA,MAAK;AACZ;AAAA,MACF;AAEA,YAAM,aAAa,SAAS,aAAa,MAAM,IAAI,OAAO,MAAM,EAAE,KAAK;AAEvE,UAAI,eAAe,QAAQ;AACzB,eAAOA,MAAK;AAAA,MACd;AAEA,MAAAA,MAAK,cAAc,eAAe,KAAK;AAEvC,cAAQ,cAAc;AAAA,IACxB,CAAC;AAED,WAAO;AAAA,EACT;AAAA,EAEA,UAAU,SAAS;AACjB,WAAO,KAAK,YAAY,OAAO,MAAM,GAAG,OAAO;AAAA,EACjD;AAAA,EAEA,OAAO,WAAW;AAChB,UAAM,MAAM,uBAAO,OAAO,IAAI;AAE9B,kBAAM,QAAQ,MAAM,CAAC,OAAO,WAAW;AACrC,eAAS,QAAQ,UAAU,UAAU,IAAI,UAAU,aAAa,cAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,IAAI,IAAI;AAAA,IAC5G,CAAC;AAED,WAAO;AAAA,EACT;AAAA,EAEA,CAAC,OAAO,YAAY;AAClB,WAAO,OAAO,QAAQ,KAAK,OAAO,CAAC,EAAE,OAAO,UAAU;AAAA,EACxD;AAAA,EAEA,WAAW;AACT,WAAO,OAAO,QAAQ,KAAK,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,KAAK,MAAM,SAAS,OAAO,KAAK,EAAE,KAAK,IAAI;AAAA,EAChG;AAAA,EAEA,KAAK,OAAO,eAAe;AACzB,WAAO;AAAA,EACT;AAAA,EAEA,OAAO,KAAK,OAAO;AACjB,WAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;AAAA,EACvD;AAAA,EAEA,OAAO,OAAO,UAAU,SAAS;AAC/B,UAAM,WAAW,IAAI,KAAK,KAAK;AAE/B,YAAQ,QAAQ,CAAC,WAAW,SAAS,IAAI,MAAM,CAAC;AAEhD,WAAO;AAAA,EACT;AAAA,EAEA,OAAO,SAAS,QAAQ;AACtB,UAAM,YAAY,KAAK,cAAe,KAAK,cAAc;AAAA,MACvD,WAAW,CAAC;AAAA,IACd;AAEA,UAAM,YAAY,UAAU;AAC5B,UAAMC,aAAY,KAAK;AAEvB,aAAS,eAAe,SAAS;AAC/B,YAAM,UAAU,gBAAgB,OAAO;AAEvC,UAAI,CAAC,UAAU,UAAU;AACvB,uBAAeA,YAAW,OAAO;AACjC,kBAAU,WAAW;AAAA,MACvB;AAAA,IACF;AAEA,kBAAM,QAAQ,MAAM,IAAI,OAAO,QAAQ,cAAc,IAAI,eAAe,MAAM;AAE9E,WAAO;AAAA,EACT;AACF;AAEA,aAAa,SAAS,CAAC,gBAAgB,kBAAkB,UAAU,mBAAmB,cAAc,eAAe,CAAC;AAGpH,cAAM,kBAAkB,aAAa,WAAW,CAAC,EAAC,MAAK,GAAG,QAAQ;AAChE,MAAI,SAAS,IAAI,GAAG,YAAY,IAAI,IAAI,MAAM,CAAC;AAC/C,SAAO;AAAA,IACL,KAAK,MAAM;AAAA,IACX,IAAI,aAAa;AACf,WAAK,UAAU;AAAA,IACjB;AAAA,EACF;AACF,CAAC;AAED,cAAM,cAAc,YAAY;AAEhC,IAAO,uBAAQ;;;AC3RA,SAAR,cAA+B,KAAK,UAAU;AACnD,QAAM,SAAS,QAAQ;AACvB,QAAM,UAAU,YAAY;AAC5B,QAAM,UAAU,qBAAa,KAAK,QAAQ,OAAO;AACjD,MAAI,OAAO,QAAQ;AAEnB,gBAAM,QAAQ,KAAK,SAAS,UAAU,IAAI;AACxC,WAAO,GAAG,KAAK,QAAQ,MAAM,QAAQ,UAAU,GAAG,WAAW,SAAS,SAAS,MAAS;AAAA,EAC1F,CAAC;AAED,UAAQ,UAAU;AAElB,SAAO;AACT;;;ACzBe,SAAR,SAA0B,OAAO;AACtC,SAAO,CAAC,EAAE,SAAS,MAAM;AAC3B;;;ACUA,SAAS,cAAc,SAAS,QAAQ,SAAS;AAE/C,qBAAW,KAAK,MAAM,WAAW,OAAO,aAAa,SAAS,mBAAW,cAAc,QAAQ,OAAO;AACtG,OAAK,OAAO;AACd;AAEA,cAAM,SAAS,eAAe,oBAAY;AAAA,EACxC,YAAY;AACd,CAAC;AAED,IAAO,wBAAQ;;;ACXA,SAAR,OAAwB,SAAS,QAAQ,UAAU;AACxD,QAAMC,kBAAiB,SAAS,OAAO;AACvC,MAAI,CAAC,SAAS,UAAU,CAACA,mBAAkBA,gBAAe,SAAS,MAAM,GAAG;AAC1E,YAAQ,QAAQ;AAAA,EAClB,OAAO;AACL,WAAO,IAAI;AAAA,MACT,qCAAqC,SAAS;AAAA,MAC9C,CAAC,mBAAW,iBAAiB,mBAAW,gBAAgB,EAAE,KAAK,MAAM,SAAS,SAAS,GAAG,IAAI;AAAA,MAC9F,SAAS;AAAA,MACT,SAAS;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACvBA,IAAO,kBAAQ,iBAAS,wBAGtB;AAAA,EACE,MAAM,MAAM,OAAO,SAAS,MAAM,QAAQ,QAAQ;AAChD,UAAM,SAAS,CAAC,OAAO,MAAM,mBAAmB,KAAK,CAAC;AAEtD,kBAAM,SAAS,OAAO,KAAK,OAAO,KAAK,aAAa,IAAI,KAAK,OAAO,EAAE,YAAY,CAAC;AAEnF,kBAAM,SAAS,IAAI,KAAK,OAAO,KAAK,UAAU,IAAI;AAElD,kBAAM,SAAS,MAAM,KAAK,OAAO,KAAK,YAAY,MAAM;AAExD,eAAW,QAAQ,OAAO,KAAK,QAAQ;AAEvC,aAAS,SAAS,OAAO,KAAK,IAAI;AAAA,EACpC;AAAA,EAEA,KAAK,MAAM;AACT,UAAM,QAAQ,SAAS,OAAO,MAAM,IAAI,OAAO,eAAe,OAAO,WAAW,CAAC;AACjF,WAAQ,QAAQ,mBAAmB,MAAM,EAAE,IAAI;AAAA,EACjD;AAAA,EAEA,OAAO,MAAM;AACX,SAAK,MAAM,MAAM,IAAI,KAAK,IAAI,IAAI,KAAQ;AAAA,EAC5C;AACF,IAKA;AAAA,EACE,QAAQ;AAAA,EAAC;AAAA,EACT,OAAO;AACL,WAAO;AAAA,EACT;AAAA,EACA,SAAS;AAAA,EAAC;AACZ;;;AC/Ba,SAAR,cAA+B,KAAK;AAIzC,SAAO,8BAA8B,KAAK,GAAG;AAC/C;;;ACJe,SAAR,YAA6B,SAAS,aAAa;AACxD,SAAO,cACH,QAAQ,QAAQ,UAAU,EAAE,IAAI,MAAM,YAAY,QAAQ,QAAQ,EAAE,IACpE;AACN;;;ACCe,SAAR,cAA+B,SAAS,cAAc;AAC3D,MAAI,WAAW,CAAC,cAAc,YAAY,GAAG;AAC3C,WAAO,YAAY,SAAS,YAAY;AAAA,EAC1C;AACA,SAAO;AACT;;;ACfA,IAAO,0BAAQ,iBAAS,wBAIrB,SAAS,qBAAqB;AAC7B,QAAM,OAAO,kBAAkB,KAAK,UAAU,SAAS;AACvD,QAAM,iBAAiB,SAAS,cAAc,GAAG;AACjD,MAAI;AAQJ,WAAS,WAAW,KAAK;AACvB,QAAI,OAAO;AAEX,QAAI,MAAM;AAER,qBAAe,aAAa,QAAQ,IAAI;AACxC,aAAO,eAAe;AAAA,IACxB;AAEA,mBAAe,aAAa,QAAQ,IAAI;AAGxC,WAAO;AAAA,MACL,MAAM,eAAe;AAAA,MACrB,UAAU,eAAe,WAAW,eAAe,SAAS,QAAQ,MAAM,EAAE,IAAI;AAAA,MAChF,MAAM,eAAe;AAAA,MACrB,QAAQ,eAAe,SAAS,eAAe,OAAO,QAAQ,OAAO,EAAE,IAAI;AAAA,MAC3E,MAAM,eAAe,OAAO,eAAe,KAAK,QAAQ,MAAM,EAAE,IAAI;AAAA,MACpE,UAAU,eAAe;AAAA,MACzB,MAAM,eAAe;AAAA,MACrB,UAAW,eAAe,SAAS,OAAO,CAAC,MAAM,MAC/C,eAAe,WACf,MAAM,eAAe;AAAA,IACzB;AAAA,EACF;AAEA,cAAY,WAAW,OAAO,SAAS,IAAI;AAQ3C,SAAO,SAAS,gBAAgB,YAAY;AAC1C,UAAM,SAAU,cAAM,SAAS,UAAU,IAAK,WAAW,UAAU,IAAI;AACvE,WAAQ,OAAO,aAAa,UAAU,YAClC,OAAO,SAAS,UAAU;AAAA,EAChC;AACF,EAAG,IAGF,SAAS,wBAAwB;AAChC,SAAO,SAAS,kBAAkB;AAChC,WAAO;AAAA,EACT;AACF,EAAG;;;AChEU,SAAR,cAA+B,KAAK;AACzC,QAAM,QAAQ,4BAA4B,KAAK,GAAG;AAClD,SAAO,SAAS,MAAM,MAAM;AAC9B;;;ACGA,SAAS,YAAY,cAAc,KAAK;AACtC,iBAAe,gBAAgB;AAC/B,QAAM,QAAQ,IAAI,MAAM,YAAY;AACpC,QAAM,aAAa,IAAI,MAAM,YAAY;AACzC,MAAI,OAAO;AACX,MAAI,OAAO;AACX,MAAI;AAEJ,QAAM,QAAQ,SAAY,MAAM;AAEhC,SAAO,SAAS,KAAK,aAAa;AAChC,UAAM,MAAM,KAAK,IAAI;AAErB,UAAM,YAAY,WAAW;AAE7B,QAAI,CAAC,eAAe;AAClB,sBAAgB;AAAA,IAClB;AAEA,UAAM,QAAQ;AACd,eAAW,QAAQ;AAEnB,QAAI,IAAI;AACR,QAAI,aAAa;AAEjB,WAAO,MAAM,MAAM;AACjB,oBAAc,MAAM;AACpB,UAAI,IAAI;AAAA,IACV;AAEA,YAAQ,OAAO,KAAK;AAEpB,QAAI,SAAS,MAAM;AACjB,cAAQ,OAAO,KAAK;AAAA,IACtB;AAEA,QAAI,MAAM,gBAAgB,KAAK;AAC7B;AAAA,IACF;AAEA,UAAM,SAAS,aAAa,MAAM;AAElC,WAAO,SAAS,KAAK,MAAM,aAAa,MAAO,MAAM,IAAI;AAAA,EAC3D;AACF;AAEA,IAAO,sBAAQ;;;ACtCf,SAAS,qBAAqB,UAAU,kBAAkB;AACxD,MAAI,gBAAgB;AACpB,QAAM,eAAe,oBAAY,IAAI,GAAG;AAExC,SAAO,OAAK;AACV,UAAM,SAAS,EAAE;AACjB,UAAM,QAAQ,EAAE,mBAAmB,EAAE,QAAQ;AAC7C,UAAM,gBAAgB,SAAS;AAC/B,UAAM,OAAO,aAAa,aAAa;AACvC,UAAM,UAAU,UAAU;AAE1B,oBAAgB;AAEhB,UAAM,OAAO;AAAA,MACX;AAAA,MACA;AAAA,MACA,UAAU,QAAS,SAAS,QAAS;AAAA,MACrC,OAAO;AAAA,MACP,MAAM,OAAO,OAAO;AAAA,MACpB,WAAW,QAAQ,SAAS,WAAW,QAAQ,UAAU,OAAO;AAAA,MAChE,OAAO;AAAA,IACT;AAEA,SAAK,mBAAmB,aAAa,YAAY;AAEjD,aAAS,IAAI;AAAA,EACf;AACF;AAEA,IAAM,wBAAwB,OAAO,mBAAmB;AAExD,IAAO,cAAQ,yBAAyB,SAAU,QAAQ;AACxD,SAAO,IAAI,QAAQ,SAAS,mBAAmB,SAAS,QAAQ;AAC9D,QAAI,cAAc,OAAO;AACzB,UAAM,iBAAiB,qBAAa,KAAK,OAAO,OAAO,EAAE,UAAU;AACnE,QAAI,EAAC,cAAc,cAAa,IAAI;AACpC,QAAI;AACJ,aAAS,OAAO;AACd,UAAI,OAAO,aAAa;AACtB,eAAO,YAAY,YAAY,UAAU;AAAA,MAC3C;AAEA,UAAI,OAAO,QAAQ;AACjB,eAAO,OAAO,oBAAoB,SAAS,UAAU;AAAA,MACvD;AAAA,IACF;AAEA,QAAI;AAEJ,QAAI,cAAM,WAAW,WAAW,GAAG;AACjC,UAAI,iBAAS,yBAAyB,iBAAS,gCAAgC;AAC7E,uBAAe,eAAe,KAAK;AAAA,MACrC,YAAY,cAAc,eAAe,eAAe,OAAO,OAAO;AAEpE,cAAM,CAAC,SAAS,MAAM,IAAI,cAAc,YAAY,MAAM,GAAG,EAAE,IAAI,WAAS,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO,IAAI,CAAC;AAC7G,uBAAe,eAAe,CAAC,QAAQ,uBAAuB,GAAG,MAAM,EAAE,KAAK,IAAI,CAAC;AAAA,MACrF;AAAA,IACF;AAEA,QAAI,UAAU,IAAI,eAAe;AAGjC,QAAI,OAAO,MAAM;AACf,YAAM,WAAW,OAAO,KAAK,YAAY;AACzC,YAAM,WAAW,OAAO,KAAK,WAAW,SAAS,mBAAmB,OAAO,KAAK,QAAQ,CAAC,IAAI;AAC7F,qBAAe,IAAI,iBAAiB,WAAW,KAAK,WAAW,MAAM,QAAQ,CAAC;AAAA,IAChF;AAEA,UAAM,WAAW,cAAc,OAAO,SAAS,OAAO,GAAG;AAEzD,YAAQ,KAAK,OAAO,OAAO,YAAY,GAAG,SAAS,UAAU,OAAO,QAAQ,OAAO,gBAAgB,GAAG,IAAI;AAG1G,YAAQ,UAAU,OAAO;AAEzB,aAAS,YAAY;AACnB,UAAI,CAAC,SAAS;AACZ;AAAA,MACF;AAEA,YAAM,kBAAkB,qBAAa;AAAA,QACnC,2BAA2B,WAAW,QAAQ,sBAAsB;AAAA,MACtE;AACA,YAAM,eAAe,CAAC,gBAAgB,iBAAiB,UAAU,iBAAiB,SAChF,QAAQ,eAAe,QAAQ;AACjC,YAAM,WAAW;AAAA,QACf,MAAM;AAAA,QACN,QAAQ,QAAQ;AAAA,QAChB,YAAY,QAAQ;AAAA,QACpB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,MACF;AAEA,aAAO,SAAS,SAAS,OAAO;AAC9B,gBAAQ,KAAK;AACb,aAAK;AAAA,MACP,GAAG,SAAS,QAAQ,KAAK;AACvB,eAAO,GAAG;AACV,aAAK;AAAA,MACP,GAAG,QAAQ;AAGX,gBAAU;AAAA,IACZ;AAEA,QAAI,eAAe,SAAS;AAE1B,cAAQ,YAAY;AAAA,IACtB,OAAO;AAEL,cAAQ,qBAAqB,SAAS,aAAa;AACjD,YAAI,CAAC,WAAW,QAAQ,eAAe,GAAG;AACxC;AAAA,QACF;AAMA,YAAI,QAAQ,WAAW,KAAK,EAAE,QAAQ,eAAe,QAAQ,YAAY,QAAQ,OAAO,MAAM,IAAI;AAChG;AAAA,QACF;AAGA,mBAAW,SAAS;AAAA,MACtB;AAAA,IACF;AAGA,YAAQ,UAAU,SAAS,cAAc;AACvC,UAAI,CAAC,SAAS;AACZ;AAAA,MACF;AAEA,aAAO,IAAI,mBAAW,mBAAmB,mBAAW,cAAc,QAAQ,OAAO,CAAC;AAGlF,gBAAU;AAAA,IACZ;AAGA,YAAQ,UAAU,SAAS,cAAc;AAGvC,aAAO,IAAI,mBAAW,iBAAiB,mBAAW,aAAa,QAAQ,OAAO,CAAC;AAG/E,gBAAU;AAAA,IACZ;AAGA,YAAQ,YAAY,SAAS,gBAAgB;AAC3C,UAAI,sBAAsB,OAAO,UAAU,gBAAgB,OAAO,UAAU,gBAAgB;AAC5F,YAAMC,gBAAe,OAAO,gBAAgB;AAC5C,UAAI,OAAO,qBAAqB;AAC9B,8BAAsB,OAAO;AAAA,MAC/B;AACA,aAAO,IAAI;AAAA,QACT;AAAA,QACAA,cAAa,sBAAsB,mBAAW,YAAY,mBAAW;AAAA,QACrE;AAAA,QACA;AAAA,MAAO,CAAC;AAGV,gBAAU;AAAA,IACZ;AAKA,QAAG,iBAAS,uBAAuB;AACjC,uBAAiB,cAAM,WAAW,aAAa,MAAM,gBAAgB,cAAc,MAAM;AAEzF,UAAI,iBAAkB,kBAAkB,SAAS,wBAAgB,QAAQ,GAAI;AAE3E,cAAM,YAAY,OAAO,kBAAkB,OAAO,kBAAkB,gBAAQ,KAAK,OAAO,cAAc;AAEtG,YAAI,WAAW;AACb,yBAAe,IAAI,OAAO,gBAAgB,SAAS;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAGA,oBAAgB,UAAa,eAAe,eAAe,IAAI;AAG/D,QAAI,sBAAsB,SAAS;AACjC,oBAAM,QAAQ,eAAe,OAAO,GAAG,SAAS,iBAAiB,KAAK,KAAK;AACzE,gBAAQ,iBAAiB,KAAK,GAAG;AAAA,MACnC,CAAC;AAAA,IACH;AAGA,QAAI,CAAC,cAAM,YAAY,OAAO,eAAe,GAAG;AAC9C,cAAQ,kBAAkB,CAAC,CAAC,OAAO;AAAA,IACrC;AAGA,QAAI,gBAAgB,iBAAiB,QAAQ;AAC3C,cAAQ,eAAe,OAAO;AAAA,IAChC;AAGA,QAAI,OAAO,OAAO,uBAAuB,YAAY;AACnD,cAAQ,iBAAiB,YAAY,qBAAqB,OAAO,oBAAoB,IAAI,CAAC;AAAA,IAC5F;AAGA,QAAI,OAAO,OAAO,qBAAqB,cAAc,QAAQ,QAAQ;AACnE,cAAQ,OAAO,iBAAiB,YAAY,qBAAqB,OAAO,gBAAgB,CAAC;AAAA,IAC3F;AAEA,QAAI,OAAO,eAAe,OAAO,QAAQ;AAGvC,mBAAa,YAAU;AACrB,YAAI,CAAC,SAAS;AACZ;AAAA,QACF;AACA,eAAO,CAAC,UAAU,OAAO,OAAO,IAAI,sBAAc,MAAM,QAAQ,OAAO,IAAI,MAAM;AACjF,gBAAQ,MAAM;AACd,kBAAU;AAAA,MACZ;AAEA,aAAO,eAAe,OAAO,YAAY,UAAU,UAAU;AAC7D,UAAI,OAAO,QAAQ;AACjB,eAAO,OAAO,UAAU,WAAW,IAAI,OAAO,OAAO,iBAAiB,SAAS,UAAU;AAAA,MAC3F;AAAA,IACF;AAEA,UAAM,WAAW,cAAc,QAAQ;AAEvC,QAAI,YAAY,iBAAS,UAAU,QAAQ,QAAQ,MAAM,IAAI;AAC3D,aAAO,IAAI,mBAAW,0BAA0B,WAAW,KAAK,mBAAW,iBAAiB,MAAM,CAAC;AACnG;AAAA,IACF;AAIA,YAAQ,KAAK,eAAe,IAAI;AAAA,EAClC,CAAC;AACH;;;AC9PA,IAAM,gBAAgB;AAAA,EACpB,MAAM;AAAA,EACN,KAAK;AACP;AAEA,cAAM,QAAQ,eAAe,CAAC,IAAI,UAAU;AAC1C,MAAI,IAAI;AACN,QAAI;AACF,aAAO,eAAe,IAAI,QAAQ,EAAC,MAAK,CAAC;AAAA,IAC3C,SAAS,GAAP;AAAA,IAEF;AACA,WAAO,eAAe,IAAI,eAAe,EAAC,MAAK,CAAC;AAAA,EAClD;AACF,CAAC;AAED,IAAM,eAAe,CAAC,WAAW,KAAK;AAEtC,IAAM,mBAAmB,CAAC,YAAY,cAAM,WAAW,OAAO,KAAK,YAAY,QAAQ,YAAY;AAEnG,IAAO,mBAAQ;AAAA,EACb,YAAY,CAAC,aAAa;AACxB,eAAW,cAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC,QAAQ;AAEzD,UAAM,EAAC,OAAM,IAAI;AACjB,QAAI;AACJ,QAAI;AAEJ,UAAM,kBAAkB,CAAC;AAEzB,aAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,sBAAgB,SAAS;AACzB,UAAI;AAEJ,gBAAU;AAEV,UAAI,CAAC,iBAAiB,aAAa,GAAG;AACpC,kBAAU,eAAe,KAAK,OAAO,aAAa,GAAG,YAAY;AAEjE,YAAI,YAAY,QAAW;AACzB,gBAAM,IAAI,mBAAW,oBAAoB,KAAK;AAAA,QAChD;AAAA,MACF;AAEA,UAAI,SAAS;AACX;AAAA,MACF;AAEA,sBAAgB,MAAM,MAAM,KAAK;AAAA,IACnC;AAEA,QAAI,CAAC,SAAS;AAEZ,YAAM,UAAU,OAAO,QAAQ,eAAe,EAC3C;AAAA,QAAI,CAAC,CAAC,IAAI,KAAK,MAAM,WAAW,SAC9B,UAAU,QAAQ,wCAAwC;AAAA,MAC7D;AAEF,UAAI,IAAI,SACL,QAAQ,SAAS,IAAI,cAAc,QAAQ,IAAI,YAAY,EAAE,KAAK,IAAI,IAAI,MAAM,aAAa,QAAQ,EAAE,IACxG;AAEF,YAAM,IAAI;AAAA,QACR,0DAA0D;AAAA,QAC1D;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EACA,UAAU;AACZ;;;AC5DA,SAAS,6BAA6B,QAAQ;AAC5C,MAAI,OAAO,aAAa;AACtB,WAAO,YAAY,iBAAiB;AAAA,EACtC;AAEA,MAAI,OAAO,UAAU,OAAO,OAAO,SAAS;AAC1C,UAAM,IAAI,sBAAc,MAAM,MAAM;AAAA,EACtC;AACF;AASe,SAAR,gBAAiC,QAAQ;AAC9C,+BAA6B,MAAM;AAEnC,SAAO,UAAU,qBAAa,KAAK,OAAO,OAAO;AAGjD,SAAO,OAAO,cAAc;AAAA,IAC1B;AAAA,IACA,OAAO;AAAA,EACT;AAEA,MAAI,CAAC,QAAQ,OAAO,OAAO,EAAE,QAAQ,OAAO,MAAM,MAAM,IAAI;AAC1D,WAAO,QAAQ,eAAe,qCAAqC,KAAK;AAAA,EAC1E;AAEA,QAAM,UAAU,iBAAS,WAAW,OAAO,WAAW,iBAAS,OAAO;AAEtE,SAAO,QAAQ,MAAM,EAAE,KAAK,SAAS,oBAAoB,UAAU;AACjE,iCAA6B,MAAM;AAGnC,aAAS,OAAO,cAAc;AAAA,MAC5B;AAAA,MACA,OAAO;AAAA,MACP;AAAA,IACF;AAEA,aAAS,UAAU,qBAAa,KAAK,SAAS,OAAO;AAErD,WAAO;AAAA,EACT,GAAG,SAAS,mBAAmB,QAAQ;AACrC,QAAI,CAAC,SAAS,MAAM,GAAG;AACrB,mCAA6B,MAAM;AAGnC,UAAI,UAAU,OAAO,UAAU;AAC7B,eAAO,SAAS,OAAO,cAAc;AAAA,UACnC;AAAA,UACA,OAAO;AAAA,UACP,OAAO;AAAA,QACT;AACA,eAAO,SAAS,UAAU,qBAAa,KAAK,OAAO,SAAS,OAAO;AAAA,MACrE;AAAA,IACF;AAEA,WAAO,QAAQ,OAAO,MAAM;AAAA,EAC9B,CAAC;AACH;;;AC3EA,IAAM,kBAAkB,CAAC,UAAU,iBAAiB,uBAAe,MAAM,OAAO,IAAI;AAWrE,SAAR,YAA6B,SAAS,SAAS;AAEpD,YAAU,WAAW,CAAC;AACtB,QAAM,SAAS,CAAC;AAEhB,WAAS,eAAe,QAAQ,QAAQ,UAAU;AAChD,QAAI,cAAM,cAAc,MAAM,KAAK,cAAM,cAAc,MAAM,GAAG;AAC9D,aAAO,cAAM,MAAM,KAAK,EAAC,SAAQ,GAAG,QAAQ,MAAM;AAAA,IACpD,WAAW,cAAM,cAAc,MAAM,GAAG;AACtC,aAAO,cAAM,MAAM,CAAC,GAAG,MAAM;AAAA,IAC/B,WAAW,cAAM,QAAQ,MAAM,GAAG;AAChC,aAAO,OAAO,MAAM;AAAA,IACtB;AACA,WAAO;AAAA,EACT;AAGA,WAAS,oBAAoB,GAAG,GAAG,UAAU;AAC3C,QAAI,CAAC,cAAM,YAAY,CAAC,GAAG;AACzB,aAAO,eAAe,GAAG,GAAG,QAAQ;AAAA,IACtC,WAAW,CAAC,cAAM,YAAY,CAAC,GAAG;AAChC,aAAO,eAAe,QAAW,GAAG,QAAQ;AAAA,IAC9C;AAAA,EACF;AAGA,WAAS,iBAAiB,GAAG,GAAG;AAC9B,QAAI,CAAC,cAAM,YAAY,CAAC,GAAG;AACzB,aAAO,eAAe,QAAW,CAAC;AAAA,IACpC;AAAA,EACF;AAGA,WAAS,iBAAiB,GAAG,GAAG;AAC9B,QAAI,CAAC,cAAM,YAAY,CAAC,GAAG;AACzB,aAAO,eAAe,QAAW,CAAC;AAAA,IACpC,WAAW,CAAC,cAAM,YAAY,CAAC,GAAG;AAChC,aAAO,eAAe,QAAW,CAAC;AAAA,IACpC;AAAA,EACF;AAGA,WAAS,gBAAgB,GAAG,GAAG,MAAM;AACnC,QAAI,QAAQ,SAAS;AACnB,aAAO,eAAe,GAAG,CAAC;AAAA,IAC5B,WAAW,QAAQ,SAAS;AAC1B,aAAO,eAAe,QAAW,CAAC;AAAA,IACpC;AAAA,EACF;AAEA,QAAM,WAAW;AAAA,IACf,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,SAAS;AAAA,IACT,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,SAAS;AAAA,IACT,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,cAAc;AAAA,IACd,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,oBAAoB;AAAA,IACpB,YAAY;AAAA,IACZ,kBAAkB;AAAA,IAClB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,aAAa;AAAA,IACb,YAAY;AAAA,IACZ,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,SAAS,CAAC,GAAG,MAAM,oBAAoB,gBAAgB,CAAC,GAAG,gBAAgB,CAAC,GAAG,IAAI;AAAA,EACrF;AAEA,gBAAM,QAAQ,OAAO,KAAK,OAAO,OAAO,CAAC,GAAG,SAAS,OAAO,CAAC,GAAG,SAAS,mBAAmB,MAAM;AAChG,UAAMC,SAAQ,SAAS,SAAS;AAChC,UAAM,cAAcA,OAAM,QAAQ,OAAO,QAAQ,OAAO,IAAI;AAC5D,IAAC,cAAM,YAAY,WAAW,KAAKA,WAAU,oBAAqB,OAAO,QAAQ;AAAA,EACnF,CAAC;AAED,SAAO;AACT;;;ACzGO,IAAM,UAAU;;;ACKvB,IAAM,aAAa,CAAC;AAGpB,CAAC,UAAU,WAAW,UAAU,YAAY,UAAU,QAAQ,EAAE,QAAQ,CAAC,MAAM,MAAM;AACnF,aAAW,QAAQ,SAAS,UAAU,OAAO;AAC3C,WAAO,OAAO,UAAU,QAAQ,OAAO,IAAI,IAAI,OAAO,OAAO;AAAA,EAC/D;AACF,CAAC;AAED,IAAM,qBAAqB,CAAC;AAW5B,WAAW,eAAe,SAAS,aAAa,WAAW,SAAS,SAAS;AAC3E,WAAS,cAAc,KAAK,MAAM;AAChC,WAAO,aAAa,UAAU,4BAA6B,MAAM,MAAO,QAAQ,UAAU,OAAO,UAAU;AAAA,EAC7G;AAGA,SAAO,CAAC,OAAO,KAAK,SAAS;AAC3B,QAAI,cAAc,OAAO;AACvB,YAAM,IAAI;AAAA,QACR,cAAc,KAAK,uBAAuB,UAAU,SAAS,UAAU,GAAG;AAAA,QAC1E,mBAAW;AAAA,MACb;AAAA,IACF;AAEA,QAAI,WAAW,CAAC,mBAAmB,MAAM;AACvC,yBAAmB,OAAO;AAE1B,cAAQ;AAAA,QACN;AAAA,UACE;AAAA,UACA,iCAAiC,UAAU;AAAA,QAC7C;AAAA,MACF;AAAA,IACF;AAEA,WAAO,YAAY,UAAU,OAAO,KAAK,IAAI,IAAI;AAAA,EACnD;AACF;AAYA,SAAS,cAAc,SAAS,QAAQ,cAAc;AACpD,MAAI,OAAO,YAAY,UAAU;AAC/B,UAAM,IAAI,mBAAW,6BAA6B,mBAAW,oBAAoB;AAAA,EACnF;AACA,QAAM,OAAO,OAAO,KAAK,OAAO;AAChC,MAAI,IAAI,KAAK;AACb,SAAO,MAAM,GAAG;AACd,UAAM,MAAM,KAAK;AACjB,UAAM,YAAY,OAAO;AACzB,QAAI,WAAW;AACb,YAAM,QAAQ,QAAQ;AACtB,YAAM,SAAS,UAAU,UAAa,UAAU,OAAO,KAAK,OAAO;AACnE,UAAI,WAAW,MAAM;AACnB,cAAM,IAAI,mBAAW,YAAY,MAAM,cAAc,QAAQ,mBAAW,oBAAoB;AAAA,MAC9F;AACA;AAAA,IACF;AACA,QAAI,iBAAiB,MAAM;AACzB,YAAM,IAAI,mBAAW,oBAAoB,KAAK,mBAAW,cAAc;AAAA,IACzE;AAAA,EACF;AACF;AAEA,IAAO,oBAAQ;AAAA,EACb;AAAA,EACA;AACF;;;AC/EA,IAAMC,cAAa,kBAAU;AAS7B,IAAM,QAAN,MAAY;AAAA,EACV,YAAY,gBAAgB;AAC1B,SAAK,WAAW;AAChB,SAAK,eAAe;AAAA,MAClB,SAAS,IAAI,2BAAmB;AAAA,MAChC,UAAU,IAAI,2BAAmB;AAAA,IACnC;AAAA,EACF;AAAA,EAUA,MAAM,QAAQ,aAAa,QAAQ;AACjC,QAAI;AACF,aAAO,MAAM,KAAK,SAAS,aAAa,MAAM;AAAA,IAChD,SAAS,KAAP;AACA,UAAI,eAAe,OAAO;AACxB,YAAI;AAEJ,cAAM,oBAAoB,MAAM,kBAAkB,QAAQ,CAAC,CAAC,IAAK,QAAQ,IAAI,MAAM;AAGnF,cAAM,QAAQ,MAAM,QAAQ,MAAM,MAAM,QAAQ,SAAS,EAAE,IAAI;AAE/D,YAAI,CAAC,IAAI,OAAO;AACd,cAAI,QAAQ;AAAA,QAEd,WAAW,SAAS,CAAC,OAAO,IAAI,KAAK,EAAE,SAAS,MAAM,QAAQ,aAAa,EAAE,CAAC,GAAG;AAC/E,cAAI,SAAS,OAAO;AAAA,QACtB;AAAA,MACF;AAEA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,SAAS,aAAa,QAAQ;AAG5B,QAAI,OAAO,gBAAgB,UAAU;AACnC,eAAS,UAAU,CAAC;AACpB,aAAO,MAAM;AAAA,IACf,OAAO;AACL,eAAS,eAAe,CAAC;AAAA,IAC3B;AAEA,aAAS,YAAY,KAAK,UAAU,MAAM;AAE1C,UAAM,EAAC,cAAAC,eAAc,kBAAkB,QAAO,IAAI;AAElD,QAAIA,kBAAiB,QAAW;AAC9B,wBAAU,cAAcA,eAAc;AAAA,QACpC,mBAAmBD,YAAW,aAAaA,YAAW,OAAO;AAAA,QAC7D,mBAAmBA,YAAW,aAAaA,YAAW,OAAO;AAAA,QAC7D,qBAAqBA,YAAW,aAAaA,YAAW,OAAO;AAAA,MACjE,GAAG,KAAK;AAAA,IACV;AAEA,QAAI,oBAAoB,MAAM;AAC5B,UAAI,cAAM,WAAW,gBAAgB,GAAG;AACtC,eAAO,mBAAmB;AAAA,UACxB,WAAW;AAAA,QACb;AAAA,MACF,OAAO;AACL,0BAAU,cAAc,kBAAkB;AAAA,UACxC,QAAQA,YAAW;AAAA,UACnB,WAAWA,YAAW;AAAA,QACxB,GAAG,IAAI;AAAA,MACT;AAAA,IACF;AAGA,WAAO,UAAU,OAAO,UAAU,KAAK,SAAS,UAAU,OAAO,YAAY;AAG7E,QAAI,iBAAiB,WAAW,cAAM;AAAA,MACpC,QAAQ;AAAA,MACR,QAAQ,OAAO;AAAA,IACjB;AAEA,eAAW,cAAM;AAAA,MACf,CAAC,UAAU,OAAO,QAAQ,QAAQ,OAAO,SAAS,QAAQ;AAAA,MAC1D,CAAC,WAAW;AACV,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF;AAEA,WAAO,UAAU,qBAAa,OAAO,gBAAgB,OAAO;AAG5D,UAAM,0BAA0B,CAAC;AACjC,QAAI,iCAAiC;AACrC,SAAK,aAAa,QAAQ,QAAQ,SAAS,2BAA2B,aAAa;AACjF,UAAI,OAAO,YAAY,YAAY,cAAc,YAAY,QAAQ,MAAM,MAAM,OAAO;AACtF;AAAA,MACF;AAEA,uCAAiC,kCAAkC,YAAY;AAE/E,8BAAwB,QAAQ,YAAY,WAAW,YAAY,QAAQ;AAAA,IAC7E,CAAC;AAED,UAAM,2BAA2B,CAAC;AAClC,SAAK,aAAa,SAAS,QAAQ,SAAS,yBAAyB,aAAa;AAChF,+BAAyB,KAAK,YAAY,WAAW,YAAY,QAAQ;AAAA,IAC3E,CAAC;AAED,QAAI;AACJ,QAAI,IAAI;AACR,QAAI;AAEJ,QAAI,CAAC,gCAAgC;AACnC,YAAM,QAAQ,CAAC,gBAAgB,KAAK,IAAI,GAAG,MAAS;AACpD,YAAM,QAAQ,MAAM,OAAO,uBAAuB;AAClD,YAAM,KAAK,MAAM,OAAO,wBAAwB;AAChD,YAAM,MAAM;AAEZ,gBAAU,QAAQ,QAAQ,MAAM;AAEhC,aAAO,IAAI,KAAK;AACd,kBAAU,QAAQ,KAAK,MAAM,MAAM,MAAM,IAAI;AAAA,MAC/C;AAEA,aAAO;AAAA,IACT;AAEA,UAAM,wBAAwB;AAE9B,QAAI,YAAY;AAEhB,QAAI;AAEJ,WAAO,IAAI,KAAK;AACd,YAAM,cAAc,wBAAwB;AAC5C,YAAM,aAAa,wBAAwB;AAC3C,UAAI;AACF,oBAAY,YAAY,SAAS;AAAA,MACnC,SAAS,OAAP;AACA,mBAAW,KAAK,MAAM,KAAK;AAC3B;AAAA,MACF;AAAA,IACF;AAEA,QAAI;AACF,gBAAU,gBAAgB,KAAK,MAAM,SAAS;AAAA,IAChD,SAAS,OAAP;AACA,aAAO,QAAQ,OAAO,KAAK;AAAA,IAC7B;AAEA,QAAI;AACJ,UAAM,yBAAyB;AAE/B,WAAO,IAAI,KAAK;AACd,gBAAU,QAAQ,KAAK,yBAAyB,MAAM,yBAAyB,IAAI;AAAA,IACrF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,OAAO,QAAQ;AACb,aAAS,YAAY,KAAK,UAAU,MAAM;AAC1C,UAAM,WAAW,cAAc,OAAO,SAAS,OAAO,GAAG;AACzD,WAAO,SAAS,UAAU,OAAO,QAAQ,OAAO,gBAAgB;AAAA,EAClE;AACF;AAGA,cAAM,QAAQ,CAAC,UAAU,OAAO,QAAQ,SAAS,GAAG,SAAS,oBAAoB,QAAQ;AAEvF,QAAM,UAAU,UAAU,SAAS,KAAK,QAAQ;AAC9C,WAAO,KAAK,QAAQ,YAAY,UAAU,CAAC,GAAG;AAAA,MAC5C;AAAA,MACA;AAAA,MACA,OAAO,UAAU,CAAC,GAAG;AAAA,IACvB,CAAC,CAAC;AAAA,EACJ;AACF,CAAC;AAED,cAAM,QAAQ,CAAC,QAAQ,OAAO,OAAO,GAAG,SAAS,sBAAsB,QAAQ;AAG7E,WAAS,mBAAmB,QAAQ;AAClC,WAAO,SAAS,WAAW,KAAK,MAAM,QAAQ;AAC5C,aAAO,KAAK,QAAQ,YAAY,UAAU,CAAC,GAAG;AAAA,QAC5C;AAAA,QACA,SAAS,SAAS;AAAA,UAChB,gBAAgB;AAAA,QAClB,IAAI,CAAC;AAAA,QACL;AAAA,QACA;AAAA,MACF,CAAC,CAAC;AAAA,IACJ;AAAA,EACF;AAEA,QAAM,UAAU,UAAU,mBAAmB;AAE7C,QAAM,UAAU,SAAS,UAAU,mBAAmB,IAAI;AAC5D,CAAC;AAED,IAAO,gBAAQ;;;ACrNf,IAAM,cAAN,MAAkB;AAAA,EAChB,YAAY,UAAU;AACpB,QAAI,OAAO,aAAa,YAAY;AAClC,YAAM,IAAI,UAAU,8BAA8B;AAAA,IACpD;AAEA,QAAI;AAEJ,SAAK,UAAU,IAAI,QAAQ,SAAS,gBAAgB,SAAS;AAC3D,uBAAiB;AAAA,IACnB,CAAC;AAED,UAAM,QAAQ;AAGd,SAAK,QAAQ,KAAK,YAAU;AAC1B,UAAI,CAAC,MAAM;AAAY;AAEvB,UAAI,IAAI,MAAM,WAAW;AAEzB,aAAO,MAAM,GAAG;AACd,cAAM,WAAW,GAAG,MAAM;AAAA,MAC5B;AACA,YAAM,aAAa;AAAA,IACrB,CAAC;AAGD,SAAK,QAAQ,OAAO,iBAAe;AACjC,UAAI;AAEJ,YAAM,UAAU,IAAI,QAAQ,aAAW;AACrC,cAAM,UAAU,OAAO;AACvB,mBAAW;AAAA,MACb,CAAC,EAAE,KAAK,WAAW;AAEnB,cAAQ,SAAS,SAAS,SAAS;AACjC,cAAM,YAAY,QAAQ;AAAA,MAC5B;AAEA,aAAO;AAAA,IACT;AAEA,aAAS,SAAS,OAAO,SAAS,QAAQ,SAAS;AACjD,UAAI,MAAM,QAAQ;AAEhB;AAAA,MACF;AAEA,YAAM,SAAS,IAAI,sBAAc,SAAS,QAAQ,OAAO;AACzD,qBAAe,MAAM,MAAM;AAAA,IAC7B,CAAC;AAAA,EACH;AAAA,EAKA,mBAAmB;AACjB,QAAI,KAAK,QAAQ;AACf,YAAM,KAAK;AAAA,IACb;AAAA,EACF;AAAA,EAMA,UAAU,UAAU;AAClB,QAAI,KAAK,QAAQ;AACf,eAAS,KAAK,MAAM;AACpB;AAAA,IACF;AAEA,QAAI,KAAK,YAAY;AACnB,WAAK,WAAW,KAAK,QAAQ;AAAA,IAC/B,OAAO;AACL,WAAK,aAAa,CAAC,QAAQ;AAAA,IAC7B;AAAA,EACF;AAAA,EAMA,YAAY,UAAU;AACpB,QAAI,CAAC,KAAK,YAAY;AACpB;AAAA,IACF;AACA,UAAM,QAAQ,KAAK,WAAW,QAAQ,QAAQ;AAC9C,QAAI,UAAU,IAAI;AAChB,WAAK,WAAW,OAAO,OAAO,CAAC;AAAA,IACjC;AAAA,EACF;AAAA,EAMA,OAAO,SAAS;AACd,QAAI;AACJ,UAAM,QAAQ,IAAI,YAAY,SAAS,SAAS,GAAG;AACjD,eAAS;AAAA,IACX,CAAC;AACD,WAAO;AAAA,MACL;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,sBAAQ;;;ACjGA,SAAR,OAAwB,UAAU;AACvC,SAAO,SAAS,KAAK,KAAK;AACxB,WAAO,SAAS,MAAM,MAAM,GAAG;AAAA,EACjC;AACF;;;AChBe,SAAR,aAA8B,SAAS;AAC5C,SAAO,cAAM,SAAS,OAAO,KAAM,QAAQ,iBAAiB;AAC9D;;;ACbA,IAAM,iBAAiB;AAAA,EACrB,UAAU;AAAA,EACV,oBAAoB;AAAA,EACpB,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,UAAU;AAAA,EACV,6BAA6B;AAAA,EAC7B,WAAW;AAAA,EACX,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,QAAQ;AAAA,EACR,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,OAAO;AAAA,EACP,UAAU;AAAA,EACV,aAAa;AAAA,EACb,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,6BAA6B;AAAA,EAC7B,gBAAgB;AAAA,EAChB,UAAU;AAAA,EACV,MAAM;AAAA,EACN,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,YAAY;AAAA,EACZ,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,mBAAmB;AAAA,EACnB,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,sBAAsB;AAAA,EACtB,iBAAiB;AAAA,EACjB,6BAA6B;AAAA,EAC7B,4BAA4B;AAAA,EAC5B,qBAAqB;AAAA,EACrB,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,yBAAyB;AAAA,EACzB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,cAAc;AAAA,EACd,aAAa;AAAA,EACb,+BAA+B;AACjC;AAEA,OAAO,QAAQ,cAAc,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACvD,iBAAe,SAAS;AAC1B,CAAC;AAED,IAAO,yBAAQ;;;AC3Cf,SAAS,eAAe,eAAe;AACrC,QAAM,UAAU,IAAI,cAAM,aAAa;AACvC,QAAM,WAAW,KAAK,cAAM,UAAU,SAAS,OAAO;AAGtD,gBAAM,OAAO,UAAU,cAAM,WAAW,SAAS,EAAC,YAAY,KAAI,CAAC;AAGnE,gBAAM,OAAO,UAAU,SAAS,MAAM,EAAC,YAAY,KAAI,CAAC;AAGxD,WAAS,SAAS,SAAS,OAAO,gBAAgB;AAChD,WAAO,eAAe,YAAY,eAAe,cAAc,CAAC;AAAA,EAClE;AAEA,SAAO;AACT;AAGA,IAAM,QAAQ,eAAe,gBAAQ;AAGrC,MAAM,QAAQ;AAGd,MAAM,gBAAgB;AACtB,MAAM,cAAc;AACpB,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,aAAa;AAGnB,MAAM,aAAa;AAGnB,MAAM,SAAS,MAAM;AAGrB,MAAM,MAAM,SAAS,IAAI,UAAU;AACjC,SAAO,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,SAAS;AAGf,MAAM,eAAe;AAGrB,MAAM,cAAc;AAEpB,MAAM,eAAe;AAErB,MAAM,aAAa,WAAS,uBAAe,cAAM,WAAW,KAAK,IAAI,IAAI,SAAS,KAAK,IAAI,KAAK;AAEhG,MAAM,aAAa,iBAAS;AAE5B,MAAM,iBAAiB;AAEvB,MAAM,UAAU;AAGhB,IAAO,gBAAQ;;;ACnFf,IAAM;AAAA,EACJ,OAAAE;AAAA,EACA,YAAAC;AAAA,EACA,eAAAC;AAAA,EACA,UAAAC;AAAA,EACA,aAAAC;AAAA,EACA,SAAAC;AAAA,EACA,KAAAC;AAAA,EACA;AAAA,EACA,cAAAC;AAAA,EACA,QAAAC;AAAA,EACA,YAAAC;AAAA,EACA,cAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAC;AACF,IAAI;", + "names": ["prototype", "descriptors", "filter", "hasOwnProperty", "filter", "prototype", "toString", "encode", "isFormData", "isFileList", "transitional", "filter", "self", "prototype", "validateStatus", "transitional", "merge", "validators", "transitional", "Axios", "AxiosError", "CanceledError", "isCancel", "CancelToken", "VERSION", "all", "isAxiosError", "spread", "toFormData", "AxiosHeaders", "HttpStatusCode", "mergeConfig"] +} diff --git a/web/client/node_modules/.vite/deps/chunk-JC4IRQUL.js b/web/client/node_modules/.vite/deps/chunk-JC4IRQUL.js new file mode 100644 index 0000000000000000000000000000000000000000..e23c475771bd2b6dbfd6929ff8a5b3a79eb308c0 --- /dev/null +++ b/web/client/node_modules/.vite/deps/chunk-JC4IRQUL.js @@ -0,0 +1,10 @@ +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +export { + __export +}; +//# sourceMappingURL=chunk-JC4IRQUL.js.map diff --git a/web/client/node_modules/.vite/deps/chunk-JC4IRQUL.js.map b/web/client/node_modules/.vite/deps/chunk-JC4IRQUL.js.map new file mode 100644 index 0000000000000000000000000000000000000000..98652118b6862120fb1a693020ad8654fe85851d --- /dev/null +++ b/web/client/node_modules/.vite/deps/chunk-JC4IRQUL.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": [], + "sourcesContent": [], + "mappings": "", + "names": [] +} diff --git a/web/client/node_modules/.vite/deps/chunk-LL35M65S.js b/web/client/node_modules/.vite/deps/chunk-LL35M65S.js new file mode 100644 index 0000000000000000000000000000000000000000..7728ccd1e5e81e20bec89674d5662a04bad17a5d --- /dev/null +++ b/web/client/node_modules/.vite/deps/chunk-LL35M65S.js @@ -0,0 +1,11153 @@ +// node_modules/@vue/shared/dist/shared.esm-bundler.js +function makeMap(str, expectsLowerCase) { + const set2 = new Set(str.split(",")); + return expectsLowerCase ? (val) => set2.has(val.toLowerCase()) : (val) => set2.has(val); +} +var EMPTY_OBJ = true ? Object.freeze({}) : {}; +var EMPTY_ARR = true ? Object.freeze([]) : []; +var NOOP = () => { +}; +var NO = () => false; +var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); +var isModelListener = (key) => key.startsWith("onUpdate:"); +var extend = Object.assign; +var remove = (arr, el) => { + const i = arr.indexOf(el); + if (i > -1) { + arr.splice(i, 1); + } +}; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var hasOwn = (val, key) => hasOwnProperty.call(val, key); +var isArray = Array.isArray; +var isMap = (val) => toTypeString(val) === "[object Map]"; +var isSet = (val) => toTypeString(val) === "[object Set]"; +var isDate = (val) => toTypeString(val) === "[object Date]"; +var isRegExp = (val) => toTypeString(val) === "[object RegExp]"; +var isFunction = (val) => typeof val === "function"; +var isString = (val) => typeof val === "string"; +var isSymbol = (val) => typeof val === "symbol"; +var isObject = (val) => val !== null && typeof val === "object"; +var isPromise = (val) => { + return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch); +}; +var objectToString = Object.prototype.toString; +var toTypeString = (value) => objectToString.call(value); +var toRawType = (value) => { + return toTypeString(value).slice(8, -1); +}; +var isPlainObject = (val) => toTypeString(val) === "[object Object]"; +var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; +var isReservedProp = makeMap( + ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" +); +var isBuiltInDirective = makeMap( + "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" +); +var cacheStringFunction = (fn) => { + const cache = /* @__PURE__ */ Object.create(null); + return (str) => { + const hit = cache[str]; + return hit || (cache[str] = fn(str)); + }; +}; +var camelizeRE = /-(\w)/g; +var camelize = cacheStringFunction((str) => { + return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); +}); +var hyphenateRE = /\B([A-Z])/g; +var hyphenate = cacheStringFunction( + (str) => str.replace(hyphenateRE, "-$1").toLowerCase() +); +var capitalize = cacheStringFunction((str) => { + return str.charAt(0).toUpperCase() + str.slice(1); +}); +var toHandlerKey = cacheStringFunction((str) => { + const s = str ? `on${capitalize(str)}` : ``; + return s; +}); +var hasChanged = (value, oldValue) => !Object.is(value, oldValue); +var invokeArrayFns = (fns, arg) => { + for (let i = 0; i < fns.length; i++) { + fns[i](arg); + } +}; +var def = (obj, key, value) => { + Object.defineProperty(obj, key, { + configurable: true, + enumerable: false, + value + }); +}; +var looseToNumber = (val) => { + const n = parseFloat(val); + return isNaN(n) ? val : n; +}; +var toNumber = (val) => { + const n = isString(val) ? Number(val) : NaN; + return isNaN(n) ? val : n; +}; +var _globalThis; +var getGlobalThis = () => { + return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); +}; +var GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error"; +var isGloballyAllowed = makeMap(GLOBALS_ALLOWED); +function normalizeStyle(value) { + if (isArray(value)) { + const res = {}; + for (let i = 0; i < value.length; i++) { + const item = value[i]; + const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item); + if (normalized) { + for (const key in normalized) { + res[key] = normalized[key]; + } + } + } + return res; + } else if (isString(value) || isObject(value)) { + return value; + } +} +var listDelimiterRE = /;(?![^(]*\))/g; +var propertyDelimiterRE = /:([^]+)/; +var styleCommentRE = /\/\*[^]*?\*\//g; +function parseStringStyle(cssText) { + const ret = {}; + cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { + if (item) { + const tmp = item.split(propertyDelimiterRE); + tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); + } + }); + return ret; +} +function stringifyStyle(styles) { + let ret = ""; + if (!styles || isString(styles)) { + return ret; + } + for (const key in styles) { + const value = styles[key]; + const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); + if (isString(value) || typeof value === "number") { + ret += `${normalizedKey}:${value};`; + } + } + return ret; +} +function normalizeClass(value) { + let res = ""; + if (isString(value)) { + res = value; + } else if (isArray(value)) { + for (let i = 0; i < value.length; i++) { + const normalized = normalizeClass(value[i]); + if (normalized) { + res += normalized + " "; + } + } + } else if (isObject(value)) { + for (const name in value) { + if (value[name]) { + res += name + " "; + } + } + } + return res.trim(); +} +function normalizeProps(props) { + if (!props) + return null; + let { class: klass, style } = props; + if (klass && !isString(klass)) { + props.class = normalizeClass(klass); + } + if (style) { + props.style = normalizeStyle(style); + } + return props; +} +var HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; +var SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; +var MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; +var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; +var isHTMLTag = makeMap(HTML_TAGS); +var isSVGTag = makeMap(SVG_TAGS); +var isMathMLTag = makeMap(MATH_TAGS); +var isVoidTag = makeMap(VOID_TAGS); +var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; +var isSpecialBooleanAttr = makeMap(specialBooleanAttrs); +var isBooleanAttr = makeMap( + specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` +); +function includeBooleanAttr(value) { + return !!value || value === ""; +} +var isKnownHtmlAttr = makeMap( + `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` +); +var isKnownSvgAttr = makeMap( + `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan` +); +function isRenderableAttrValue(value) { + if (value == null) { + return false; + } + const type = typeof value; + return type === "string" || type === "number" || type === "boolean"; +} +function looseCompareArrays(a, b) { + if (a.length !== b.length) + return false; + let equal = true; + for (let i = 0; equal && i < a.length; i++) { + equal = looseEqual(a[i], b[i]); + } + return equal; +} +function looseEqual(a, b) { + if (a === b) + return true; + let aValidType = isDate(a); + let bValidType = isDate(b); + if (aValidType || bValidType) { + return aValidType && bValidType ? a.getTime() === b.getTime() : false; + } + aValidType = isSymbol(a); + bValidType = isSymbol(b); + if (aValidType || bValidType) { + return a === b; + } + aValidType = isArray(a); + bValidType = isArray(b); + if (aValidType || bValidType) { + return aValidType && bValidType ? looseCompareArrays(a, b) : false; + } + aValidType = isObject(a); + bValidType = isObject(b); + if (aValidType || bValidType) { + if (!aValidType || !bValidType) { + return false; + } + const aKeysCount = Object.keys(a).length; + const bKeysCount = Object.keys(b).length; + if (aKeysCount !== bKeysCount) { + return false; + } + for (const key in a) { + const aHasKey = a.hasOwnProperty(key); + const bHasKey = b.hasOwnProperty(key); + if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) { + return false; + } + } + } + return String(a) === String(b); +} +function looseIndexOf(arr, val) { + return arr.findIndex((item) => looseEqual(item, val)); +} +var toDisplayString = (val) => { + return isString(val) ? val : val == null ? "" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val); +}; +var replacer = (_key, val) => { + if (val && val.__v_isRef) { + return replacer(_key, val.value); + } else if (isMap(val)) { + return { + [`Map(${val.size})`]: [...val.entries()].reduce( + (entries, [key, val2], i) => { + entries[stringifySymbol(key, i) + " =>"] = val2; + return entries; + }, + {} + ) + }; + } else if (isSet(val)) { + return { + [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) + }; + } else if (isSymbol(val)) { + return stringifySymbol(val); + } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { + return String(val); + } + return val; +}; +var stringifySymbol = (v, i = "") => { + var _a; + return isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v; +}; + +// node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js +function warn(msg, ...args) { + console.warn(`[Vue warn] ${msg}`, ...args); +} +var activeEffectScope; +var EffectScope = class { + constructor(detached = false) { + this.detached = detached; + this._active = true; + this.effects = []; + this.cleanups = []; + this.parent = activeEffectScope; + if (!detached && activeEffectScope) { + this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( + this + ) - 1; + } + } + get active() { + return this._active; + } + run(fn) { + if (this._active) { + const currentEffectScope = activeEffectScope; + try { + activeEffectScope = this; + return fn(); + } finally { + activeEffectScope = currentEffectScope; + } + } else if (true) { + warn(`cannot run an inactive effect scope.`); + } + } + on() { + activeEffectScope = this; + } + off() { + activeEffectScope = this.parent; + } + stop(fromParent) { + if (this._active) { + let i, l; + for (i = 0, l = this.effects.length; i < l; i++) { + this.effects[i].stop(); + } + for (i = 0, l = this.cleanups.length; i < l; i++) { + this.cleanups[i](); + } + if (this.scopes) { + for (i = 0, l = this.scopes.length; i < l; i++) { + this.scopes[i].stop(true); + } + } + if (!this.detached && this.parent && !fromParent) { + const last = this.parent.scopes.pop(); + if (last && last !== this) { + this.parent.scopes[this.index] = last; + last.index = this.index; + } + } + this.parent = void 0; + this._active = false; + } + } +}; +function effectScope(detached) { + return new EffectScope(detached); +} +function recordEffectScope(effect2, scope = activeEffectScope) { + if (scope && scope.active) { + scope.effects.push(effect2); + } +} +function getCurrentScope() { + return activeEffectScope; +} +function onScopeDispose(fn) { + if (activeEffectScope) { + activeEffectScope.cleanups.push(fn); + } else if (true) { + warn( + `onScopeDispose() is called when there is no active effect scope to be associated with.` + ); + } +} +var activeEffect; +var ReactiveEffect = class { + constructor(fn, trigger2, scheduler, scope) { + this.fn = fn; + this.trigger = trigger2; + this.scheduler = scheduler; + this.active = true; + this.deps = []; + this._dirtyLevel = 4; + this._trackId = 0; + this._runnings = 0; + this._shouldSchedule = false; + this._depsLength = 0; + recordEffectScope(this, scope); + } + get dirty() { + if (this._dirtyLevel === 2 || this._dirtyLevel === 3) { + this._dirtyLevel = 1; + pauseTracking(); + for (let i = 0; i < this._depsLength; i++) { + const dep = this.deps[i]; + if (dep.computed) { + triggerComputed(dep.computed); + if (this._dirtyLevel >= 4) { + break; + } + } + } + if (this._dirtyLevel === 1) { + this._dirtyLevel = 0; + } + resetTracking(); + } + return this._dirtyLevel >= 4; + } + set dirty(v) { + this._dirtyLevel = v ? 4 : 0; + } + run() { + this._dirtyLevel = 0; + if (!this.active) { + return this.fn(); + } + let lastShouldTrack = shouldTrack; + let lastEffect = activeEffect; + try { + shouldTrack = true; + activeEffect = this; + this._runnings++; + preCleanupEffect(this); + return this.fn(); + } finally { + postCleanupEffect(this); + this._runnings--; + activeEffect = lastEffect; + shouldTrack = lastShouldTrack; + } + } + stop() { + var _a; + if (this.active) { + preCleanupEffect(this); + postCleanupEffect(this); + (_a = this.onStop) == null ? void 0 : _a.call(this); + this.active = false; + } + } +}; +function triggerComputed(computed3) { + return computed3.value; +} +function preCleanupEffect(effect2) { + effect2._trackId++; + effect2._depsLength = 0; +} +function postCleanupEffect(effect2) { + if (effect2.deps.length > effect2._depsLength) { + for (let i = effect2._depsLength; i < effect2.deps.length; i++) { + cleanupDepEffect(effect2.deps[i], effect2); + } + effect2.deps.length = effect2._depsLength; + } +} +function cleanupDepEffect(dep, effect2) { + const trackId = dep.get(effect2); + if (trackId !== void 0 && effect2._trackId !== trackId) { + dep.delete(effect2); + if (dep.size === 0) { + dep.cleanup(); + } + } +} +function effect(fn, options) { + if (fn.effect instanceof ReactiveEffect) { + fn = fn.effect.fn; + } + const _effect = new ReactiveEffect(fn, NOOP, () => { + if (_effect.dirty) { + _effect.run(); + } + }); + if (options) { + extend(_effect, options); + if (options.scope) + recordEffectScope(_effect, options.scope); + } + if (!options || !options.lazy) { + _effect.run(); + } + const runner = _effect.run.bind(_effect); + runner.effect = _effect; + return runner; +} +function stop(runner) { + runner.effect.stop(); +} +var shouldTrack = true; +var pauseScheduleStack = 0; +var trackStack = []; +function pauseTracking() { + trackStack.push(shouldTrack); + shouldTrack = false; +} +function resetTracking() { + const last = trackStack.pop(); + shouldTrack = last === void 0 ? true : last; +} +function pauseScheduling() { + pauseScheduleStack++; +} +function resetScheduling() { + pauseScheduleStack--; + while (!pauseScheduleStack && queueEffectSchedulers.length) { + queueEffectSchedulers.shift()(); + } +} +function trackEffect(effect2, dep, debuggerEventExtraInfo) { + var _a; + if (dep.get(effect2) !== effect2._trackId) { + dep.set(effect2, effect2._trackId); + const oldDep = effect2.deps[effect2._depsLength]; + if (oldDep !== dep) { + if (oldDep) { + cleanupDepEffect(oldDep, effect2); + } + effect2.deps[effect2._depsLength++] = dep; + } else { + effect2._depsLength++; + } + if (true) { + (_a = effect2.onTrack) == null ? void 0 : _a.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo)); + } + } +} +var queueEffectSchedulers = []; +function triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) { + var _a; + pauseScheduling(); + for (const effect2 of dep.keys()) { + let tracking; + if (effect2._dirtyLevel < dirtyLevel && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { + effect2._shouldSchedule || (effect2._shouldSchedule = effect2._dirtyLevel === 0); + effect2._dirtyLevel = dirtyLevel; + } + if (effect2._shouldSchedule && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { + if (true) { + (_a = effect2.onTrigger) == null ? void 0 : _a.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo)); + } + effect2.trigger(); + if ((!effect2._runnings || effect2.allowRecurse) && effect2._dirtyLevel !== 2) { + effect2._shouldSchedule = false; + if (effect2.scheduler) { + queueEffectSchedulers.push(effect2.scheduler); + } + } + } + } + resetScheduling(); +} +var createDep = (cleanup, computed3) => { + const dep = /* @__PURE__ */ new Map(); + dep.cleanup = cleanup; + dep.computed = computed3; + return dep; +}; +var targetMap = /* @__PURE__ */ new WeakMap(); +var ITERATE_KEY = Symbol(true ? "iterate" : ""); +var MAP_KEY_ITERATE_KEY = Symbol(true ? "Map key iterate" : ""); +function track(target, type, key) { + if (shouldTrack && activeEffect) { + let depsMap = targetMap.get(target); + if (!depsMap) { + targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); + } + let dep = depsMap.get(key); + if (!dep) { + depsMap.set(key, dep = createDep(() => depsMap.delete(key))); + } + trackEffect( + activeEffect, + dep, + true ? { + target, + type, + key + } : void 0 + ); + } +} +function trigger(target, type, key, newValue, oldValue, oldTarget) { + const depsMap = targetMap.get(target); + if (!depsMap) { + return; + } + let deps = []; + if (type === "clear") { + deps = [...depsMap.values()]; + } else if (key === "length" && isArray(target)) { + const newLength = Number(newValue); + depsMap.forEach((dep, key2) => { + if (key2 === "length" || !isSymbol(key2) && key2 >= newLength) { + deps.push(dep); + } + }); + } else { + if (key !== void 0) { + deps.push(depsMap.get(key)); + } + switch (type) { + case "add": + if (!isArray(target)) { + deps.push(depsMap.get(ITERATE_KEY)); + if (isMap(target)) { + deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); + } + } else if (isIntegerKey(key)) { + deps.push(depsMap.get("length")); + } + break; + case "delete": + if (!isArray(target)) { + deps.push(depsMap.get(ITERATE_KEY)); + if (isMap(target)) { + deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); + } + } + break; + case "set": + if (isMap(target)) { + deps.push(depsMap.get(ITERATE_KEY)); + } + break; + } + } + pauseScheduling(); + for (const dep of deps) { + if (dep) { + triggerEffects( + dep, + 4, + true ? { + target, + type, + key, + newValue, + oldValue, + oldTarget + } : void 0 + ); + } + } + resetScheduling(); +} +function getDepFromReactive(object, key) { + var _a; + return (_a = targetMap.get(object)) == null ? void 0 : _a.get(key); +} +var isNonTrackableKeys = makeMap(`__proto__,__v_isRef,__isVue`); +var builtInSymbols = new Set( + Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol) +); +var arrayInstrumentations = createArrayInstrumentations(); +function createArrayInstrumentations() { + const instrumentations = {}; + ["includes", "indexOf", "lastIndexOf"].forEach((key) => { + instrumentations[key] = function(...args) { + const arr = toRaw(this); + for (let i = 0, l = this.length; i < l; i++) { + track(arr, "get", i + ""); + } + const res = arr[key](...args); + if (res === -1 || res === false) { + return arr[key](...args.map(toRaw)); + } else { + return res; + } + }; + }); + ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { + instrumentations[key] = function(...args) { + pauseTracking(); + pauseScheduling(); + const res = toRaw(this)[key].apply(this, args); + resetScheduling(); + resetTracking(); + return res; + }; + }); + return instrumentations; +} +function hasOwnProperty2(key) { + const obj = toRaw(this); + track(obj, "has", key); + return obj.hasOwnProperty(key); +} +var BaseReactiveHandler = class { + constructor(_isReadonly = false, _isShallow = false) { + this._isReadonly = _isReadonly; + this._isShallow = _isShallow; + } + get(target, key, receiver) { + const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; + if (key === "__v_isReactive") { + return !isReadonly2; + } else if (key === "__v_isReadonly") { + return isReadonly2; + } else if (key === "__v_isShallow") { + return isShallow2; + } else if (key === "__v_raw") { + if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { + return target; + } + return; + } + const targetIsArray = isArray(target); + if (!isReadonly2) { + if (targetIsArray && hasOwn(arrayInstrumentations, key)) { + return Reflect.get(arrayInstrumentations, key, receiver); + } + if (key === "hasOwnProperty") { + return hasOwnProperty2; + } + } + const res = Reflect.get(target, key, receiver); + if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { + return res; + } + if (!isReadonly2) { + track(target, "get", key); + } + if (isShallow2) { + return res; + } + if (isRef(res)) { + return targetIsArray && isIntegerKey(key) ? res : res.value; + } + if (isObject(res)) { + return isReadonly2 ? readonly(res) : reactive(res); + } + return res; + } +}; +var MutableReactiveHandler = class extends BaseReactiveHandler { + constructor(isShallow2 = false) { + super(false, isShallow2); + } + set(target, key, value, receiver) { + let oldValue = target[key]; + if (!this._isShallow) { + const isOldValueReadonly = isReadonly(oldValue); + if (!isShallow(value) && !isReadonly(value)) { + oldValue = toRaw(oldValue); + value = toRaw(value); + } + if (!isArray(target) && isRef(oldValue) && !isRef(value)) { + if (isOldValueReadonly) { + return false; + } else { + oldValue.value = value; + return true; + } + } + } + const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key); + const result = Reflect.set(target, key, value, receiver); + if (target === toRaw(receiver)) { + if (!hadKey) { + trigger(target, "add", key, value); + } else if (hasChanged(value, oldValue)) { + trigger(target, "set", key, value, oldValue); + } + } + return result; + } + deleteProperty(target, key) { + const hadKey = hasOwn(target, key); + const oldValue = target[key]; + const result = Reflect.deleteProperty(target, key); + if (result && hadKey) { + trigger(target, "delete", key, void 0, oldValue); + } + return result; + } + has(target, key) { + const result = Reflect.has(target, key); + if (!isSymbol(key) || !builtInSymbols.has(key)) { + track(target, "has", key); + } + return result; + } + ownKeys(target) { + track( + target, + "iterate", + isArray(target) ? "length" : ITERATE_KEY + ); + return Reflect.ownKeys(target); + } +}; +var ReadonlyReactiveHandler = class extends BaseReactiveHandler { + constructor(isShallow2 = false) { + super(true, isShallow2); + } + set(target, key) { + if (true) { + warn( + `Set operation on key "${String(key)}" failed: target is readonly.`, + target + ); + } + return true; + } + deleteProperty(target, key) { + if (true) { + warn( + `Delete operation on key "${String(key)}" failed: target is readonly.`, + target + ); + } + return true; + } +}; +var mutableHandlers = new MutableReactiveHandler(); +var readonlyHandlers = new ReadonlyReactiveHandler(); +var shallowReactiveHandlers = new MutableReactiveHandler( + true +); +var shallowReadonlyHandlers = new ReadonlyReactiveHandler(true); +var toShallow = (value) => value; +var getProto = (v) => Reflect.getPrototypeOf(v); +function get(target, key, isReadonly2 = false, isShallow2 = false) { + target = target["__v_raw"]; + const rawTarget = toRaw(target); + const rawKey = toRaw(key); + if (!isReadonly2) { + if (hasChanged(key, rawKey)) { + track(rawTarget, "get", key); + } + track(rawTarget, "get", rawKey); + } + const { has: has2 } = getProto(rawTarget); + const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; + if (has2.call(rawTarget, key)) { + return wrap(target.get(key)); + } else if (has2.call(rawTarget, rawKey)) { + return wrap(target.get(rawKey)); + } else if (target !== rawTarget) { + target.get(key); + } +} +function has(key, isReadonly2 = false) { + const target = this["__v_raw"]; + const rawTarget = toRaw(target); + const rawKey = toRaw(key); + if (!isReadonly2) { + if (hasChanged(key, rawKey)) { + track(rawTarget, "has", key); + } + track(rawTarget, "has", rawKey); + } + return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); +} +function size(target, isReadonly2 = false) { + target = target["__v_raw"]; + !isReadonly2 && track(toRaw(target), "iterate", ITERATE_KEY); + return Reflect.get(target, "size", target); +} +function add(value) { + value = toRaw(value); + const target = toRaw(this); + const proto = getProto(target); + const hadKey = proto.has.call(target, value); + if (!hadKey) { + target.add(value); + trigger(target, "add", value, value); + } + return this; +} +function set(key, value) { + value = toRaw(value); + const target = toRaw(this); + const { has: has2, get: get2 } = getProto(target); + let hadKey = has2.call(target, key); + if (!hadKey) { + key = toRaw(key); + hadKey = has2.call(target, key); + } else if (true) { + checkIdentityKeys(target, has2, key); + } + const oldValue = get2.call(target, key); + target.set(key, value); + if (!hadKey) { + trigger(target, "add", key, value); + } else if (hasChanged(value, oldValue)) { + trigger(target, "set", key, value, oldValue); + } + return this; +} +function deleteEntry(key) { + const target = toRaw(this); + const { has: has2, get: get2 } = getProto(target); + let hadKey = has2.call(target, key); + if (!hadKey) { + key = toRaw(key); + hadKey = has2.call(target, key); + } else if (true) { + checkIdentityKeys(target, has2, key); + } + const oldValue = get2 ? get2.call(target, key) : void 0; + const result = target.delete(key); + if (hadKey) { + trigger(target, "delete", key, void 0, oldValue); + } + return result; +} +function clear() { + const target = toRaw(this); + const hadItems = target.size !== 0; + const oldTarget = true ? isMap(target) ? new Map(target) : new Set(target) : void 0; + const result = target.clear(); + if (hadItems) { + trigger(target, "clear", void 0, void 0, oldTarget); + } + return result; +} +function createForEach(isReadonly2, isShallow2) { + return function forEach(callback, thisArg) { + const observed = this; + const target = observed["__v_raw"]; + const rawTarget = toRaw(target); + const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; + !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); + return target.forEach((value, key) => { + return callback.call(thisArg, wrap(value), wrap(key), observed); + }); + }; +} +function createIterableMethod(method, isReadonly2, isShallow2) { + return function(...args) { + const target = this["__v_raw"]; + const rawTarget = toRaw(target); + const targetIsMap = isMap(rawTarget); + const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; + const isKeyOnly = method === "keys" && targetIsMap; + const innerIterator = target[method](...args); + const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; + !isReadonly2 && track( + rawTarget, + "iterate", + isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY + ); + return { + next() { + const { value, done } = innerIterator.next(); + return done ? { value, done } : { + value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), + done + }; + }, + [Symbol.iterator]() { + return this; + } + }; + }; +} +function createReadonlyMethod(type) { + return function(...args) { + if (true) { + const key = args[0] ? `on key "${args[0]}" ` : ``; + warn( + `${capitalize(type)} operation ${key}failed: target is readonly.`, + toRaw(this) + ); + } + return type === "delete" ? false : type === "clear" ? void 0 : this; + }; +} +function createInstrumentations() { + const mutableInstrumentations2 = { + get(key) { + return get(this, key); + }, + get size() { + return size(this); + }, + has, + add, + set, + delete: deleteEntry, + clear, + forEach: createForEach(false, false) + }; + const shallowInstrumentations2 = { + get(key) { + return get(this, key, false, true); + }, + get size() { + return size(this); + }, + has, + add, + set, + delete: deleteEntry, + clear, + forEach: createForEach(false, true) + }; + const readonlyInstrumentations2 = { + get(key) { + return get(this, key, true); + }, + get size() { + return size(this, true); + }, + has(key) { + return has.call(this, key, true); + }, + add: createReadonlyMethod("add"), + set: createReadonlyMethod("set"), + delete: createReadonlyMethod("delete"), + clear: createReadonlyMethod("clear"), + forEach: createForEach(true, false) + }; + const shallowReadonlyInstrumentations2 = { + get(key) { + return get(this, key, true, true); + }, + get size() { + return size(this, true); + }, + has(key) { + return has.call(this, key, true); + }, + add: createReadonlyMethod("add"), + set: createReadonlyMethod("set"), + delete: createReadonlyMethod("delete"), + clear: createReadonlyMethod("clear"), + forEach: createForEach(true, true) + }; + const iteratorMethods = ["keys", "values", "entries", Symbol.iterator]; + iteratorMethods.forEach((method) => { + mutableInstrumentations2[method] = createIterableMethod( + method, + false, + false + ); + readonlyInstrumentations2[method] = createIterableMethod( + method, + true, + false + ); + shallowInstrumentations2[method] = createIterableMethod( + method, + false, + true + ); + shallowReadonlyInstrumentations2[method] = createIterableMethod( + method, + true, + true + ); + }); + return [ + mutableInstrumentations2, + readonlyInstrumentations2, + shallowInstrumentations2, + shallowReadonlyInstrumentations2 + ]; +} +var [ + mutableInstrumentations, + readonlyInstrumentations, + shallowInstrumentations, + shallowReadonlyInstrumentations +] = createInstrumentations(); +function createInstrumentationGetter(isReadonly2, shallow) { + const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; + return (target, key, receiver) => { + if (key === "__v_isReactive") { + return !isReadonly2; + } else if (key === "__v_isReadonly") { + return isReadonly2; + } else if (key === "__v_raw") { + return target; + } + return Reflect.get( + hasOwn(instrumentations, key) && key in target ? instrumentations : target, + key, + receiver + ); + }; +} +var mutableCollectionHandlers = { + get: createInstrumentationGetter(false, false) +}; +var shallowCollectionHandlers = { + get: createInstrumentationGetter(false, true) +}; +var readonlyCollectionHandlers = { + get: createInstrumentationGetter(true, false) +}; +var shallowReadonlyCollectionHandlers = { + get: createInstrumentationGetter(true, true) +}; +function checkIdentityKeys(target, has2, key) { + const rawKey = toRaw(key); + if (rawKey !== key && has2.call(target, rawKey)) { + const type = toRawType(target); + warn( + `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.` + ); + } +} +var reactiveMap = /* @__PURE__ */ new WeakMap(); +var shallowReactiveMap = /* @__PURE__ */ new WeakMap(); +var readonlyMap = /* @__PURE__ */ new WeakMap(); +var shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); +function targetTypeMap(rawType) { + switch (rawType) { + case "Object": + case "Array": + return 1; + case "Map": + case "Set": + case "WeakMap": + case "WeakSet": + return 2; + default: + return 0; + } +} +function getTargetType(value) { + return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value)); +} +function reactive(target) { + if (isReadonly(target)) { + return target; + } + return createReactiveObject( + target, + false, + mutableHandlers, + mutableCollectionHandlers, + reactiveMap + ); +} +function shallowReactive(target) { + return createReactiveObject( + target, + false, + shallowReactiveHandlers, + shallowCollectionHandlers, + shallowReactiveMap + ); +} +function readonly(target) { + return createReactiveObject( + target, + true, + readonlyHandlers, + readonlyCollectionHandlers, + readonlyMap + ); +} +function shallowReadonly(target) { + return createReactiveObject( + target, + true, + shallowReadonlyHandlers, + shallowReadonlyCollectionHandlers, + shallowReadonlyMap + ); +} +function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { + if (!isObject(target)) { + if (true) { + warn(`value cannot be made reactive: ${String(target)}`); + } + return target; + } + if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { + return target; + } + const existingProxy = proxyMap.get(target); + if (existingProxy) { + return existingProxy; + } + const targetType = getTargetType(target); + if (targetType === 0) { + return target; + } + const proxy = new Proxy( + target, + targetType === 2 ? collectionHandlers : baseHandlers + ); + proxyMap.set(target, proxy); + return proxy; +} +function isReactive(value) { + if (isReadonly(value)) { + return isReactive(value["__v_raw"]); + } + return !!(value && value["__v_isReactive"]); +} +function isReadonly(value) { + return !!(value && value["__v_isReadonly"]); +} +function isShallow(value) { + return !!(value && value["__v_isShallow"]); +} +function isProxy(value) { + return isReactive(value) || isReadonly(value); +} +function toRaw(observed) { + const raw = observed && observed["__v_raw"]; + return raw ? toRaw(raw) : observed; +} +function markRaw(value) { + if (Object.isExtensible(value)) { + def(value, "__v_skip", true); + } + return value; +} +var toReactive = (value) => isObject(value) ? reactive(value) : value; +var toReadonly = (value) => isObject(value) ? readonly(value) : value; +var COMPUTED_SIDE_EFFECT_WARN = `Computed is still dirty after getter evaluation, likely because a computed is mutating its own dependency in its getter. State mutations in computed getters should be avoided. Check the docs for more details: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free`; +var ComputedRefImpl = class { + constructor(getter, _setter, isReadonly2, isSSR) { + this.getter = getter; + this._setter = _setter; + this.dep = void 0; + this.__v_isRef = true; + this["__v_isReadonly"] = false; + this.effect = new ReactiveEffect( + () => getter(this._value), + () => triggerRefValue( + this, + this.effect._dirtyLevel === 2 ? 2 : 3 + ) + ); + this.effect.computed = this; + this.effect.active = this._cacheable = !isSSR; + this["__v_isReadonly"] = isReadonly2; + } + get value() { + const self2 = toRaw(this); + if ((!self2._cacheable || self2.effect.dirty) && hasChanged(self2._value, self2._value = self2.effect.run())) { + triggerRefValue(self2, 4); + } + trackRefValue(self2); + if (self2.effect._dirtyLevel >= 2) { + if (this._warnRecursive) { + warn(COMPUTED_SIDE_EFFECT_WARN, ` + +getter: `, this.getter); + } + triggerRefValue(self2, 2); + } + return self2._value; + } + set value(newValue) { + this._setter(newValue); + } + get _dirty() { + return this.effect.dirty; + } + set _dirty(v) { + this.effect.dirty = v; + } +}; +function computed(getterOrOptions, debugOptions, isSSR = false) { + let getter; + let setter; + const onlyGetter = isFunction(getterOrOptions); + if (onlyGetter) { + getter = getterOrOptions; + setter = true ? () => { + warn("Write operation failed: computed value is readonly"); + } : NOOP; + } else { + getter = getterOrOptions.get; + setter = getterOrOptions.set; + } + const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR); + if (debugOptions && !isSSR) { + cRef.effect.onTrack = debugOptions.onTrack; + cRef.effect.onTrigger = debugOptions.onTrigger; + } + return cRef; +} +function trackRefValue(ref2) { + var _a; + if (shouldTrack && activeEffect) { + ref2 = toRaw(ref2); + trackEffect( + activeEffect, + (_a = ref2.dep) != null ? _a : ref2.dep = createDep( + () => ref2.dep = void 0, + ref2 instanceof ComputedRefImpl ? ref2 : void 0 + ), + true ? { + target: ref2, + type: "get", + key: "value" + } : void 0 + ); + } +} +function triggerRefValue(ref2, dirtyLevel = 4, newVal) { + ref2 = toRaw(ref2); + const dep = ref2.dep; + if (dep) { + triggerEffects( + dep, + dirtyLevel, + true ? { + target: ref2, + type: "set", + key: "value", + newValue: newVal + } : void 0 + ); + } +} +function isRef(r) { + return !!(r && r.__v_isRef === true); +} +function ref(value) { + return createRef(value, false); +} +function shallowRef(value) { + return createRef(value, true); +} +function createRef(rawValue, shallow) { + if (isRef(rawValue)) { + return rawValue; + } + return new RefImpl(rawValue, shallow); +} +var RefImpl = class { + constructor(value, __v_isShallow) { + this.__v_isShallow = __v_isShallow; + this.dep = void 0; + this.__v_isRef = true; + this._rawValue = __v_isShallow ? value : toRaw(value); + this._value = __v_isShallow ? value : toReactive(value); + } + get value() { + trackRefValue(this); + return this._value; + } + set value(newVal) { + const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal); + newVal = useDirectValue ? newVal : toRaw(newVal); + if (hasChanged(newVal, this._rawValue)) { + this._rawValue = newVal; + this._value = useDirectValue ? newVal : toReactive(newVal); + triggerRefValue(this, 4, newVal); + } + } +}; +function triggerRef(ref2) { + triggerRefValue(ref2, 4, true ? ref2.value : void 0); +} +function unref(ref2) { + return isRef(ref2) ? ref2.value : ref2; +} +function toValue(source) { + return isFunction(source) ? source() : unref(source); +} +var shallowUnwrapHandlers = { + get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), + set: (target, key, value, receiver) => { + const oldValue = target[key]; + if (isRef(oldValue) && !isRef(value)) { + oldValue.value = value; + return true; + } else { + return Reflect.set(target, key, value, receiver); + } + } +}; +function proxyRefs(objectWithRefs) { + return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); +} +var CustomRefImpl = class { + constructor(factory) { + this.dep = void 0; + this.__v_isRef = true; + const { get: get2, set: set2 } = factory( + () => trackRefValue(this), + () => triggerRefValue(this) + ); + this._get = get2; + this._set = set2; + } + get value() { + return this._get(); + } + set value(newVal) { + this._set(newVal); + } +}; +function customRef(factory) { + return new CustomRefImpl(factory); +} +function toRefs(object) { + if (!isProxy(object)) { + warn(`toRefs() expects a reactive object but received a plain one.`); + } + const ret = isArray(object) ? new Array(object.length) : {}; + for (const key in object) { + ret[key] = propertyToRef(object, key); + } + return ret; +} +var ObjectRefImpl = class { + constructor(_object, _key, _defaultValue) { + this._object = _object; + this._key = _key; + this._defaultValue = _defaultValue; + this.__v_isRef = true; + } + get value() { + const val = this._object[this._key]; + return val === void 0 ? this._defaultValue : val; + } + set value(newVal) { + this._object[this._key] = newVal; + } + get dep() { + return getDepFromReactive(toRaw(this._object), this._key); + } +}; +var GetterRefImpl = class { + constructor(_getter) { + this._getter = _getter; + this.__v_isRef = true; + this.__v_isReadonly = true; + } + get value() { + return this._getter(); + } +}; +function toRef(source, key, defaultValue) { + if (isRef(source)) { + return source; + } else if (isFunction(source)) { + return new GetterRefImpl(source); + } else if (isObject(source) && arguments.length > 1) { + return propertyToRef(source, key, defaultValue); + } else { + return ref(source); + } +} +function propertyToRef(source, key, defaultValue) { + const val = source[key]; + return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue); +} +var TrackOpTypes = { + "GET": "get", + "HAS": "has", + "ITERATE": "iterate" +}; +var TriggerOpTypes = { + "SET": "set", + "ADD": "add", + "DELETE": "delete", + "CLEAR": "clear" +}; + +// node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js +var stack = []; +function pushWarningContext(vnode) { + stack.push(vnode); +} +function popWarningContext() { + stack.pop(); +} +function warn$1(msg, ...args) { + pauseTracking(); + const instance = stack.length ? stack[stack.length - 1].component : null; + const appWarnHandler = instance && instance.appContext.config.warnHandler; + const trace = getComponentTrace(); + if (appWarnHandler) { + callWithErrorHandling( + appWarnHandler, + instance, + 11, + [ + msg + args.join(""), + instance && instance.proxy, + trace.map( + ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` + ).join("\n"), + trace + ] + ); + } else { + const warnArgs = [`[Vue warn]: ${msg}`, ...args]; + if (trace.length && true) { + warnArgs.push(` +`, ...formatTrace(trace)); + } + console.warn(...warnArgs); + } + resetTracking(); +} +function getComponentTrace() { + let currentVNode = stack[stack.length - 1]; + if (!currentVNode) { + return []; + } + const normalizedStack = []; + while (currentVNode) { + const last = normalizedStack[0]; + if (last && last.vnode === currentVNode) { + last.recurseCount++; + } else { + normalizedStack.push({ + vnode: currentVNode, + recurseCount: 0 + }); + } + const parentInstance = currentVNode.component && currentVNode.component.parent; + currentVNode = parentInstance && parentInstance.vnode; + } + return normalizedStack; +} +function formatTrace(trace) { + const logs = []; + trace.forEach((entry, i) => { + logs.push(...i === 0 ? [] : [` +`], ...formatTraceEntry(entry)); + }); + return logs; +} +function formatTraceEntry({ vnode, recurseCount }) { + const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; + const isRoot = vnode.component ? vnode.component.parent == null : false; + const open = ` at <${formatComponentName( + vnode.component, + vnode.type, + isRoot + )}`; + const close = `>` + postfix; + return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close]; +} +function formatProps(props) { + const res = []; + const keys = Object.keys(props); + keys.slice(0, 3).forEach((key) => { + res.push(...formatProp(key, props[key])); + }); + if (keys.length > 3) { + res.push(` ...`); + } + return res; +} +function formatProp(key, value, raw) { + if (isString(value)) { + value = JSON.stringify(value); + return raw ? value : [`${key}=${value}`]; + } else if (typeof value === "number" || typeof value === "boolean" || value == null) { + return raw ? value : [`${key}=${value}`]; + } else if (isRef(value)) { + value = formatProp(key, toRaw(value.value), true); + return raw ? value : [`${key}=Ref<`, value, `>`]; + } else if (isFunction(value)) { + return [`${key}=fn${value.name ? `<${value.name}>` : ``}`]; + } else { + value = toRaw(value); + return raw ? value : [`${key}=`, value]; + } +} +function assertNumber(val, type) { + if (false) + return; + if (val === void 0) { + return; + } else if (typeof val !== "number") { + warn$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`); + } else if (isNaN(val)) { + warn$1(`${type} is NaN - the duration expression might be incorrect.`); + } +} +var ErrorCodes = { + "SETUP_FUNCTION": 0, + "0": "SETUP_FUNCTION", + "RENDER_FUNCTION": 1, + "1": "RENDER_FUNCTION", + "WATCH_GETTER": 2, + "2": "WATCH_GETTER", + "WATCH_CALLBACK": 3, + "3": "WATCH_CALLBACK", + "WATCH_CLEANUP": 4, + "4": "WATCH_CLEANUP", + "NATIVE_EVENT_HANDLER": 5, + "5": "NATIVE_EVENT_HANDLER", + "COMPONENT_EVENT_HANDLER": 6, + "6": "COMPONENT_EVENT_HANDLER", + "VNODE_HOOK": 7, + "7": "VNODE_HOOK", + "DIRECTIVE_HOOK": 8, + "8": "DIRECTIVE_HOOK", + "TRANSITION_HOOK": 9, + "9": "TRANSITION_HOOK", + "APP_ERROR_HANDLER": 10, + "10": "APP_ERROR_HANDLER", + "APP_WARN_HANDLER": 11, + "11": "APP_WARN_HANDLER", + "FUNCTION_REF": 12, + "12": "FUNCTION_REF", + "ASYNC_COMPONENT_LOADER": 13, + "13": "ASYNC_COMPONENT_LOADER", + "SCHEDULER": 14, + "14": "SCHEDULER" +}; +var ErrorTypeStrings$1 = { + ["sp"]: "serverPrefetch hook", + ["bc"]: "beforeCreate hook", + ["c"]: "created hook", + ["bm"]: "beforeMount hook", + ["m"]: "mounted hook", + ["bu"]: "beforeUpdate hook", + ["u"]: "updated", + ["bum"]: "beforeUnmount hook", + ["um"]: "unmounted hook", + ["a"]: "activated hook", + ["da"]: "deactivated hook", + ["ec"]: "errorCaptured hook", + ["rtc"]: "renderTracked hook", + ["rtg"]: "renderTriggered hook", + [0]: "setup function", + [1]: "render function", + [2]: "watcher getter", + [3]: "watcher callback", + [4]: "watcher cleanup function", + [5]: "native event handler", + [6]: "component event handler", + [7]: "vnode hook", + [8]: "directive hook", + [9]: "transition hook", + [10]: "app errorHandler", + [11]: "app warnHandler", + [12]: "ref function", + [13]: "async component loader", + [14]: "scheduler flush. This is likely a Vue internals bug. Please open an issue at https://github.com/vuejs/core ." +}; +function callWithErrorHandling(fn, instance, type, args) { + try { + return args ? fn(...args) : fn(); + } catch (err) { + handleError(err, instance, type); + } +} +function callWithAsyncErrorHandling(fn, instance, type, args) { + if (isFunction(fn)) { + const res = callWithErrorHandling(fn, instance, type, args); + if (res && isPromise(res)) { + res.catch((err) => { + handleError(err, instance, type); + }); + } + return res; + } + const values = []; + for (let i = 0; i < fn.length; i++) { + values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); + } + return values; +} +function handleError(err, instance, type, throwInDev = true) { + const contextVNode = instance ? instance.vnode : null; + if (instance) { + let cur = instance.parent; + const exposedInstance = instance.proxy; + const errorInfo = true ? ErrorTypeStrings$1[type] : `https://vuejs.org/error-reference/#runtime-${type}`; + while (cur) { + const errorCapturedHooks = cur.ec; + if (errorCapturedHooks) { + for (let i = 0; i < errorCapturedHooks.length; i++) { + if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) { + return; + } + } + } + cur = cur.parent; + } + const appErrorHandler = instance.appContext.config.errorHandler; + if (appErrorHandler) { + callWithErrorHandling( + appErrorHandler, + null, + 10, + [err, exposedInstance, errorInfo] + ); + return; + } + } + logError(err, type, contextVNode, throwInDev); +} +function logError(err, type, contextVNode, throwInDev = true) { + if (true) { + const info = ErrorTypeStrings$1[type]; + if (contextVNode) { + pushWarningContext(contextVNode); + } + warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`); + if (contextVNode) { + popWarningContext(); + } + if (throwInDev) { + throw err; + } else { + console.error(err); + } + } else { + console.error(err); + } +} +var isFlushing = false; +var isFlushPending = false; +var queue = []; +var flushIndex = 0; +var pendingPostFlushCbs = []; +var activePostFlushCbs = null; +var postFlushIndex = 0; +var resolvedPromise = Promise.resolve(); +var currentFlushPromise = null; +var RECURSION_LIMIT = 100; +function nextTick(fn) { + const p2 = currentFlushPromise || resolvedPromise; + return fn ? p2.then(this ? fn.bind(this) : fn) : p2; +} +function findInsertionIndex(id) { + let start = flushIndex + 1; + let end = queue.length; + while (start < end) { + const middle = start + end >>> 1; + const middleJob = queue[middle]; + const middleJobId = getId(middleJob); + if (middleJobId < id || middleJobId === id && middleJob.pre) { + start = middle + 1; + } else { + end = middle; + } + } + return start; +} +function queueJob(job) { + if (!queue.length || !queue.includes( + job, + isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex + )) { + if (job.id == null) { + queue.push(job); + } else { + queue.splice(findInsertionIndex(job.id), 0, job); + } + queueFlush(); + } +} +function queueFlush() { + if (!isFlushing && !isFlushPending) { + isFlushPending = true; + currentFlushPromise = resolvedPromise.then(flushJobs); + } +} +function invalidateJob(job) { + const i = queue.indexOf(job); + if (i > flushIndex) { + queue.splice(i, 1); + } +} +function queuePostFlushCb(cb) { + if (!isArray(cb)) { + if (!activePostFlushCbs || !activePostFlushCbs.includes( + cb, + cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex + )) { + pendingPostFlushCbs.push(cb); + } + } else { + pendingPostFlushCbs.push(...cb); + } + queueFlush(); +} +function flushPreFlushCbs(instance, seen, i = isFlushing ? flushIndex + 1 : 0) { + if (true) { + seen = seen || /* @__PURE__ */ new Map(); + } + for (; i < queue.length; i++) { + const cb = queue[i]; + if (cb && cb.pre) { + if (instance && cb.id !== instance.uid) { + continue; + } + if (checkRecursiveUpdates(seen, cb)) { + continue; + } + queue.splice(i, 1); + i--; + cb(); + } + } +} +function flushPostFlushCbs(seen) { + if (pendingPostFlushCbs.length) { + const deduped = [...new Set(pendingPostFlushCbs)].sort( + (a, b) => getId(a) - getId(b) + ); + pendingPostFlushCbs.length = 0; + if (activePostFlushCbs) { + activePostFlushCbs.push(...deduped); + return; + } + activePostFlushCbs = deduped; + if (true) { + seen = seen || /* @__PURE__ */ new Map(); + } + for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { + if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) { + continue; + } + activePostFlushCbs[postFlushIndex](); + } + activePostFlushCbs = null; + postFlushIndex = 0; + } +} +var getId = (job) => job.id == null ? Infinity : job.id; +var comparator = (a, b) => { + const diff = getId(a) - getId(b); + if (diff === 0) { + if (a.pre && !b.pre) + return -1; + if (b.pre && !a.pre) + return 1; + } + return diff; +}; +function flushJobs(seen) { + isFlushPending = false; + isFlushing = true; + if (true) { + seen = seen || /* @__PURE__ */ new Map(); + } + queue.sort(comparator); + const check = true ? (job) => checkRecursiveUpdates(seen, job) : NOOP; + try { + for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { + const job = queue[flushIndex]; + if (job && job.active !== false) { + if (check(job)) { + continue; + } + callWithErrorHandling(job, null, 14); + } + } + } finally { + flushIndex = 0; + queue.length = 0; + flushPostFlushCbs(seen); + isFlushing = false; + currentFlushPromise = null; + if (queue.length || pendingPostFlushCbs.length) { + flushJobs(seen); + } + } +} +function checkRecursiveUpdates(seen, fn) { + if (!seen.has(fn)) { + seen.set(fn, 1); + } else { + const count = seen.get(fn); + if (count > RECURSION_LIMIT) { + const instance = fn.ownerInstance; + const componentName = instance && getComponentName(instance.type); + handleError( + `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`, + null, + 10 + ); + return true; + } else { + seen.set(fn, count + 1); + } + } +} +var isHmrUpdating = false; +var hmrDirtyComponents = /* @__PURE__ */ new Set(); +if (true) { + getGlobalThis().__VUE_HMR_RUNTIME__ = { + createRecord: tryWrap(createRecord), + rerender: tryWrap(rerender), + reload: tryWrap(reload) + }; +} +var map = /* @__PURE__ */ new Map(); +function registerHMR(instance) { + const id = instance.type.__hmrId; + let record = map.get(id); + if (!record) { + createRecord(id, instance.type); + record = map.get(id); + } + record.instances.add(instance); +} +function unregisterHMR(instance) { + map.get(instance.type.__hmrId).instances.delete(instance); +} +function createRecord(id, initialDef) { + if (map.has(id)) { + return false; + } + map.set(id, { + initialDef: normalizeClassComponent(initialDef), + instances: /* @__PURE__ */ new Set() + }); + return true; +} +function normalizeClassComponent(component) { + return isClassComponent(component) ? component.__vccOpts : component; +} +function rerender(id, newRender) { + const record = map.get(id); + if (!record) { + return; + } + record.initialDef.render = newRender; + [...record.instances].forEach((instance) => { + if (newRender) { + instance.render = newRender; + normalizeClassComponent(instance.type).render = newRender; + } + instance.renderCache = []; + isHmrUpdating = true; + instance.effect.dirty = true; + instance.update(); + isHmrUpdating = false; + }); +} +function reload(id, newComp) { + const record = map.get(id); + if (!record) + return; + newComp = normalizeClassComponent(newComp); + updateComponentDef(record.initialDef, newComp); + const instances = [...record.instances]; + for (const instance of instances) { + const oldComp = normalizeClassComponent(instance.type); + if (!hmrDirtyComponents.has(oldComp)) { + if (oldComp !== record.initialDef) { + updateComponentDef(oldComp, newComp); + } + hmrDirtyComponents.add(oldComp); + } + instance.appContext.propsCache.delete(instance.type); + instance.appContext.emitsCache.delete(instance.type); + instance.appContext.optionsCache.delete(instance.type); + if (instance.ceReload) { + hmrDirtyComponents.add(oldComp); + instance.ceReload(newComp.styles); + hmrDirtyComponents.delete(oldComp); + } else if (instance.parent) { + instance.parent.effect.dirty = true; + queueJob(instance.parent.update); + } else if (instance.appContext.reload) { + instance.appContext.reload(); + } else if (typeof window !== "undefined") { + window.location.reload(); + } else { + console.warn( + "[HMR] Root or manually mounted instance modified. Full reload required." + ); + } + } + queuePostFlushCb(() => { + for (const instance of instances) { + hmrDirtyComponents.delete( + normalizeClassComponent(instance.type) + ); + } + }); +} +function updateComponentDef(oldComp, newComp) { + extend(oldComp, newComp); + for (const key in oldComp) { + if (key !== "__file" && !(key in newComp)) { + delete oldComp[key]; + } + } +} +function tryWrap(fn) { + return (id, arg) => { + try { + return fn(id, arg); + } catch (e) { + console.error(e); + console.warn( + `[HMR] Something went wrong during Vue component hot-reload. Full reload required.` + ); + } + }; +} +var devtools$1; +var buffer = []; +var devtoolsNotInstalled = false; +function emit$1(event, ...args) { + if (devtools$1) { + devtools$1.emit(event, ...args); + } else if (!devtoolsNotInstalled) { + buffer.push({ event, args }); + } +} +function setDevtoolsHook$1(hook, target) { + var _a, _b; + devtools$1 = hook; + if (devtools$1) { + devtools$1.enabled = true; + buffer.forEach(({ event, args }) => devtools$1.emit(event, ...args)); + buffer = []; + } else if (typeof window !== "undefined" && window.HTMLElement && !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.includes("jsdom"))) { + const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; + replay.push((newHook) => { + setDevtoolsHook$1(newHook, target); + }); + setTimeout(() => { + if (!devtools$1) { + target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null; + devtoolsNotInstalled = true; + buffer = []; + } + }, 3e3); + } else { + devtoolsNotInstalled = true; + buffer = []; + } +} +function devtoolsInitApp(app, version2) { + emit$1("app:init", app, version2, { + Fragment, + Text, + Comment, + Static + }); +} +function devtoolsUnmountApp(app) { + emit$1("app:unmount", app); +} +var devtoolsComponentAdded = createDevtoolsComponentHook( + "component:added" +); +var devtoolsComponentUpdated = createDevtoolsComponentHook("component:updated"); +var _devtoolsComponentRemoved = createDevtoolsComponentHook( + "component:removed" +); +var devtoolsComponentRemoved = (component) => { + if (devtools$1 && typeof devtools$1.cleanupBuffer === "function" && !devtools$1.cleanupBuffer(component)) { + _devtoolsComponentRemoved(component); + } +}; +function createDevtoolsComponentHook(hook) { + return (component) => { + emit$1( + hook, + component.appContext.app, + component.uid, + component.parent ? component.parent.uid : void 0, + component + ); + }; +} +var devtoolsPerfStart = createDevtoolsPerformanceHook( + "perf:start" +); +var devtoolsPerfEnd = createDevtoolsPerformanceHook( + "perf:end" +); +function createDevtoolsPerformanceHook(hook) { + return (component, type, time) => { + emit$1(hook, component.appContext.app, component.uid, component, type, time); + }; +} +function devtoolsComponentEmit(component, event, params) { + emit$1( + "component:emit", + component.appContext.app, + component, + event, + params + ); +} +function emit(instance, event, ...rawArgs) { + if (instance.isUnmounted) + return; + const props = instance.vnode.props || EMPTY_OBJ; + if (true) { + const { + emitsOptions, + propsOptions: [propsOptions] + } = instance; + if (emitsOptions) { + if (!(event in emitsOptions) && true) { + if (!propsOptions || !(toHandlerKey(event) in propsOptions)) { + warn$1( + `Component emitted event "${event}" but it is neither declared in the emits option nor as an "${toHandlerKey(event)}" prop.` + ); + } + } else { + const validator = emitsOptions[event]; + if (isFunction(validator)) { + const isValid = validator(...rawArgs); + if (!isValid) { + warn$1( + `Invalid event arguments: event validation failed for event "${event}".` + ); + } + } + } + } + } + let args = rawArgs; + const isModelListener2 = event.startsWith("update:"); + const modelArg = isModelListener2 && event.slice(7); + if (modelArg && modelArg in props) { + const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`; + const { number, trim } = props[modifiersKey] || EMPTY_OBJ; + if (trim) { + args = rawArgs.map((a) => isString(a) ? a.trim() : a); + } + if (number) { + args = rawArgs.map(looseToNumber); + } + } + if (true) { + devtoolsComponentEmit(instance, event, args); + } + if (true) { + const lowerCaseEvent = event.toLowerCase(); + if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) { + warn$1( + `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName( + instance, + instance.type + )} but the handler is registered for "${event}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${hyphenate( + event + )}" instead of "${event}".` + ); + } + } + let handlerName; + let handler = props[handlerName = toHandlerKey(event)] || props[handlerName = toHandlerKey(camelize(event))]; + if (!handler && isModelListener2) { + handler = props[handlerName = toHandlerKey(hyphenate(event))]; + } + if (handler) { + callWithAsyncErrorHandling( + handler, + instance, + 6, + args + ); + } + const onceHandler = props[handlerName + `Once`]; + if (onceHandler) { + if (!instance.emitted) { + instance.emitted = {}; + } else if (instance.emitted[handlerName]) { + return; + } + instance.emitted[handlerName] = true; + callWithAsyncErrorHandling( + onceHandler, + instance, + 6, + args + ); + } +} +function normalizeEmitsOptions(comp, appContext, asMixin = false) { + const cache = appContext.emitsCache; + const cached = cache.get(comp); + if (cached !== void 0) { + return cached; + } + const raw = comp.emits; + let normalized = {}; + let hasExtends = false; + if (__VUE_OPTIONS_API__ && !isFunction(comp)) { + const extendEmits = (raw2) => { + const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); + if (normalizedFromExtend) { + hasExtends = true; + extend(normalized, normalizedFromExtend); + } + }; + if (!asMixin && appContext.mixins.length) { + appContext.mixins.forEach(extendEmits); + } + if (comp.extends) { + extendEmits(comp.extends); + } + if (comp.mixins) { + comp.mixins.forEach(extendEmits); + } + } + if (!raw && !hasExtends) { + if (isObject(comp)) { + cache.set(comp, null); + } + return null; + } + if (isArray(raw)) { + raw.forEach((key) => normalized[key] = null); + } else { + extend(normalized, raw); + } + if (isObject(comp)) { + cache.set(comp, normalized); + } + return normalized; +} +function isEmitListener(options, key) { + if (!options || !isOn(key)) { + return false; + } + key = key.slice(2).replace(/Once$/, ""); + return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key); +} +var currentRenderingInstance = null; +var currentScopeId = null; +function setCurrentRenderingInstance(instance) { + const prev = currentRenderingInstance; + currentRenderingInstance = instance; + currentScopeId = instance && instance.type.__scopeId || null; + return prev; +} +function pushScopeId(id) { + currentScopeId = id; +} +function popScopeId() { + currentScopeId = null; +} +var withScopeId = (_id) => withCtx; +function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { + if (!ctx) + return fn; + if (fn._n) { + return fn; + } + const renderFnWithContext = (...args) => { + if (renderFnWithContext._d) { + setBlockTracking(-1); + } + const prevInstance = setCurrentRenderingInstance(ctx); + let res; + try { + res = fn(...args); + } finally { + setCurrentRenderingInstance(prevInstance); + if (renderFnWithContext._d) { + setBlockTracking(1); + } + } + if (true) { + devtoolsComponentUpdated(ctx); + } + return res; + }; + renderFnWithContext._n = true; + renderFnWithContext._c = true; + renderFnWithContext._d = true; + return renderFnWithContext; +} +var accessedAttrs = false; +function markAttrsAccessed() { + accessedAttrs = true; +} +function renderComponentRoot(instance) { + const { + type: Component, + vnode, + proxy, + withProxy, + props, + propsOptions: [propsOptions], + slots, + attrs, + emit: emit2, + render: render2, + renderCache, + data, + setupState, + ctx, + inheritAttrs + } = instance; + let result; + let fallthroughAttrs; + const prev = setCurrentRenderingInstance(instance); + if (true) { + accessedAttrs = false; + } + try { + if (vnode.shapeFlag & 4) { + const proxyToUse = withProxy || proxy; + const thisProxy = setupState.__isScriptSetup ? new Proxy(proxyToUse, { + get(target, key, receiver) { + warn$1( + `Property '${String( + key + )}' was accessed via 'this'. Avoid using 'this' in templates.` + ); + return Reflect.get(target, key, receiver); + } + }) : proxyToUse; + result = normalizeVNode( + render2.call( + thisProxy, + proxyToUse, + renderCache, + props, + setupState, + data, + ctx + ) + ); + fallthroughAttrs = attrs; + } else { + const render22 = Component; + if (attrs === props) { + markAttrsAccessed(); + } + result = normalizeVNode( + render22.length > 1 ? render22( + props, + true ? { + get attrs() { + markAttrsAccessed(); + return attrs; + }, + slots, + emit: emit2 + } : { attrs, slots, emit: emit2 } + ) : render22( + props, + null + ) + ); + fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs); + } + } catch (err) { + blockStack.length = 0; + handleError(err, instance, 1); + result = createVNode(Comment); + } + let root = result; + let setRoot = void 0; + if (result.patchFlag > 0 && result.patchFlag & 2048) { + [root, setRoot] = getChildRoot(result); + } + if (fallthroughAttrs && inheritAttrs !== false) { + const keys = Object.keys(fallthroughAttrs); + const { shapeFlag } = root; + if (keys.length) { + if (shapeFlag & (1 | 6)) { + if (propsOptions && keys.some(isModelListener)) { + fallthroughAttrs = filterModelListeners( + fallthroughAttrs, + propsOptions + ); + } + root = cloneVNode(root, fallthroughAttrs); + } else if (!accessedAttrs && root.type !== Comment) { + const allAttrs = Object.keys(attrs); + const eventAttrs = []; + const extraAttrs = []; + for (let i = 0, l = allAttrs.length; i < l; i++) { + const key = allAttrs[i]; + if (isOn(key)) { + if (!isModelListener(key)) { + eventAttrs.push(key[2].toLowerCase() + key.slice(3)); + } + } else { + extraAttrs.push(key); + } + } + if (extraAttrs.length) { + warn$1( + `Extraneous non-props attributes (${extraAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.` + ); + } + if (eventAttrs.length) { + warn$1( + `Extraneous non-emits event listeners (${eventAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.` + ); + } + } + } + } + if (vnode.dirs) { + if (!isElementRoot(root)) { + warn$1( + `Runtime directive used on component with non-element root node. The directives will not function as intended.` + ); + } + root = cloneVNode(root); + root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs; + } + if (vnode.transition) { + if (!isElementRoot(root)) { + warn$1( + `Component inside renders non-element root node that cannot be animated.` + ); + } + root.transition = vnode.transition; + } + if (setRoot) { + setRoot(root); + } else { + result = root; + } + setCurrentRenderingInstance(prev); + return result; +} +var getChildRoot = (vnode) => { + const rawChildren = vnode.children; + const dynamicChildren = vnode.dynamicChildren; + const childRoot = filterSingleRoot(rawChildren, false); + if (!childRoot) { + return [vnode, void 0]; + } else if (childRoot.patchFlag > 0 && childRoot.patchFlag & 2048) { + return getChildRoot(childRoot); + } + const index = rawChildren.indexOf(childRoot); + const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; + const setRoot = (updatedRoot) => { + rawChildren[index] = updatedRoot; + if (dynamicChildren) { + if (dynamicIndex > -1) { + dynamicChildren[dynamicIndex] = updatedRoot; + } else if (updatedRoot.patchFlag > 0) { + vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; + } + } + }; + return [normalizeVNode(childRoot), setRoot]; +}; +function filterSingleRoot(children, recurse = true) { + let singleRoot; + for (let i = 0; i < children.length; i++) { + const child = children[i]; + if (isVNode(child)) { + if (child.type !== Comment || child.children === "v-if") { + if (singleRoot) { + return; + } else { + singleRoot = child; + if (recurse && singleRoot.patchFlag > 0 && singleRoot.patchFlag & 2048) { + return filterSingleRoot(singleRoot.children); + } + } + } + } else { + return; + } + } + return singleRoot; +} +var getFunctionalFallthrough = (attrs) => { + let res; + for (const key in attrs) { + if (key === "class" || key === "style" || isOn(key)) { + (res || (res = {}))[key] = attrs[key]; + } + } + return res; +}; +var filterModelListeners = (attrs, props) => { + const res = {}; + for (const key in attrs) { + if (!isModelListener(key) || !(key.slice(9) in props)) { + res[key] = attrs[key]; + } + } + return res; +}; +var isElementRoot = (vnode) => { + return vnode.shapeFlag & (6 | 1) || vnode.type === Comment; +}; +function shouldUpdateComponent(prevVNode, nextVNode, optimized) { + const { props: prevProps, children: prevChildren, component } = prevVNode; + const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; + const emits = component.emitsOptions; + if ((prevChildren || nextChildren) && isHmrUpdating) { + return true; + } + if (nextVNode.dirs || nextVNode.transition) { + return true; + } + if (optimized && patchFlag >= 0) { + if (patchFlag & 1024) { + return true; + } + if (patchFlag & 16) { + if (!prevProps) { + return !!nextProps; + } + return hasPropsChanged(prevProps, nextProps, emits); + } else if (patchFlag & 8) { + const dynamicProps = nextVNode.dynamicProps; + for (let i = 0; i < dynamicProps.length; i++) { + const key = dynamicProps[i]; + if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) { + return true; + } + } + } + } else { + if (prevChildren || nextChildren) { + if (!nextChildren || !nextChildren.$stable) { + return true; + } + } + if (prevProps === nextProps) { + return false; + } + if (!prevProps) { + return !!nextProps; + } + if (!nextProps) { + return true; + } + return hasPropsChanged(prevProps, nextProps, emits); + } + return false; +} +function hasPropsChanged(prevProps, nextProps, emitsOptions) { + const nextKeys = Object.keys(nextProps); + if (nextKeys.length !== Object.keys(prevProps).length) { + return true; + } + for (let i = 0; i < nextKeys.length; i++) { + const key = nextKeys[i]; + if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) { + return true; + } + } + return false; +} +function updateHOCHostEl({ vnode, parent }, el) { + while (parent) { + const root = parent.subTree; + if (root.suspense && root.suspense.activeBranch === vnode) { + root.el = vnode.el; + } + if (root === vnode) { + (vnode = parent.vnode).el = el; + parent = parent.parent; + } else { + break; + } + } +} +var COMPONENTS = "components"; +var DIRECTIVES = "directives"; +function resolveComponent(name, maybeSelfReference) { + return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; +} +var NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc"); +function resolveDynamicComponent(component) { + if (isString(component)) { + return resolveAsset(COMPONENTS, component, false) || component; + } else { + return component || NULL_DYNAMIC_COMPONENT; + } +} +function resolveDirective(name) { + return resolveAsset(DIRECTIVES, name); +} +function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { + const instance = currentRenderingInstance || currentInstance; + if (instance) { + const Component = instance.type; + if (type === COMPONENTS) { + const selfName = getComponentName( + Component, + false + ); + if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) { + return Component; + } + } + const res = resolve(instance[type] || Component[type], name) || resolve(instance.appContext[type], name); + if (!res && maybeSelfReference) { + return Component; + } + if (warnMissing && !res) { + const extra = type === COMPONENTS ? ` +If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; + warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); + } + return res; + } else if (true) { + warn$1( + `resolve${capitalize(type.slice(0, -1))} can only be used in render() or setup().` + ); + } +} +function resolve(registry, name) { + return registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))]); +} +var isSuspense = (type) => type.__isSuspense; +var suspenseId = 0; +var SuspenseImpl = { + name: "Suspense", + __isSuspense: true, + process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { + if (n1 == null) { + mountSuspense( + n2, + container, + anchor, + parentComponent, + parentSuspense, + namespace, + slotScopeIds, + optimized, + rendererInternals + ); + } else { + if (parentSuspense && parentSuspense.deps > 0) { + n2.suspense = n1.suspense; + n2.suspense.vnode = n2; + n2.el = n1.el; + return; + } + patchSuspense( + n1, + n2, + container, + anchor, + parentComponent, + namespace, + slotScopeIds, + optimized, + rendererInternals + ); + } + }, + hydrate: hydrateSuspense, + create: createSuspenseBoundary, + normalize: normalizeSuspenseChildren +}; +var Suspense = SuspenseImpl; +function triggerEvent(vnode, name) { + const eventListener = vnode.props && vnode.props[name]; + if (isFunction(eventListener)) { + eventListener(); + } +} +function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { + const { + p: patch, + o: { createElement } + } = rendererInternals; + const hiddenContainer = createElement("div"); + const suspense = vnode.suspense = createSuspenseBoundary( + vnode, + parentSuspense, + parentComponent, + container, + hiddenContainer, + anchor, + namespace, + slotScopeIds, + optimized, + rendererInternals + ); + patch( + null, + suspense.pendingBranch = vnode.ssContent, + hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds + ); + if (suspense.deps > 0) { + triggerEvent(vnode, "onPending"); + triggerEvent(vnode, "onFallback"); + patch( + null, + vnode.ssFallback, + container, + anchor, + parentComponent, + null, + namespace, + slotScopeIds + ); + setActiveBranch(suspense, vnode.ssFallback); + } else { + suspense.resolve(false, true); + } +} +function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) { + const suspense = n2.suspense = n1.suspense; + suspense.vnode = n2; + n2.el = n1.el; + const newBranch = n2.ssContent; + const newFallback = n2.ssFallback; + const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; + if (pendingBranch) { + suspense.pendingBranch = newBranch; + if (isSameVNodeType(newBranch, pendingBranch)) { + patch( + pendingBranch, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } else if (isInFallback) { + if (!isHydrating) { + patch( + activeBranch, + newFallback, + container, + anchor, + parentComponent, + null, + namespace, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, newFallback); + } + } + } else { + suspense.pendingId = suspenseId++; + if (isHydrating) { + suspense.isHydrating = false; + suspense.activeBranch = pendingBranch; + } else { + unmount(pendingBranch, parentComponent, suspense); + } + suspense.deps = 0; + suspense.effects.length = 0; + suspense.hiddenContainer = createElement("div"); + if (isInFallback) { + patch( + null, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } else { + patch( + activeBranch, + newFallback, + container, + anchor, + parentComponent, + null, + namespace, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, newFallback); + } + } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { + patch( + activeBranch, + newBranch, + container, + anchor, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + suspense.resolve(true); + } else { + patch( + null, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } + } + } + } else { + if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { + patch( + activeBranch, + newBranch, + container, + anchor, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, newBranch); + } else { + triggerEvent(n2, "onPending"); + suspense.pendingBranch = newBranch; + if (newBranch.shapeFlag & 512) { + suspense.pendingId = newBranch.component.suspenseId; + } else { + suspense.pendingId = suspenseId++; + } + patch( + null, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } else { + const { timeout, pendingId } = suspense; + if (timeout > 0) { + setTimeout(() => { + if (suspense.pendingId === pendingId) { + suspense.fallback(newFallback); + } + }, timeout); + } else if (timeout === 0) { + suspense.fallback(newFallback); + } + } + } + } +} +var hasWarned = false; +function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) { + if (!hasWarned) { + hasWarned = true; + console[console.info ? "info" : "log"]( + ` is an experimental feature and its API will likely change.` + ); + } + const { + p: patch, + m: move, + um: unmount, + n: next, + o: { parentNode, remove: remove2 } + } = rendererInternals; + let parentSuspenseId; + const isSuspensible = isVNodeSuspensible(vnode); + if (isSuspensible) { + if (parentSuspense == null ? void 0 : parentSuspense.pendingBranch) { + parentSuspenseId = parentSuspense.pendingId; + parentSuspense.deps++; + } + } + const timeout = vnode.props ? toNumber(vnode.props.timeout) : void 0; + if (true) { + assertNumber(timeout, `Suspense timeout`); + } + const initialAnchor = anchor; + const suspense = { + vnode, + parent: parentSuspense, + parentComponent, + namespace, + container, + hiddenContainer, + deps: 0, + pendingId: suspenseId++, + timeout: typeof timeout === "number" ? timeout : -1, + activeBranch: null, + pendingBranch: null, + isInFallback: !isHydrating, + isHydrating, + isUnmounted: false, + effects: [], + resolve(resume = false, sync = false) { + if (true) { + if (!resume && !suspense.pendingBranch) { + throw new Error( + `suspense.resolve() is called without a pending branch.` + ); + } + if (suspense.isUnmounted) { + throw new Error( + `suspense.resolve() is called on an already unmounted suspense boundary.` + ); + } + } + const { + vnode: vnode2, + activeBranch, + pendingBranch, + pendingId, + effects, + parentComponent: parentComponent2, + container: container2 + } = suspense; + let delayEnter = false; + if (suspense.isHydrating) { + suspense.isHydrating = false; + } else if (!resume) { + delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; + if (delayEnter) { + activeBranch.transition.afterLeave = () => { + if (pendingId === suspense.pendingId) { + move( + pendingBranch, + container2, + anchor === initialAnchor ? next(activeBranch) : anchor, + 0 + ); + queuePostFlushCb(effects); + } + }; + } + if (activeBranch) { + if (parentNode(activeBranch.el) !== suspense.hiddenContainer) { + anchor = next(activeBranch); + } + unmount(activeBranch, parentComponent2, suspense, true); + } + if (!delayEnter) { + move(pendingBranch, container2, anchor, 0); + } + } + setActiveBranch(suspense, pendingBranch); + suspense.pendingBranch = null; + suspense.isInFallback = false; + let parent = suspense.parent; + let hasUnresolvedAncestor = false; + while (parent) { + if (parent.pendingBranch) { + parent.effects.push(...effects); + hasUnresolvedAncestor = true; + break; + } + parent = parent.parent; + } + if (!hasUnresolvedAncestor && !delayEnter) { + queuePostFlushCb(effects); + } + suspense.effects = []; + if (isSuspensible) { + if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { + parentSuspense.deps--; + if (parentSuspense.deps === 0 && !sync) { + parentSuspense.resolve(); + } + } + } + triggerEvent(vnode2, "onResolve"); + }, + fallback(fallbackVNode) { + if (!suspense.pendingBranch) { + return; + } + const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense; + triggerEvent(vnode2, "onFallback"); + const anchor2 = next(activeBranch); + const mountFallback = () => { + if (!suspense.isInFallback) { + return; + } + patch( + null, + fallbackVNode, + container2, + anchor2, + parentComponent2, + null, + namespace2, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, fallbackVNode); + }; + const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; + if (delayEnter) { + activeBranch.transition.afterLeave = mountFallback; + } + suspense.isInFallback = true; + unmount( + activeBranch, + parentComponent2, + null, + true + ); + if (!delayEnter) { + mountFallback(); + } + }, + move(container2, anchor2, type) { + suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); + suspense.container = container2; + }, + next() { + return suspense.activeBranch && next(suspense.activeBranch); + }, + registerDep(instance, setupRenderEffect) { + const isInPendingSuspense = !!suspense.pendingBranch; + if (isInPendingSuspense) { + suspense.deps++; + } + const hydratedEl = instance.vnode.el; + instance.asyncDep.catch((err) => { + handleError(err, instance, 0); + }).then((asyncSetupResult) => { + if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { + return; + } + instance.asyncResolved = true; + const { vnode: vnode2 } = instance; + if (true) { + pushWarningContext(vnode2); + } + handleSetupResult(instance, asyncSetupResult, false); + if (hydratedEl) { + vnode2.el = hydratedEl; + } + const placeholder = !hydratedEl && instance.subTree.el; + setupRenderEffect( + instance, + vnode2, + parentNode(hydratedEl || instance.subTree.el), + hydratedEl ? null : next(instance.subTree), + suspense, + namespace, + optimized + ); + if (placeholder) { + remove2(placeholder); + } + updateHOCHostEl(instance, vnode2.el); + if (true) { + popWarningContext(); + } + if (isInPendingSuspense && --suspense.deps === 0) { + suspense.resolve(); + } + }); + }, + unmount(parentSuspense2, doRemove) { + suspense.isUnmounted = true; + if (suspense.activeBranch) { + unmount( + suspense.activeBranch, + parentComponent, + parentSuspense2, + doRemove + ); + } + if (suspense.pendingBranch) { + unmount( + suspense.pendingBranch, + parentComponent, + parentSuspense2, + doRemove + ); + } + } + }; + return suspense; +} +function hydrateSuspense(node, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) { + const suspense = vnode.suspense = createSuspenseBoundary( + vnode, + parentSuspense, + parentComponent, + node.parentNode, + document.createElement("div"), + null, + namespace, + slotScopeIds, + optimized, + rendererInternals, + true + ); + const result = hydrateNode( + node, + suspense.pendingBranch = vnode.ssContent, + parentComponent, + suspense, + slotScopeIds, + optimized + ); + if (suspense.deps === 0) { + suspense.resolve(false, true); + } + return result; +} +function normalizeSuspenseChildren(vnode) { + const { shapeFlag, children } = vnode; + const isSlotChildren = shapeFlag & 32; + vnode.ssContent = normalizeSuspenseSlot( + isSlotChildren ? children.default : children + ); + vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); +} +function normalizeSuspenseSlot(s) { + let block; + if (isFunction(s)) { + const trackBlock = isBlockTreeEnabled && s._c; + if (trackBlock) { + s._d = false; + openBlock(); + } + s = s(); + if (trackBlock) { + s._d = true; + block = currentBlock; + closeBlock(); + } + } + if (isArray(s)) { + const singleChild = filterSingleRoot(s); + if (!singleChild && s.filter((child) => child !== NULL_DYNAMIC_COMPONENT).length > 0) { + warn$1(` slots expect a single root node.`); + } + s = singleChild; + } + s = normalizeVNode(s); + if (block && !s.dynamicChildren) { + s.dynamicChildren = block.filter((c) => c !== s); + } + return s; +} +function queueEffectWithSuspense(fn, suspense) { + if (suspense && suspense.pendingBranch) { + if (isArray(fn)) { + suspense.effects.push(...fn); + } else { + suspense.effects.push(fn); + } + } else { + queuePostFlushCb(fn); + } +} +function setActiveBranch(suspense, branch) { + suspense.activeBranch = branch; + const { vnode, parentComponent } = suspense; + let el = branch.el; + while (!el && branch.component) { + branch = branch.component.subTree; + el = branch.el; + } + vnode.el = el; + if (parentComponent && parentComponent.subTree === vnode) { + parentComponent.vnode.el = el; + updateHOCHostEl(parentComponent, el); + } +} +function isVNodeSuspensible(vnode) { + var _a; + return ((_a = vnode.props) == null ? void 0 : _a.suspensible) != null && vnode.props.suspensible !== false; +} +var ssrContextKey = Symbol.for("v-scx"); +var useSSRContext = () => { + { + const ctx = inject(ssrContextKey); + if (!ctx) { + warn$1( + `Server rendering context not provided. Make sure to only call useSSRContext() conditionally in the server build.` + ); + } + return ctx; + } +}; +function watchEffect(effect2, options) { + return doWatch(effect2, null, options); +} +function watchPostEffect(effect2, options) { + return doWatch( + effect2, + null, + true ? extend({}, options, { flush: "post" }) : { flush: "post" } + ); +} +function watchSyncEffect(effect2, options) { + return doWatch( + effect2, + null, + true ? extend({}, options, { flush: "sync" }) : { flush: "sync" } + ); +} +var INITIAL_WATCHER_VALUE = {}; +function watch(source, cb, options) { + if (!isFunction(cb)) { + warn$1( + `\`watch(fn, options?)\` signature has been moved to a separate API. Use \`watchEffect(fn, options?)\` instead. \`watch\` now only supports \`watch(source, cb, options?) signature.` + ); + } + return doWatch(source, cb, options); +} +function doWatch(source, cb, { + immediate, + deep, + flush, + once, + onTrack, + onTrigger +} = EMPTY_OBJ) { + if (cb && once) { + const _cb = cb; + cb = (...args) => { + _cb(...args); + unwatch(); + }; + } + if (deep !== void 0 && typeof deep === "number") { + warn$1( + `watch() "deep" option with number value will be used as watch depth in future versions. Please use a boolean instead to avoid potential breakage.` + ); + } + if (!cb) { + if (immediate !== void 0) { + warn$1( + `watch() "immediate" option is only respected when using the watch(source, callback, options?) signature.` + ); + } + if (deep !== void 0) { + warn$1( + `watch() "deep" option is only respected when using the watch(source, callback, options?) signature.` + ); + } + if (once !== void 0) { + warn$1( + `watch() "once" option is only respected when using the watch(source, callback, options?) signature.` + ); + } + } + const warnInvalidSource = (s) => { + warn$1( + `Invalid watch source: `, + s, + `A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.` + ); + }; + const instance = currentInstance; + const reactiveGetter = (source2) => deep === true ? source2 : traverse(source2, deep === false ? 1 : void 0); + let getter; + let forceTrigger = false; + let isMultiSource = false; + if (isRef(source)) { + getter = () => source.value; + forceTrigger = isShallow(source); + } else if (isReactive(source)) { + getter = () => reactiveGetter(source); + forceTrigger = true; + } else if (isArray(source)) { + isMultiSource = true; + forceTrigger = source.some((s) => isReactive(s) || isShallow(s)); + getter = () => source.map((s) => { + if (isRef(s)) { + return s.value; + } else if (isReactive(s)) { + return reactiveGetter(s); + } else if (isFunction(s)) { + return callWithErrorHandling(s, instance, 2); + } else { + warnInvalidSource(s); + } + }); + } else if (isFunction(source)) { + if (cb) { + getter = () => callWithErrorHandling(source, instance, 2); + } else { + getter = () => { + if (cleanup) { + cleanup(); + } + return callWithAsyncErrorHandling( + source, + instance, + 3, + [onCleanup] + ); + }; + } + } else { + getter = NOOP; + warnInvalidSource(source); + } + if (cb && deep) { + const baseGetter = getter; + getter = () => traverse(baseGetter()); + } + let cleanup; + let onCleanup = (fn) => { + cleanup = effect2.onStop = () => { + callWithErrorHandling(fn, instance, 4); + cleanup = effect2.onStop = void 0; + }; + }; + let ssrCleanup; + if (isInSSRComponentSetup) { + onCleanup = NOOP; + if (!cb) { + getter(); + } else if (immediate) { + callWithAsyncErrorHandling(cb, instance, 3, [ + getter(), + isMultiSource ? [] : void 0, + onCleanup + ]); + } + if (flush === "sync") { + const ctx = useSSRContext(); + ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []); + } else { + return NOOP; + } + } + let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; + const job = () => { + if (!effect2.active || !effect2.dirty) { + return; + } + if (cb) { + const newValue = effect2.run(); + if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue)) || false) { + if (cleanup) { + cleanup(); + } + callWithAsyncErrorHandling(cb, instance, 3, [ + newValue, + oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, + onCleanup + ]); + oldValue = newValue; + } + } else { + effect2.run(); + } + }; + job.allowRecurse = !!cb; + let scheduler; + if (flush === "sync") { + scheduler = job; + } else if (flush === "post") { + scheduler = () => queuePostRenderEffect(job, instance && instance.suspense); + } else { + job.pre = true; + if (instance) + job.id = instance.uid; + scheduler = () => queueJob(job); + } + const effect2 = new ReactiveEffect(getter, NOOP, scheduler); + const scope = getCurrentScope(); + const unwatch = () => { + effect2.stop(); + if (scope) { + remove(scope.effects, effect2); + } + }; + if (true) { + effect2.onTrack = onTrack; + effect2.onTrigger = onTrigger; + } + if (cb) { + if (immediate) { + job(); + } else { + oldValue = effect2.run(); + } + } else if (flush === "post") { + queuePostRenderEffect( + effect2.run.bind(effect2), + instance && instance.suspense + ); + } else { + effect2.run(); + } + if (ssrCleanup) + ssrCleanup.push(unwatch); + return unwatch; +} +function instanceWatch(source, value, options) { + const publicThis = this.proxy; + const getter = isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); + let cb; + if (isFunction(value)) { + cb = value; + } else { + cb = value.handler; + options = value; + } + const reset = setCurrentInstance(this); + const res = doWatch(getter, cb.bind(publicThis), options); + reset(); + return res; +} +function createPathGetter(ctx, path) { + const segments = path.split("."); + return () => { + let cur = ctx; + for (let i = 0; i < segments.length && cur; i++) { + cur = cur[segments[i]]; + } + return cur; + }; +} +function traverse(value, depth, currentDepth = 0, seen) { + if (!isObject(value) || value["__v_skip"]) { + return value; + } + if (depth && depth > 0) { + if (currentDepth >= depth) { + return value; + } + currentDepth++; + } + seen = seen || /* @__PURE__ */ new Set(); + if (seen.has(value)) { + return value; + } + seen.add(value); + if (isRef(value)) { + traverse(value.value, depth, currentDepth, seen); + } else if (isArray(value)) { + for (let i = 0; i < value.length; i++) { + traverse(value[i], depth, currentDepth, seen); + } + } else if (isSet(value) || isMap(value)) { + value.forEach((v) => { + traverse(v, depth, currentDepth, seen); + }); + } else if (isPlainObject(value)) { + for (const key in value) { + traverse(value[key], depth, currentDepth, seen); + } + } + return value; +} +function validateDirectiveName(name) { + if (isBuiltInDirective(name)) { + warn$1("Do not use built-in directive ids as custom directive id: " + name); + } +} +function withDirectives(vnode, directives) { + if (currentRenderingInstance === null) { + warn$1(`withDirectives can only be used inside render functions.`); + return vnode; + } + const instance = getExposeProxy(currentRenderingInstance) || currentRenderingInstance.proxy; + const bindings = vnode.dirs || (vnode.dirs = []); + for (let i = 0; i < directives.length; i++) { + let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]; + if (dir) { + if (isFunction(dir)) { + dir = { + mounted: dir, + updated: dir + }; + } + if (dir.deep) { + traverse(value); + } + bindings.push({ + dir, + instance, + value, + oldValue: void 0, + arg, + modifiers + }); + } + } + return vnode; +} +function invokeDirectiveHook(vnode, prevVNode, instance, name) { + const bindings = vnode.dirs; + const oldBindings = prevVNode && prevVNode.dirs; + for (let i = 0; i < bindings.length; i++) { + const binding = bindings[i]; + if (oldBindings) { + binding.oldValue = oldBindings[i].value; + } + let hook = binding.dir[name]; + if (hook) { + pauseTracking(); + callWithAsyncErrorHandling(hook, instance, 8, [ + vnode.el, + binding, + vnode, + prevVNode + ]); + resetTracking(); + } + } +} +var leaveCbKey = Symbol("_leaveCb"); +var enterCbKey = Symbol("_enterCb"); +function useTransitionState() { + const state = { + isMounted: false, + isLeaving: false, + isUnmounting: false, + leavingVNodes: /* @__PURE__ */ new Map() + }; + onMounted(() => { + state.isMounted = true; + }); + onBeforeUnmount(() => { + state.isUnmounting = true; + }); + return state; +} +var TransitionHookValidator = [Function, Array]; +var BaseTransitionPropsValidators = { + mode: String, + appear: Boolean, + persisted: Boolean, + onBeforeEnter: TransitionHookValidator, + onEnter: TransitionHookValidator, + onAfterEnter: TransitionHookValidator, + onEnterCancelled: TransitionHookValidator, + onBeforeLeave: TransitionHookValidator, + onLeave: TransitionHookValidator, + onAfterLeave: TransitionHookValidator, + onLeaveCancelled: TransitionHookValidator, + onBeforeAppear: TransitionHookValidator, + onAppear: TransitionHookValidator, + onAfterAppear: TransitionHookValidator, + onAppearCancelled: TransitionHookValidator +}; +var BaseTransitionImpl = { + name: `BaseTransition`, + props: BaseTransitionPropsValidators, + setup(props, { slots }) { + const instance = getCurrentInstance(); + const state = useTransitionState(); + return () => { + const children = slots.default && getTransitionRawChildren(slots.default(), true); + if (!children || !children.length) { + return; + } + let child = children[0]; + if (children.length > 1) { + let hasFound = false; + for (const c of children) { + if (c.type !== Comment) { + if (hasFound) { + warn$1( + " can only be used on a single element or component. Use for lists." + ); + break; + } + child = c; + hasFound = true; + if (false) + break; + } + } + } + const rawProps = toRaw(props); + const { mode } = rawProps; + if (mode && mode !== "in-out" && mode !== "out-in" && mode !== "default") { + warn$1(`invalid mode: ${mode}`); + } + if (state.isLeaving) { + return emptyPlaceholder(child); + } + const innerChild = getKeepAliveChild(child); + if (!innerChild) { + return emptyPlaceholder(child); + } + const enterHooks = resolveTransitionHooks( + innerChild, + rawProps, + state, + instance + ); + setTransitionHooks(innerChild, enterHooks); + const oldChild = instance.subTree; + const oldInnerChild = oldChild && getKeepAliveChild(oldChild); + if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(innerChild, oldInnerChild)) { + const leavingHooks = resolveTransitionHooks( + oldInnerChild, + rawProps, + state, + instance + ); + setTransitionHooks(oldInnerChild, leavingHooks); + if (mode === "out-in") { + state.isLeaving = true; + leavingHooks.afterLeave = () => { + state.isLeaving = false; + if (instance.update.active !== false) { + instance.effect.dirty = true; + instance.update(); + } + }; + return emptyPlaceholder(child); + } else if (mode === "in-out" && innerChild.type !== Comment) { + leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => { + const leavingVNodesCache = getLeavingNodesForType( + state, + oldInnerChild + ); + leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild; + el[leaveCbKey] = () => { + earlyRemove(); + el[leaveCbKey] = void 0; + delete enterHooks.delayedLeave; + }; + enterHooks.delayedLeave = delayedLeave; + }; + } + } + return child; + }; + } +}; +var BaseTransition = BaseTransitionImpl; +function getLeavingNodesForType(state, vnode) { + const { leavingVNodes } = state; + let leavingVNodesCache = leavingVNodes.get(vnode.type); + if (!leavingVNodesCache) { + leavingVNodesCache = /* @__PURE__ */ Object.create(null); + leavingVNodes.set(vnode.type, leavingVNodesCache); + } + return leavingVNodesCache; +} +function resolveTransitionHooks(vnode, props, state, instance) { + const { + appear, + mode, + persisted = false, + onBeforeEnter, + onEnter, + onAfterEnter, + onEnterCancelled, + onBeforeLeave, + onLeave, + onAfterLeave, + onLeaveCancelled, + onBeforeAppear, + onAppear, + onAfterAppear, + onAppearCancelled + } = props; + const key = String(vnode.key); + const leavingVNodesCache = getLeavingNodesForType(state, vnode); + const callHook3 = (hook, args) => { + hook && callWithAsyncErrorHandling( + hook, + instance, + 9, + args + ); + }; + const callAsyncHook = (hook, args) => { + const done = args[1]; + callHook3(hook, args); + if (isArray(hook)) { + if (hook.every((hook2) => hook2.length <= 1)) + done(); + } else if (hook.length <= 1) { + done(); + } + }; + const hooks = { + mode, + persisted, + beforeEnter(el) { + let hook = onBeforeEnter; + if (!state.isMounted) { + if (appear) { + hook = onBeforeAppear || onBeforeEnter; + } else { + return; + } + } + if (el[leaveCbKey]) { + el[leaveCbKey]( + true + ); + } + const leavingVNode = leavingVNodesCache[key]; + if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el[leaveCbKey]) { + leavingVNode.el[leaveCbKey](); + } + callHook3(hook, [el]); + }, + enter(el) { + let hook = onEnter; + let afterHook = onAfterEnter; + let cancelHook = onEnterCancelled; + if (!state.isMounted) { + if (appear) { + hook = onAppear || onEnter; + afterHook = onAfterAppear || onAfterEnter; + cancelHook = onAppearCancelled || onEnterCancelled; + } else { + return; + } + } + let called = false; + const done = el[enterCbKey] = (cancelled) => { + if (called) + return; + called = true; + if (cancelled) { + callHook3(cancelHook, [el]); + } else { + callHook3(afterHook, [el]); + } + if (hooks.delayedLeave) { + hooks.delayedLeave(); + } + el[enterCbKey] = void 0; + }; + if (hook) { + callAsyncHook(hook, [el, done]); + } else { + done(); + } + }, + leave(el, remove2) { + const key2 = String(vnode.key); + if (el[enterCbKey]) { + el[enterCbKey]( + true + ); + } + if (state.isUnmounting) { + return remove2(); + } + callHook3(onBeforeLeave, [el]); + let called = false; + const done = el[leaveCbKey] = (cancelled) => { + if (called) + return; + called = true; + remove2(); + if (cancelled) { + callHook3(onLeaveCancelled, [el]); + } else { + callHook3(onAfterLeave, [el]); + } + el[leaveCbKey] = void 0; + if (leavingVNodesCache[key2] === vnode) { + delete leavingVNodesCache[key2]; + } + }; + leavingVNodesCache[key2] = vnode; + if (onLeave) { + callAsyncHook(onLeave, [el, done]); + } else { + done(); + } + }, + clone(vnode2) { + return resolveTransitionHooks(vnode2, props, state, instance); + } + }; + return hooks; +} +function emptyPlaceholder(vnode) { + if (isKeepAlive(vnode)) { + vnode = cloneVNode(vnode); + vnode.children = null; + return vnode; + } +} +function getKeepAliveChild(vnode) { + return isKeepAlive(vnode) ? vnode.component ? vnode.component.subTree : vnode.children ? vnode.children[0] : void 0 : vnode; +} +function setTransitionHooks(vnode, hooks) { + if (vnode.shapeFlag & 6 && vnode.component) { + setTransitionHooks(vnode.component.subTree, hooks); + } else if (vnode.shapeFlag & 128) { + vnode.ssContent.transition = hooks.clone(vnode.ssContent); + vnode.ssFallback.transition = hooks.clone(vnode.ssFallback); + } else { + vnode.transition = hooks; + } +} +function getTransitionRawChildren(children, keepComment = false, parentKey) { + let ret = []; + let keyedFragmentCount = 0; + for (let i = 0; i < children.length; i++) { + let child = children[i]; + const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i); + if (child.type === Fragment) { + if (child.patchFlag & 128) + keyedFragmentCount++; + ret = ret.concat( + getTransitionRawChildren(child.children, keepComment, key) + ); + } else if (keepComment || child.type !== Comment) { + ret.push(key != null ? cloneVNode(child, { key }) : child); + } + } + if (keyedFragmentCount > 1) { + for (let i = 0; i < ret.length; i++) { + ret[i].patchFlag = -2; + } + } + return ret; +} +function defineComponent(options, extraOptions) { + return isFunction(options) ? (() => extend({ name: options.name }, extraOptions, { setup: options }))() : options; +} +var isAsyncWrapper = (i) => !!i.type.__asyncLoader; +function defineAsyncComponent(source) { + if (isFunction(source)) { + source = { loader: source }; + } + const { + loader, + loadingComponent, + errorComponent, + delay = 200, + timeout, + suspensible = true, + onError: userOnError + } = source; + let pendingRequest = null; + let resolvedComp; + let retries = 0; + const retry = () => { + retries++; + pendingRequest = null; + return load(); + }; + const load = () => { + let thisRequest; + return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { + err = err instanceof Error ? err : new Error(String(err)); + if (userOnError) { + return new Promise((resolve2, reject) => { + const userRetry = () => resolve2(retry()); + const userFail = () => reject(err); + userOnError(err, userRetry, userFail, retries + 1); + }); + } else { + throw err; + } + }).then((comp) => { + if (thisRequest !== pendingRequest && pendingRequest) { + return pendingRequest; + } + if (!comp) { + warn$1( + `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` + ); + } + if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { + comp = comp.default; + } + if (comp && !isObject(comp) && !isFunction(comp)) { + throw new Error(`Invalid async component load result: ${comp}`); + } + resolvedComp = comp; + return comp; + })); + }; + return defineComponent({ + name: "AsyncComponentWrapper", + __asyncLoader: load, + get __asyncResolved() { + return resolvedComp; + }, + setup() { + const instance = currentInstance; + if (resolvedComp) { + return () => createInnerComp(resolvedComp, instance); + } + const onError = (err) => { + pendingRequest = null; + handleError( + err, + instance, + 13, + !errorComponent + ); + }; + if (suspensible && instance.suspense || isInSSRComponentSetup) { + return load().then((comp) => { + return () => createInnerComp(comp, instance); + }).catch((err) => { + onError(err); + return () => errorComponent ? createVNode(errorComponent, { + error: err + }) : null; + }); + } + const loaded = ref(false); + const error = ref(); + const delayed = ref(!!delay); + if (delay) { + setTimeout(() => { + delayed.value = false; + }, delay); + } + if (timeout != null) { + setTimeout(() => { + if (!loaded.value && !error.value) { + const err = new Error( + `Async component timed out after ${timeout}ms.` + ); + onError(err); + error.value = err; + } + }, timeout); + } + load().then(() => { + loaded.value = true; + if (instance.parent && isKeepAlive(instance.parent.vnode)) { + instance.parent.effect.dirty = true; + queueJob(instance.parent.update); + } + }).catch((err) => { + onError(err); + error.value = err; + }); + return () => { + if (loaded.value && resolvedComp) { + return createInnerComp(resolvedComp, instance); + } else if (error.value && errorComponent) { + return createVNode(errorComponent, { + error: error.value + }); + } else if (loadingComponent && !delayed.value) { + return createVNode(loadingComponent); + } + }; + } + }); +} +function createInnerComp(comp, parent) { + const { ref: ref2, props, children, ce } = parent.vnode; + const vnode = createVNode(comp, props, children); + vnode.ref = ref2; + vnode.ce = ce; + delete parent.vnode.ce; + return vnode; +} +var isKeepAlive = (vnode) => vnode.type.__isKeepAlive; +var KeepAliveImpl = { + name: `KeepAlive`, + __isKeepAlive: true, + props: { + include: [String, RegExp, Array], + exclude: [String, RegExp, Array], + max: [String, Number] + }, + setup(props, { slots }) { + const instance = getCurrentInstance(); + const sharedContext = instance.ctx; + if (!sharedContext.renderer) { + return () => { + const children = slots.default && slots.default(); + return children && children.length === 1 ? children[0] : children; + }; + } + const cache = /* @__PURE__ */ new Map(); + const keys = /* @__PURE__ */ new Set(); + let current = null; + if (true) { + instance.__v_cache = cache; + } + const parentSuspense = instance.suspense; + const { + renderer: { + p: patch, + m: move, + um: _unmount, + o: { createElement } + } + } = sharedContext; + const storageContainer = createElement("div"); + sharedContext.activate = (vnode, container, anchor, namespace, optimized) => { + const instance2 = vnode.component; + move(vnode, container, anchor, 0, parentSuspense); + patch( + instance2.vnode, + vnode, + container, + anchor, + instance2, + parentSuspense, + namespace, + vnode.slotScopeIds, + optimized + ); + queuePostRenderEffect(() => { + instance2.isDeactivated = false; + if (instance2.a) { + invokeArrayFns(instance2.a); + } + const vnodeHook = vnode.props && vnode.props.onVnodeMounted; + if (vnodeHook) { + invokeVNodeHook(vnodeHook, instance2.parent, vnode); + } + }, parentSuspense); + if (true) { + devtoolsComponentAdded(instance2); + } + }; + sharedContext.deactivate = (vnode) => { + const instance2 = vnode.component; + move(vnode, storageContainer, null, 1, parentSuspense); + queuePostRenderEffect(() => { + if (instance2.da) { + invokeArrayFns(instance2.da); + } + const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted; + if (vnodeHook) { + invokeVNodeHook(vnodeHook, instance2.parent, vnode); + } + instance2.isDeactivated = true; + }, parentSuspense); + if (true) { + devtoolsComponentAdded(instance2); + } + }; + function unmount(vnode) { + resetShapeFlag(vnode); + _unmount(vnode, instance, parentSuspense, true); + } + function pruneCache(filter) { + cache.forEach((vnode, key) => { + const name = getComponentName(vnode.type); + if (name && (!filter || !filter(name))) { + pruneCacheEntry(key); + } + }); + } + function pruneCacheEntry(key) { + const cached = cache.get(key); + if (!current || !isSameVNodeType(cached, current)) { + unmount(cached); + } else if (current) { + resetShapeFlag(current); + } + cache.delete(key); + keys.delete(key); + } + watch( + () => [props.include, props.exclude], + ([include, exclude]) => { + include && pruneCache((name) => matches(include, name)); + exclude && pruneCache((name) => !matches(exclude, name)); + }, + { flush: "post", deep: true } + ); + let pendingCacheKey = null; + const cacheSubtree = () => { + if (pendingCacheKey != null) { + cache.set(pendingCacheKey, getInnerChild(instance.subTree)); + } + }; + onMounted(cacheSubtree); + onUpdated(cacheSubtree); + onBeforeUnmount(() => { + cache.forEach((cached) => { + const { subTree, suspense } = instance; + const vnode = getInnerChild(subTree); + if (cached.type === vnode.type && cached.key === vnode.key) { + resetShapeFlag(vnode); + const da = vnode.component.da; + da && queuePostRenderEffect(da, suspense); + return; + } + unmount(cached); + }); + }); + return () => { + pendingCacheKey = null; + if (!slots.default) { + return null; + } + const children = slots.default(); + const rawVNode = children[0]; + if (children.length > 1) { + if (true) { + warn$1(`KeepAlive should contain exactly one component child.`); + } + current = null; + return children; + } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) { + current = null; + return rawVNode; + } + let vnode = getInnerChild(rawVNode); + const comp = vnode.type; + const name = getComponentName( + isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp + ); + const { include, exclude, max } = props; + if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) { + current = vnode; + return rawVNode; + } + const key = vnode.key == null ? comp : vnode.key; + const cachedVNode = cache.get(key); + if (vnode.el) { + vnode = cloneVNode(vnode); + if (rawVNode.shapeFlag & 128) { + rawVNode.ssContent = vnode; + } + } + pendingCacheKey = key; + if (cachedVNode) { + vnode.el = cachedVNode.el; + vnode.component = cachedVNode.component; + if (vnode.transition) { + setTransitionHooks(vnode, vnode.transition); + } + vnode.shapeFlag |= 512; + keys.delete(key); + keys.add(key); + } else { + keys.add(key); + if (max && keys.size > parseInt(max, 10)) { + pruneCacheEntry(keys.values().next().value); + } + } + vnode.shapeFlag |= 256; + current = vnode; + return isSuspense(rawVNode.type) ? rawVNode : vnode; + }; + } +}; +var KeepAlive = KeepAliveImpl; +function matches(pattern, name) { + if (isArray(pattern)) { + return pattern.some((p2) => matches(p2, name)); + } else if (isString(pattern)) { + return pattern.split(",").includes(name); + } else if (isRegExp(pattern)) { + return pattern.test(name); + } + return false; +} +function onActivated(hook, target) { + registerKeepAliveHook(hook, "a", target); +} +function onDeactivated(hook, target) { + registerKeepAliveHook(hook, "da", target); +} +function registerKeepAliveHook(hook, type, target = currentInstance) { + const wrappedHook = hook.__wdc || (hook.__wdc = () => { + let current = target; + while (current) { + if (current.isDeactivated) { + return; + } + current = current.parent; + } + return hook(); + }); + injectHook(type, wrappedHook, target); + if (target) { + let current = target.parent; + while (current && current.parent) { + if (isKeepAlive(current.parent.vnode)) { + injectToKeepAliveRoot(wrappedHook, type, target, current); + } + current = current.parent; + } + } +} +function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { + const injected = injectHook( + type, + hook, + keepAliveRoot, + true + ); + onUnmounted(() => { + remove(keepAliveRoot[type], injected); + }, target); +} +function resetShapeFlag(vnode) { + vnode.shapeFlag &= ~256; + vnode.shapeFlag &= ~512; +} +function getInnerChild(vnode) { + return vnode.shapeFlag & 128 ? vnode.ssContent : vnode; +} +function injectHook(type, hook, target = currentInstance, prepend = false) { + if (target) { + const hooks = target[type] || (target[type] = []); + const wrappedHook = hook.__weh || (hook.__weh = (...args) => { + if (target.isUnmounted) { + return; + } + pauseTracking(); + const reset = setCurrentInstance(target); + const res = callWithAsyncErrorHandling(hook, target, type, args); + reset(); + resetTracking(); + return res; + }); + if (prepend) { + hooks.unshift(wrappedHook); + } else { + hooks.push(wrappedHook); + } + return wrappedHook; + } else if (true) { + const apiName = toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, "")); + warn$1( + `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` + ); + } +} +var createHook = (lifecycle) => (hook, target = currentInstance) => (!isInSSRComponentSetup || lifecycle === "sp") && injectHook(lifecycle, (...args) => hook(...args), target); +var onBeforeMount = createHook("bm"); +var onMounted = createHook("m"); +var onBeforeUpdate = createHook("bu"); +var onUpdated = createHook("u"); +var onBeforeUnmount = createHook("bum"); +var onUnmounted = createHook("um"); +var onServerPrefetch = createHook("sp"); +var onRenderTriggered = createHook( + "rtg" +); +var onRenderTracked = createHook( + "rtc" +); +function onErrorCaptured(hook, target = currentInstance) { + injectHook("ec", hook, target); +} +function renderList(source, renderItem, cache, index) { + let ret; + const cached = cache && cache[index]; + if (isArray(source) || isString(source)) { + ret = new Array(source.length); + for (let i = 0, l = source.length; i < l; i++) { + ret[i] = renderItem(source[i], i, void 0, cached && cached[i]); + } + } else if (typeof source === "number") { + if (!Number.isInteger(source)) { + warn$1(`The v-for range expect an integer value but got ${source}.`); + } + ret = new Array(source); + for (let i = 0; i < source; i++) { + ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]); + } + } else if (isObject(source)) { + if (source[Symbol.iterator]) { + ret = Array.from( + source, + (item, i) => renderItem(item, i, void 0, cached && cached[i]) + ); + } else { + const keys = Object.keys(source); + ret = new Array(keys.length); + for (let i = 0, l = keys.length; i < l; i++) { + const key = keys[i]; + ret[i] = renderItem(source[key], key, i, cached && cached[i]); + } + } + } else { + ret = []; + } + if (cache) { + cache[index] = ret; + } + return ret; +} +function createSlots(slots, dynamicSlots) { + for (let i = 0; i < dynamicSlots.length; i++) { + const slot = dynamicSlots[i]; + if (isArray(slot)) { + for (let j = 0; j < slot.length; j++) { + slots[slot[j].name] = slot[j].fn; + } + } else if (slot) { + slots[slot.name] = slot.key ? (...args) => { + const res = slot.fn(...args); + if (res) + res.key = slot.key; + return res; + } : slot.fn; + } + } + return slots; +} +function renderSlot(slots, name, props = {}, fallback, noSlotted) { + if (currentRenderingInstance.isCE || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.isCE) { + if (name !== "default") + props.name = name; + return createVNode("slot", props, fallback && fallback()); + } + let slot = slots[name]; + if (slot && slot.length > 1) { + warn$1( + `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.` + ); + slot = () => []; + } + if (slot && slot._c) { + slot._d = false; + } + openBlock(); + const validSlotContent = slot && ensureValidVNode(slot(props)); + const rendered = createBlock( + Fragment, + { + key: props.key || validSlotContent && validSlotContent.key || `_${name}` + }, + validSlotContent || (fallback ? fallback() : []), + validSlotContent && slots._ === 1 ? 64 : -2 + ); + if (!noSlotted && rendered.scopeId) { + rendered.slotScopeIds = [rendered.scopeId + "-s"]; + } + if (slot && slot._c) { + slot._d = true; + } + return rendered; +} +function ensureValidVNode(vnodes) { + return vnodes.some((child) => { + if (!isVNode(child)) + return true; + if (child.type === Comment) + return false; + if (child.type === Fragment && !ensureValidVNode(child.children)) + return false; + return true; + }) ? vnodes : null; +} +function toHandlers(obj, preserveCaseIfNecessary) { + const ret = {}; + if (!isObject(obj)) { + warn$1(`v-on with no argument expects an object value.`); + return ret; + } + for (const key in obj) { + ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key]; + } + return ret; +} +var getPublicInstance = (i) => { + if (!i) + return null; + if (isStatefulComponent(i)) + return getExposeProxy(i) || i.proxy; + return getPublicInstance(i.parent); +}; +var publicPropertiesMap = extend(/* @__PURE__ */ Object.create(null), { + $: (i) => i, + $el: (i) => i.vnode.el, + $data: (i) => i.data, + $props: (i) => true ? shallowReadonly(i.props) : i.props, + $attrs: (i) => true ? shallowReadonly(i.attrs) : i.attrs, + $slots: (i) => true ? shallowReadonly(i.slots) : i.slots, + $refs: (i) => true ? shallowReadonly(i.refs) : i.refs, + $parent: (i) => getPublicInstance(i.parent), + $root: (i) => getPublicInstance(i.root), + $emit: (i) => i.emit, + $options: (i) => __VUE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type, + $forceUpdate: (i) => i.f || (i.f = () => { + i.effect.dirty = true; + queueJob(i.update); + }), + $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), + $watch: (i) => __VUE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP +}); +var isReservedPrefix = (key) => key === "_" || key === "$"; +var hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key); +var PublicInstanceProxyHandlers = { + get({ _: instance }, key) { + const { ctx, setupState, data, props, accessCache, type, appContext } = instance; + if (key === "__isVue") { + return true; + } + let normalizedProps; + if (key[0] !== "$") { + const n = accessCache[key]; + if (n !== void 0) { + switch (n) { + case 1: + return setupState[key]; + case 2: + return data[key]; + case 4: + return ctx[key]; + case 3: + return props[key]; + } + } else if (hasSetupBinding(setupState, key)) { + accessCache[key] = 1; + return setupState[key]; + } else if (data !== EMPTY_OBJ && hasOwn(data, key)) { + accessCache[key] = 2; + return data[key]; + } else if ((normalizedProps = instance.propsOptions[0]) && hasOwn(normalizedProps, key)) { + accessCache[key] = 3; + return props[key]; + } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { + accessCache[key] = 4; + return ctx[key]; + } else if (!__VUE_OPTIONS_API__ || shouldCacheAccess) { + accessCache[key] = 0; + } + } + const publicGetter = publicPropertiesMap[key]; + let cssModule, globalProperties; + if (publicGetter) { + if (key === "$attrs") { + track(instance, "get", key); + markAttrsAccessed(); + } else if (key === "$slots") { + track(instance, "get", key); + } + return publicGetter(instance); + } else if ((cssModule = type.__cssModules) && (cssModule = cssModule[key])) { + return cssModule; + } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { + accessCache[key] = 4; + return ctx[key]; + } else if (globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key)) { + { + return globalProperties[key]; + } + } else if (currentRenderingInstance && (!isString(key) || key.indexOf("__v") !== 0)) { + if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) { + warn$1( + `Property ${JSON.stringify( + key + )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.` + ); + } else if (instance === currentRenderingInstance) { + warn$1( + `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.` + ); + } + } + }, + set({ _: instance }, key, value) { + const { data, setupState, ctx } = instance; + if (hasSetupBinding(setupState, key)) { + setupState[key] = value; + return true; + } else if (setupState.__isScriptSetup && hasOwn(setupState, key)) { + warn$1(`Cannot mutate + + +``` + +By default the following tag/attribute combinations are transformed, and can be configured using the `template.transformAssetUrls` option. + +```js +{ + video: ['src', 'poster'], + source: ['src'], + img: ['src'], + image: ['xlink:href', 'href'], + use: ['xlink:href', 'href'] +} +``` + +Note that only attribute values that are static strings are transformed. Otherwise, you'd need to import the asset manually, e.g. `import imgUrl from '../image.png'`. + +## Example for passing options to `vue/compiler-sfc`: + +```ts +import vue from '@vitejs/plugin-vue' + +export default { + plugins: [ + vue({ + template: { + compilerOptions: { + // ... + }, + transformAssetUrls: { + // ... + } + } + }) + ] +} +``` + +## Example for transforming custom blocks + +```ts +import vue from '@vitejs/plugin-vue' +import yaml from 'js-yaml' + +const vueI18nPlugin = { + name: 'vue-i18n', + transform(code, id) { + if (!/vue&type=i18n/.test(id)) { + return + } + if (/\.ya?ml$/.test(id)) { + code = JSON.stringify(yaml.load(code.trim())) + } + return `export default Comp => { + Comp.i18n = ${code} + }` + } +} + +export default { + plugins: [vue(), vueI18nPlugin] +} +``` + +## Using Vue SFCs as Custom Elements + +> Requires `vue@^3.2.0` & `@vitejs/plugin-vue@^1.4.0` + +Vue 3.2 introduces the `defineCustomElement` method, which works with SFCs. By default, ` diff --git a/web/client/src/assets/css/default.css b/web/client/src/assets/css/default.css new file mode 100644 index 0000000000000000000000000000000000000000..95e44581ba363b6e1fa6165e3ad41500b4d3cb29 --- /dev/null +++ b/web/client/src/assets/css/default.css @@ -0,0 +1,22 @@ +@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&family=Roboto:wght@400;700;900&display=swap"); + +:root { + --primary-color: #41b883; + --primary-color-rbg: 65, 184, 131; + --primary-color-text: #1e2d50; + --secondary-color: #34495e; + --font-family: "Poppins", sans-serif; + --vn-font-family: "Roboto", sans-serif; +} + +* { + font-family: var(--font-family); +} + +html { + scroll-behavior: smooth; +} + +.invisible { + visibility: hidden; +} diff --git a/web/client/src/assets/css/reset.css b/web/client/src/assets/css/reset.css new file mode 100644 index 0000000000000000000000000000000000000000..40bd69a775732600227128cee49eb64d18261c95 --- /dev/null +++ b/web/client/src/assets/css/reset.css @@ -0,0 +1,127 @@ +html, +body, +div, +span, +applet, +object, +iframe, +h1, +h2, +h3, +h4, +h5, +h6, +p, +blockquote, +pre, +a, +abbr, +acronym, +address, +big, +cite, +code, +del, +dfn, +em, +img, +ins, +kbd, +q, +s, +samp, +small, +strike, +strong, +sub, +sup, +tt, +var, +b, +u, +i, +center, +dl, +dt, +dd, +ol, +ul, +li, +fieldset, +form, +label, +legend, +table, +caption, +tbody, +tfoot, +thead, +tr, +th, +td, +article, +aside, +canvas, +details, +embed, +figure, +figcaption, +footer, +header, +hgroup, +menu, +nav, +output, +ruby, +section, +summary, +time, +mark, +audio, +video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section { + display: block; +} +body { + line-height: 1; +} +ol, +ul { + list-style: none; +} +blockquote, +q { + quotes: none; +} +blockquote:before, +blockquote:after, +q:before, +q:after { + content: ""; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +} +a { + text-decoration: none; +} diff --git a/web/client/src/assets/logo.svg b/web/client/src/assets/logo.svg new file mode 100644 index 0000000000000000000000000000000000000000..bc826fed80ad0c846e5ca25978776f555f4a2370 --- /dev/null +++ b/web/client/src/assets/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/web/client/src/components/Dropzone.vue b/web/client/src/components/Dropzone.vue new file mode 100644 index 0000000000000000000000000000000000000000..2ddec502e76806e279d511a9d5a5d3a034c92981 --- /dev/null +++ b/web/client/src/components/Dropzone.vue @@ -0,0 +1,133 @@ + + + + + diff --git a/web/client/src/components/DropzoneLoading.vue b/web/client/src/components/DropzoneLoading.vue new file mode 100644 index 0000000000000000000000000000000000000000..504b2ce368bdb65a2a14307dfd5a736e1f35901b --- /dev/null +++ b/web/client/src/components/DropzoneLoading.vue @@ -0,0 +1,76 @@ + + + + + diff --git a/web/client/src/components/Result.vue b/web/client/src/components/Result.vue new file mode 100644 index 0000000000000000000000000000000000000000..474749f9c6b5c7728ea22dc0c8c7b12964c9ec47 --- /dev/null +++ b/web/client/src/components/Result.vue @@ -0,0 +1,236 @@ + + + + + diff --git a/web/client/src/components/Video.vue b/web/client/src/components/Video.vue new file mode 100644 index 0000000000000000000000000000000000000000..5758354147e13812f6dfca147a9de5c9ff61e38a --- /dev/null +++ b/web/client/src/components/Video.vue @@ -0,0 +1,54 @@ + + + + + diff --git a/web/client/src/components/Webcam.vue b/web/client/src/components/Webcam.vue new file mode 100644 index 0000000000000000000000000000000000000000..c38ea69ebc519fa1fc9183a5e2225a977b5013dd --- /dev/null +++ b/web/client/src/components/Webcam.vue @@ -0,0 +1,73 @@ + + + + + diff --git a/web/client/src/main.js b/web/client/src/main.js new file mode 100644 index 0000000000000000000000000000000000000000..4598a24a3c3084ea7dad428dc07e470d94bda9f5 --- /dev/null +++ b/web/client/src/main.js @@ -0,0 +1,17 @@ +// Default CSS +import "./assets/css/default.css"; +import "./assets/css/reset.css"; + +// JS +import { createPinia } from "pinia"; +import { createApp } from "vue"; + +import App from "./App.vue"; +import router from "./router"; + +const app = createApp(App); + +app.use(createPinia()); +app.use(router); + +app.mount("#app"); diff --git a/web/client/src/router/index.js b/web/client/src/router/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2e49bc361146736ecf11ad31010b59d5135164fd --- /dev/null +++ b/web/client/src/router/index.js @@ -0,0 +1,23 @@ +import { createRouter, createWebHistory } from "vue-router"; + +const router = createRouter({ + history: createWebHistory(import.meta.env.BASE_URL), + routes: [ + { + path: "/", + name: "Home", + component: () => import("../views/Home.vue"), + }, + { + path: "/video", + name: "VideoStreaming", + component: () => import("../views/VideoStreaming.vue"), + }, + { + path: "/:pathMatch(.*)*", + redirect: { name: "Home" }, + }, + ], +}); + +export default router; diff --git a/web/client/src/views/Home.vue b/web/client/src/views/Home.vue new file mode 100644 index 0000000000000000000000000000000000000000..74bcd3c2916fd2779129c8255a1e254d8205d516 --- /dev/null +++ b/web/client/src/views/Home.vue @@ -0,0 +1,61 @@ + + + + + diff --git a/web/client/src/views/VideoStreaming.vue b/web/client/src/views/VideoStreaming.vue new file mode 100644 index 0000000000000000000000000000000000000000..3c96c180984ee5f84c27015297325b7707db1e19 --- /dev/null +++ b/web/client/src/views/VideoStreaming.vue @@ -0,0 +1,150 @@ + + + + + diff --git a/web/client/vite.config.js b/web/client/vite.config.js new file mode 100644 index 0000000000000000000000000000000000000000..f705a177ed49adb977717186d3af5a2db0fc6f7b --- /dev/null +++ b/web/client/vite.config.js @@ -0,0 +1,29 @@ +import { fileURLToPath, URL } from "node:url"; + +import vue from "@vitejs/plugin-vue"; +import { defineConfig } from "vite"; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [vue()], + resolve: { + alias: { + "@": fileURLToPath(new URL("./src", import.meta.url)), + }, + }, + build: { + rollupOptions: { + output: { + assetFileNames: (assetInfo) => { + let extType = assetInfo.name.split(".").at(1); + if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) { + extType = "img"; + } + return `static/${extType}/[name]-[hash][extname]`; + }, + chunkFileNames: "static/assets/js/[name]-[hash].js", + entryFileNames: "static/assets/js/[name]-[hash].js", + }, + }, + }, +}); diff --git a/web/node_modules/.bin/acorn b/web/node_modules/.bin/acorn new file mode 100644 index 0000000000000000000000000000000000000000..dd631458a838946ee9a6abdf9780cef062956553 --- /dev/null +++ b/web/node_modules/.bin/acorn @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:172abb5575ef74185417e36d1df7384fb27720826054f7337bdf26efc2649526 +size 379 diff --git a/web/node_modules/.bin/acorn.cmd b/web/node_modules/.bin/acorn.cmd new file mode 100644 index 0000000000000000000000000000000000000000..cee74429405188895d24e21a5ab86964bb474a93 --- /dev/null +++ b/web/node_modules/.bin/acorn.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d3aecbaf5fc581a03b5d6d0358566cfb3be6babda6e0cd72a1b7b9d6c8ee21f +size 320 diff --git a/web/node_modules/.bin/acorn.ps1 b/web/node_modules/.bin/acorn.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..e8e600e53f12b6a37936f84396fdbe205a4b6fa6 --- /dev/null +++ b/web/node_modules/.bin/acorn.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:264bfc66f8543c5adafaa0e1b01dcc93f94b9480377131c0127c541f53f865f2 +size 785 diff --git a/web/node_modules/.bin/esbuild b/web/node_modules/.bin/esbuild new file mode 100644 index 0000000000000000000000000000000000000000..81bbcfc94fa5ec8e93570e2a7e319e5dd22b12ed --- /dev/null +++ b/web/node_modules/.bin/esbuild @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:020b954fd13a2c5ee8aabd5a73e24c10a4750099ed5e02f07dc7265c6758a054 +size 387 diff --git a/web/node_modules/.bin/esbuild.cmd b/web/node_modules/.bin/esbuild.cmd new file mode 100644 index 0000000000000000000000000000000000000000..10fbb313b66ca832e8a17f7e57df17e4b2938e04 --- /dev/null +++ b/web/node_modules/.bin/esbuild.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b00afc3761267058834ab0968f58748f0422efe0eb0321540544770cafbf7a69 +size 324 diff --git a/web/node_modules/.bin/esbuild.ps1 b/web/node_modules/.bin/esbuild.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..0d52719c7a2679420b74600af4c58d5f67214b40 --- /dev/null +++ b/web/node_modules/.bin/esbuild.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a24efc13fb6ef9def6c5aaf7787e7203d0982e2ab8627b64a41eb033945b7f5 +size 801 diff --git a/web/node_modules/.bin/nanoid b/web/node_modules/.bin/nanoid new file mode 100644 index 0000000000000000000000000000000000000000..e65438e55959a5f84c70cf5404380fef6762b84f --- /dev/null +++ b/web/node_modules/.bin/nanoid @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49446fa7e9ea1b36b205bab243f2928f1230d8dbeb09881eef1d039149ad3238 +size 391 diff --git a/web/node_modules/.bin/nanoid.cmd b/web/node_modules/.bin/nanoid.cmd new file mode 100644 index 0000000000000000000000000000000000000000..88c8582050826e21543577bb6b14d30cccfc2213 --- /dev/null +++ b/web/node_modules/.bin/nanoid.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65f7afb9e8bf7fd4ff2087803c18e8818334768bfe92b9c1f28346050678c0ca +size 326 diff --git a/web/node_modules/.bin/nanoid.ps1 b/web/node_modules/.bin/nanoid.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..bd772037dbf077f81a431b4a2970b2e3e845211a --- /dev/null +++ b/web/node_modules/.bin/nanoid.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2b48c0422548661c689493b3249b16f93599ca15fc3af5e821f9e6bccbe2aad +size 809 diff --git a/web/node_modules/.bin/node-which b/web/node_modules/.bin/node-which new file mode 100644 index 0000000000000000000000000000000000000000..ebd592cb51347db03cb24472fe112d8ce4f03a29 --- /dev/null +++ b/web/node_modules/.bin/node-which @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae614137ec19cd41eab2f7a85cc508e6a19042b0dda0a2815c07e5fb43a6e059 +size 389 diff --git a/web/node_modules/.bin/node-which.cmd b/web/node_modules/.bin/node-which.cmd new file mode 100644 index 0000000000000000000000000000000000000000..6ea5f36a7a47215c9e8d6dc9d430ee2c27076c77 --- /dev/null +++ b/web/node_modules/.bin/node-which.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:818856453703b9e61de47223e7505ad77cb4f40f456e348dae2ca9cd501abad0 +size 325 diff --git a/web/node_modules/.bin/node-which.ps1 b/web/node_modules/.bin/node-which.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..98e5154312add05735d7bdb12ee1c362fc99f21a --- /dev/null +++ b/web/node_modules/.bin/node-which.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d293014f7b06fffc145f94cd02bd82b53c2dbbc3eba99ff62dedf882adcc1711 +size 805 diff --git a/web/node_modules/.bin/rollup b/web/node_modules/.bin/rollup new file mode 100644 index 0000000000000000000000000000000000000000..9913bb57a96cb107ec572676e7c2718ebc67c742 --- /dev/null +++ b/web/node_modules/.bin/rollup @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc55c2746b1a59c588127263b254384b08dd08de5b170c52796453f8a762b46 +size 393 diff --git a/web/node_modules/.bin/rollup.cmd b/web/node_modules/.bin/rollup.cmd new file mode 100644 index 0000000000000000000000000000000000000000..659848b7e66d44cb187416e8ebb9d059b0842c8e --- /dev/null +++ b/web/node_modules/.bin/rollup.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3a19226bedbf80c0cdfe75eeaadc21c74c7a58e04bff23a134f809f71ae2210 +size 327 diff --git a/web/node_modules/.bin/rollup.ps1 b/web/node_modules/.bin/rollup.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..12792954b8d43b125eba3b6021285dd788b85d7f --- /dev/null +++ b/web/node_modules/.bin/rollup.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:095ea547e7dba18c0f9679b21c8237d776916d61cc56967b34cef1cea7bc592b +size 813 diff --git a/web/node_modules/.bin/vite b/web/node_modules/.bin/vite new file mode 100644 index 0000000000000000000000000000000000000000..31aefb21ea2f2ea01a3bfda142013159cc2be0d9 --- /dev/null +++ b/web/node_modules/.bin/vite @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdf31cf5e7b6cbfa65c2111d4fec53a7484c038aeac028f3718ab565c171b7ed +size 381 diff --git a/web/node_modules/.bin/vite-node b/web/node_modules/.bin/vite-node new file mode 100644 index 0000000000000000000000000000000000000000..1b1096bbc1f46ef1a6356f53ff0d82396d763086 --- /dev/null +++ b/web/node_modules/.bin/vite-node @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:106e6c6baa78e82ee90a20b755f26e4383e97afd5bbec69737193d81ca7919cf +size 395 diff --git a/web/node_modules/.bin/vite-node.cmd b/web/node_modules/.bin/vite-node.cmd new file mode 100644 index 0000000000000000000000000000000000000000..b71a7189f892175034d2b5ee2956d20297bd6d0e --- /dev/null +++ b/web/node_modules/.bin/vite-node.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d42314f2c4662b7afb3634e36d4544655b11f168dce1e9449d501fd17da042a +size 328 diff --git a/web/node_modules/.bin/vite-node.ps1 b/web/node_modules/.bin/vite-node.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..f1df914c3ad23bae59e0aa172d306cbe5d6542b9 --- /dev/null +++ b/web/node_modules/.bin/vite-node.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d60030600cdcf00d09264901df3c1ef7e9e5f9a0f7cc35be6d4826ce2b7a551 +size 817 diff --git a/web/node_modules/.bin/vite.cmd b/web/node_modules/.bin/vite.cmd new file mode 100644 index 0000000000000000000000000000000000000000..5578d603594bd8fa47390f549db4c738c1464c57 --- /dev/null +++ b/web/node_modules/.bin/vite.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e865893c8f57ff153c66cf80aac687f436b457922d9585495becee81c927e910 +size 321 diff --git a/web/node_modules/.bin/vite.ps1 b/web/node_modules/.bin/vite.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..a28aa41bfadb3e6eb1c0d27c52300e7d8319c2d3 --- /dev/null +++ b/web/node_modules/.bin/vite.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb22a675c5bf414d459a8b07172d5cc073c7d51520bed1d7d6f1652e3fd1f3ea +size 789 diff --git a/web/node_modules/.bin/vitest b/web/node_modules/.bin/vitest new file mode 100644 index 0000000000000000000000000000000000000000..feb9deb6a1fbfb65a1adeb1c89d71736600db907 --- /dev/null +++ b/web/node_modules/.bin/vitest @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1bbe582a2450cca0708096f3fcc060280aa09d85b487dc3549201a64f6590a4 +size 383 diff --git a/web/node_modules/.bin/vitest.cmd b/web/node_modules/.bin/vitest.cmd new file mode 100644 index 0000000000000000000000000000000000000000..cd67fe119537d64c2cd0548f76b1133384df7d88 --- /dev/null +++ b/web/node_modules/.bin/vitest.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5959ce11885ed044bf1883d9a991d4db2a4690c255681d2e635991d34b393f1 +size 322 diff --git a/web/node_modules/.bin/vitest.ps1 b/web/node_modules/.bin/vitest.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..4133f4e5a2e9a9250b36207cb08ead72ee77311c --- /dev/null +++ b/web/node_modules/.bin/vitest.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b361a4204b5a5fc98974019e0f082389c835db3b6d0b78951e13728fcb830d07 +size 793 diff --git a/web/node_modules/.bin/why-is-node-running b/web/node_modules/.bin/why-is-node-running new file mode 100644 index 0000000000000000000000000000000000000000..74ba76b3210141a9ce6bd5b83f7444b61e1a93c7 --- /dev/null +++ b/web/node_modules/.bin/why-is-node-running @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b94f65f278f14f00b5a44d5c5295349a1c43ea0f682ea6b94bec33e35c0f3ab +size 401 diff --git a/web/node_modules/.bin/why-is-node-running.cmd b/web/node_modules/.bin/why-is-node-running.cmd new file mode 100644 index 0000000000000000000000000000000000000000..1b960bbd80b51376ad18a7087be9ad645957639b --- /dev/null +++ b/web/node_modules/.bin/why-is-node-running.cmd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dc2972e18708a1958d86869197d20c55362cdd091a8ecb79540785ea733af89 +size 331 diff --git a/web/node_modules/.bin/why-is-node-running.ps1 b/web/node_modules/.bin/why-is-node-running.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..02a025dc9028120c8cfc7ded790f56f5b494e2ce --- /dev/null +++ b/web/node_modules/.bin/why-is-node-running.ps1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f57cc87ebb8255239d8a067dfc0743f9b081b2c9c5f2ab53379e5e0299378b8 +size 829 diff --git a/web/node_modules/.package-lock.json b/web/node_modules/.package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..582956ea2c9550b480753520f45b8f38986bb9b6 --- /dev/null +++ b/web/node_modules/.package-lock.json @@ -0,0 +1,976 @@ +{ + "name": "web", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@esbuild/win32-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.12.tgz", + "integrity": "sha512-T1QyPSDCyMXaO3pzBkF96E8xMkiRYbUEZADd29SyPGabqxMViNoii+NcK7eWJAEoU6RZyEm5lVSIjTmcdoB9HA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.12.0.tgz", + "integrity": "sha512-ZYmr5mS2wd4Dew/JjT0Fqi2NPB/ZhZ2VvPp7SmvPZb4Y1CG/LRcS6tcRo2cYU7zLK5A7cdbhWnnWmUjoI4qapg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "dev": true + }, + "node_modules/@types/estree": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", + "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", + "dev": true + }, + "node_modules/@vitest/expect": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.3.1.tgz", + "integrity": "sha512-xofQFwIzfdmLLlHa6ag0dPV8YsnKOCP1KdAeVVh34vSjN2dcUiXYCD9htu/9eM7t8Xln4v03U9HLxLpPlsXdZw==", + "dev": true, + "dependencies": { + "@vitest/spy": "1.3.1", + "@vitest/utils": "1.3.1", + "chai": "^4.3.10" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-1.3.1.tgz", + "integrity": "sha512-5FzF9c3jG/z5bgCnjr8j9LNq/9OxV2uEBAITOXfoe3rdZJTdO7jzThth7FXv/6b+kdY65tpRQB7WaKhNZwX+Kg==", + "dev": true, + "dependencies": { + "@vitest/utils": "1.3.1", + "p-limit": "^5.0.0", + "pathe": "^1.1.1" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-1.3.1.tgz", + "integrity": "sha512-EF++BZbt6RZmOlE3SuTPu/NfwBF6q4ABS37HHXzs2LUVPBLx2QoY/K0fKpRChSo8eLiuxcbCVfqKgx/dplCDuQ==", + "dev": true, + "dependencies": { + "magic-string": "^0.30.5", + "pathe": "^1.1.1", + "pretty-format": "^29.7.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-1.3.1.tgz", + "integrity": "sha512-xAcW+S099ylC9VLU7eZfdT9myV67Nor9w9zhf0mGCYJSO+zM2839tOeROTdikOi/8Qeusffvxb/MyBSOja1Uig==", + "dev": true, + "dependencies": { + "tinyspy": "^2.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-1.3.1.tgz", + "integrity": "sha512-d3Waie/299qqRyHTm2DjADeTaNdNSVsnwHPWrs20JMpjh6eiVq7ggggweO8rc4arhf6rRkWuHKwvxGvejUXZZQ==", + "dev": true, + "dependencies": { + "diff-sequences": "^29.6.3", + "estree-walker": "^3.0.3", + "loupe": "^2.3.7", + "pretty-format": "^29.7.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz", + "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", + "integrity": "sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==", + "dev": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.0.8" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/esbuild": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.12.tgz", + "integrity": "sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.19.12", + "@esbuild/android-arm": "0.19.12", + "@esbuild/android-arm64": "0.19.12", + "@esbuild/android-x64": "0.19.12", + "@esbuild/darwin-arm64": "0.19.12", + "@esbuild/darwin-x64": "0.19.12", + "@esbuild/freebsd-arm64": "0.19.12", + "@esbuild/freebsd-x64": "0.19.12", + "@esbuild/linux-arm": "0.19.12", + "@esbuild/linux-arm64": "0.19.12", + "@esbuild/linux-ia32": "0.19.12", + "@esbuild/linux-loong64": "0.19.12", + "@esbuild/linux-mips64el": "0.19.12", + "@esbuild/linux-ppc64": "0.19.12", + "@esbuild/linux-riscv64": "0.19.12", + "@esbuild/linux-s390x": "0.19.12", + "@esbuild/linux-x64": "0.19.12", + "@esbuild/netbsd-x64": "0.19.12", + "@esbuild/openbsd-x64": "0.19.12", + "@esbuild/sunos-x64": "0.19.12", + "@esbuild/win32-arm64": "0.19.12", + "@esbuild/win32-ia32": "0.19.12", + "@esbuild/win32-x64": "0.19.12" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true, + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/js-tokens": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-8.0.3.tgz", + "integrity": "sha512-UfJMcSJc+SEXEl9lH/VLHSZbThQyLpw1vLO1Lb+j4RWDvG3N2f7yj3PVQA3cmkTBNldJ9eFnM+xEXxHIXrYiJw==", + "dev": true + }, + "node_modules/jsonc-parser": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.1.tgz", + "integrity": "sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA==", + "dev": true + }, + "node_modules/local-pkg": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.0.tgz", + "integrity": "sha512-ok6z3qlYyCDS4ZEU27HaU6x/xZa9Whf8jD4ptH5UZTQYZVYeb9bnZ3ojVhiJNLiXK1Hfc0GNbLXcmZ5plLDDBg==", + "dev": true, + "dependencies": { + "mlly": "^1.4.2", + "pkg-types": "^1.0.3" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/magic-string": { + "version": "0.30.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.7.tgz", + "integrity": "sha512-8vBuFF/I/+OSLRmdf2wwFCJCz+nSn0m6DPvGH1fS/KiQoSaR+sETbov0eIk9KhEKy8CYqIkIAnbohxT/4H0kuA==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mlly": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.6.1.tgz", + "integrity": "sha512-vLgaHvaeunuOXHSmEbZ9izxPx3USsk8KCQ8iC+aTlp5sKRSoZvwhHh5L9VbKSaVC6sJDqbyohIS76E2VmHIPAA==", + "dev": true, + "dependencies": { + "acorn": "^8.11.3", + "pathe": "^1.1.2", + "pkg-types": "^1.0.3", + "ufo": "^1.3.2" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/npm-run-path": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "dev": true, + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-5.0.0.tgz", + "integrity": "sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "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, + "engines": { + "node": ">=8" + } + }, + "node_modules/pathe": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", + "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==", + "dev": true + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "node_modules/pkg-types": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.3.tgz", + "integrity": "sha512-nN7pYi0AQqJnoLPC9eHFQ8AcyaixBUOwvqc5TDnIKCMEE6I0y8P7OKA7fPexsXGCGxQDl/cmrLAp26LhcwxZ4A==", + "dev": true, + "dependencies": { + "jsonc-parser": "^3.2.0", + "mlly": "^1.2.0", + "pathe": "^1.1.0" + } + }, + "node_modules/postcss": { + "version": "8.4.35", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.35.tgz", + "integrity": "sha512-u5U8qYpBCpN13BsiEB0CbR1Hhh4Gc0zLFuedrHJKMctHCHAGrMdG0PRM/KErzAL3CU6/eckEtmHNB3x6e3c0vA==", + "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" + } + ], + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true + }, + "node_modules/rollup": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.12.0.tgz", + "integrity": "sha512-wz66wn4t1OHIJw3+XU7mJJQV/2NAfw5OAk6G6Hoo3zcvz/XOfQ52Vgi+AN4Uxoxi0KBBwk2g8zPrTDA4btSB/Q==", + "dev": true, + "dependencies": { + "@types/estree": "1.0.5" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.12.0", + "@rollup/rollup-android-arm64": "4.12.0", + "@rollup/rollup-darwin-arm64": "4.12.0", + "@rollup/rollup-darwin-x64": "4.12.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.12.0", + "@rollup/rollup-linux-arm64-gnu": "4.12.0", + "@rollup/rollup-linux-arm64-musl": "4.12.0", + "@rollup/rollup-linux-riscv64-gnu": "4.12.0", + "@rollup/rollup-linux-x64-gnu": "4.12.0", + "@rollup/rollup-linux-x64-musl": "4.12.0", + "@rollup/rollup-win32-arm64-msvc": "4.12.0", + "@rollup/rollup-win32-ia32-msvc": "4.12.0", + "@rollup/rollup-win32-x64-msvc": "4.12.0", + "fsevents": "~2.3.2" + } + }, + "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, + "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, + "engines": { + "node": ">=8" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true + }, + "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, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true + }, + "node_modules/std-env": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.7.0.tgz", + "integrity": "sha512-JPbdCEQLj1w5GilpiHAx3qJvFndqybBysA3qUOnznweH4QbNYUsW/ea8QzSrnh0vNsezMMw5bcVool8lM0gwzg==", + "dev": true + }, + "node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-literal": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-2.0.0.tgz", + "integrity": "sha512-f9vHgsCWBq2ugHAkGMiiYY+AYG0D/cbloKKg0nhaaaSNsujdGIpVXCNsrJpCKr5M0f4aI31mr13UjY6GAuXCKA==", + "dev": true, + "dependencies": { + "js-tokens": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/tinybench": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.6.0.tgz", + "integrity": "sha512-N8hW3PG/3aOoZAN5V/NSAEDz0ZixDSSt5b/a05iqtpgfLWMSVuCo7w0k2vVvEjdrIoeGqZzweX2WlyioNIHchA==", + "dev": true + }, + "node_modules/tinypool": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.8.2.tgz", + "integrity": "sha512-SUszKYe5wgsxnNOVlBYO6IC+8VGWdVGZWAqUxp3UErNBtptZvWbwyUOyzNL59zigz2rCA92QiL3wvG+JDSdJdQ==", + "dev": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-2.2.1.tgz", + "integrity": "sha512-KYad6Vy5VDWV4GH3fjpseMQ/XU2BhIYP7Vzd0LG44qRWm/Yt2WCOTicFdvmgo6gWaqooMQCawTtILVQJupKu7A==", + "dev": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/ufo": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.4.0.tgz", + "integrity": "sha512-Hhy+BhRBleFjpJ2vchUNN40qgkh0366FWJGqVLYBHev0vpHTrXSA0ryT+74UiW6KWsldNurQMKGqCm1M2zBciQ==", + "dev": true + }, + "node_modules/vite": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.1.4.tgz", + "integrity": "sha512-n+MPqzq+d9nMVTKyewqw6kSt+R3CkvF9QAKY8obiQn8g1fwTscKxyfaYnC632HtBXAQGc1Yjomphwn1dtwGAHg==", + "dev": true, + "dependencies": { + "esbuild": "^0.19.3", + "postcss": "^8.4.35", + "rollup": "^4.2.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-1.3.1.tgz", + "integrity": "sha512-azbRrqRxlWTJEVbzInZCTchx0X69M/XPTCz4H+TLvlTcR/xH/3hkRqhOakT41fMJCMzXTu4UvegkZiEoJAWvng==", + "dev": true, + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "pathe": "^1.1.1", + "picocolors": "^1.0.0", + "vite": "^5.0.0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-1.3.1.tgz", + "integrity": "sha512-/1QJqXs8YbCrfv/GPQ05wAZf2eakUPLPa18vkJAKE7RXOKfVHqMZZ1WlTjiwl6Gcn65M5vpNUB6EFLnEdRdEXQ==", + "dev": true, + "dependencies": { + "@vitest/expect": "1.3.1", + "@vitest/runner": "1.3.1", + "@vitest/snapshot": "1.3.1", + "@vitest/spy": "1.3.1", + "@vitest/utils": "1.3.1", + "acorn-walk": "^8.3.2", + "chai": "^4.3.10", + "debug": "^4.3.4", + "execa": "^8.0.1", + "local-pkg": "^0.5.0", + "magic-string": "^0.30.5", + "pathe": "^1.1.1", + "picocolors": "^1.0.0", + "std-env": "^3.5.0", + "strip-literal": "^2.0.0", + "tinybench": "^2.5.1", + "tinypool": "^0.8.2", + "vite": "^5.0.0", + "vite-node": "1.3.1", + "why-is-node-running": "^2.2.2" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/node": "^18.0.0 || >=20.0.0", + "@vitest/browser": "1.3.1", + "@vitest/ui": "1.3.1", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "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, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.2.2.tgz", + "integrity": "sha512-6tSwToZxTOcotxHeA+qGCq1mVzKR3CwcJGmVcY+QE8SHy6TnpFnh8PAvPNHYr7EcuVeG0QSMxtYCuO1ta/G/oA==", + "dev": true, + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yocto-queue": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", + "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", + "dev": true, + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/web/node_modules/@esbuild/win32-x64/README.md b/web/node_modules/@esbuild/win32-x64/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a99ee7cf84e91677bc3c6100ac37a60fc8ec8fdb --- /dev/null +++ b/web/node_modules/@esbuild/win32-x64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/web/node_modules/@esbuild/win32-x64/esbuild.exe b/web/node_modules/@esbuild/win32-x64/esbuild.exe new file mode 100644 index 0000000000000000000000000000000000000000..b3dbe3207b2d3ee7dedc0e43d71f2d2d20a5b695 --- /dev/null +++ b/web/node_modules/@esbuild/win32-x64/esbuild.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c9b2c93322b4a6c86b3cd6d3bd6003ceb621e97ce31683fa18c310d0a542449 +size 9807360 diff --git a/web/node_modules/@esbuild/win32-x64/package.json b/web/node_modules/@esbuild/win32-x64/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e4aa5d86d12d3e236ba0bdf3cf02e05dd0dc70bc --- /dev/null +++ b/web/node_modules/@esbuild/win32-x64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@esbuild/win32-x64", + "version": "0.19.12", + "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.", + "repository": "https://github.com/evanw/esbuild", + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=12" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ] +} diff --git a/web/node_modules/@jest/schemas/LICENSE b/web/node_modules/@jest/schemas/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b93be90515ccd0b9daedaa589e42bf5929693f1f --- /dev/null +++ b/web/node_modules/@jest/schemas/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +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/web/node_modules/@jest/schemas/README.md b/web/node_modules/@jest/schemas/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b2a1d122925edc20525da1ea5c660cce4161f2ca --- /dev/null +++ b/web/node_modules/@jest/schemas/README.md @@ -0,0 +1,3 @@ +# `@jest/schemas` + +Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration. diff --git a/web/node_modules/@jest/schemas/build/index.d.ts b/web/node_modules/@jest/schemas/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..156f1978efd956532dd6c50f1ee64001daba1a51 --- /dev/null +++ b/web/node_modules/@jest/schemas/build/index.d.ts @@ -0,0 +1,63 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {Static} from '@sinclair/typebox'; +import {TBoolean} from '@sinclair/typebox'; +import {TNull} from '@sinclair/typebox'; +import {TNumber} from '@sinclair/typebox'; +import {TObject} from '@sinclair/typebox'; +import {TReadonlyOptional} from '@sinclair/typebox'; +import {TString} from '@sinclair/typebox'; + +declare const RawSnapshotFormat: TObject<{ + callToJSON: TReadonlyOptional; + compareKeys: TReadonlyOptional; + escapeRegex: TReadonlyOptional; + escapeString: TReadonlyOptional; + highlight: TReadonlyOptional; + indent: TReadonlyOptional; + maxDepth: TReadonlyOptional; + maxWidth: TReadonlyOptional; + min: TReadonlyOptional; + printBasicPrototype: TReadonlyOptional; + printFunctionName: TReadonlyOptional; + theme: TReadonlyOptional< + TObject<{ + comment: TReadonlyOptional>; + content: TReadonlyOptional>; + prop: TReadonlyOptional>; + tag: TReadonlyOptional>; + value: TReadonlyOptional>; + }> + >; +}>; + +export declare const SnapshotFormat: TObject<{ + callToJSON: TReadonlyOptional; + compareKeys: TReadonlyOptional; + escapeRegex: TReadonlyOptional; + escapeString: TReadonlyOptional; + highlight: TReadonlyOptional; + indent: TReadonlyOptional; + maxDepth: TReadonlyOptional; + maxWidth: TReadonlyOptional; + min: TReadonlyOptional; + printBasicPrototype: TReadonlyOptional; + printFunctionName: TReadonlyOptional; + theme: TReadonlyOptional< + TObject<{ + comment: TReadonlyOptional>; + content: TReadonlyOptional>; + prop: TReadonlyOptional>; + tag: TReadonlyOptional>; + value: TReadonlyOptional>; + }> + >; +}>; + +export declare type SnapshotFormat = Static; + +export {}; diff --git a/web/node_modules/@jest/schemas/build/index.js b/web/node_modules/@jest/schemas/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..870c184402412e424048671308fb3c486d108ade --- /dev/null +++ b/web/node_modules/@jest/schemas/build/index.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.SnapshotFormat = void 0; +function _typebox() { + const data = require('@sinclair/typebox'); + _typebox = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const RawSnapshotFormat = _typebox().Type.Partial( + _typebox().Type.Object({ + callToJSON: _typebox().Type.Readonly(_typebox().Type.Boolean()), + compareKeys: _typebox().Type.Readonly(_typebox().Type.Null()), + escapeRegex: _typebox().Type.Readonly(_typebox().Type.Boolean()), + escapeString: _typebox().Type.Readonly(_typebox().Type.Boolean()), + highlight: _typebox().Type.Readonly(_typebox().Type.Boolean()), + indent: _typebox().Type.Readonly( + _typebox().Type.Number({ + minimum: 0 + }) + ), + maxDepth: _typebox().Type.Readonly( + _typebox().Type.Number({ + minimum: 0 + }) + ), + maxWidth: _typebox().Type.Readonly( + _typebox().Type.Number({ + minimum: 0 + }) + ), + min: _typebox().Type.Readonly(_typebox().Type.Boolean()), + printBasicPrototype: _typebox().Type.Readonly(_typebox().Type.Boolean()), + printFunctionName: _typebox().Type.Readonly(_typebox().Type.Boolean()), + theme: _typebox().Type.Readonly( + _typebox().Type.Partial( + _typebox().Type.Object({ + comment: _typebox().Type.Readonly(_typebox().Type.String()), + content: _typebox().Type.Readonly(_typebox().Type.String()), + prop: _typebox().Type.Readonly(_typebox().Type.String()), + tag: _typebox().Type.Readonly(_typebox().Type.String()), + value: _typebox().Type.Readonly(_typebox().Type.String()) + }) + ) + ) + }) +); +const SnapshotFormat = _typebox().Type.Strict(RawSnapshotFormat); +exports.SnapshotFormat = SnapshotFormat; diff --git a/web/node_modules/@jest/schemas/package.json b/web/node_modules/@jest/schemas/package.json new file mode 100644 index 0000000000000000000000000000000000000000..db670bfa4466bac909834ca615dab54ed7928050 --- /dev/null +++ b/web/node_modules/@jest/schemas/package.json @@ -0,0 +1,29 @@ +{ + "name": "@jest/schemas", + "version": "29.6.3", + "repository": { + "type": "git", + "url": "https://github.com/jestjs/jest.git", + "directory": "packages/jest-schemas" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b" +} diff --git a/web/node_modules/@jridgewell/sourcemap-codec/LICENSE b/web/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a331065a46b90f36f82834a40086eca10d6979c5 --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/web/node_modules/@jridgewell/sourcemap-codec/README.md b/web/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbb31525a4a67c7e230d44324ee150e49dad8df --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,200 @@ +# @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 v18.0.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 5479160 bytes +sourcemap-codec 5659336 bytes +source-map-0.6.1 17144440 bytes +source-map-0.8.0 6867424 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 502 ops/sec ±1.03% (90 runs sampled) +decode: sourcemap-codec x 445 ops/sec ±0.97% (92 runs sampled) +decode: source-map-0.6.1 x 36.01 ops/sec ±1.64% (49 runs sampled) +decode: source-map-0.8.0 x 367 ops/sec ±0.04% (95 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 1261620 bytes +sourcemap-codec 9119248 bytes +source-map-0.6.1 8968560 bytes +source-map-0.8.0 8952952 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 738 ops/sec ±0.42% (98 runs sampled) +encode: sourcemap-codec x 238 ops/sec ±0.73% (88 runs sampled) +encode: source-map-0.6.1 x 162 ops/sec ±0.43% (84 runs sampled) +encode: source-map-0.8.0 x 191 ops/sec ±0.34% (90 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 35338184 bytes +sourcemap-codec 35922736 bytes +source-map-0.6.1 62366360 bytes +source-map-0.8.0 44337416 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 40.35 ops/sec ±4.47% (54 runs sampled) +decode: sourcemap-codec x 36.76 ops/sec ±3.67% (51 runs sampled) +decode: source-map-0.6.1 x 4.44 ops/sec ±2.15% (16 runs sampled) +decode: source-map-0.8.0 x 59.35 ops/sec ±0.05% (78 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +@jridgewell/sourcemap-codec 7212604 bytes +sourcemap-codec 21421456 bytes +source-map-0.6.1 25286888 bytes +source-map-0.8.0 25498744 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 112 ops/sec ±0.13% (84 runs sampled) +encode: sourcemap-codec x 30.23 ops/sec ±2.76% (53 runs sampled) +encode: source-map-0.6.1 x 19.43 ops/sec ±3.70% (37 runs sampled) +encode: source-map-0.8.0 x 19.40 ops/sec ±3.26% (37 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 500272 bytes +sourcemap-codec 516864 bytes +source-map-0.6.1 1596672 bytes +source-map-0.8.0 517272 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 16,137 ops/sec ±0.17% (99 runs sampled) +decode: sourcemap-codec x 12,139 ops/sec ±0.13% (99 runs sampled) +decode: source-map-0.6.1 x 1,264 ops/sec ±0.12% (100 runs sampled) +decode: source-map-0.8.0 x 9,894 ops/sec ±0.08% (101 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 321026 bytes +sourcemap-codec 830832 bytes +source-map-0.6.1 586608 bytes +source-map-0.8.0 586680 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 19,876 ops/sec ±0.78% (95 runs sampled) +encode: sourcemap-codec x 6,983 ops/sec ±0.15% (100 runs sampled) +encode: source-map-0.6.1 x 5,070 ops/sec ±0.12% (102 runs sampled) +encode: source-map-0.8.0 x 5,641 ops/sec ±0.17% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 734848 bytes +sourcemap-codec 954200 bytes +source-map-0.6.1 2276432 bytes +source-map-0.8.0 955488 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 5,723 ops/sec ±0.12% (98 runs sampled) +decode: sourcemap-codec x 4,555 ops/sec ±0.09% (101 runs sampled) +decode: source-map-0.6.1 x 437 ops/sec ±0.11% (93 runs sampled) +decode: source-map-0.8.0 x 3,441 ops/sec ±0.15% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 638672 bytes +sourcemap-codec 1109840 bytes +source-map-0.6.1 1321224 bytes +source-map-0.8.0 1324448 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 6,801 ops/sec ±0.48% (98 runs sampled) +encode: sourcemap-codec x 2,533 ops/sec ±0.13% (101 runs sampled) +encode: source-map-0.6.1 x 2,248 ops/sec ±0.08% (100 runs sampled) +encode: source-map-0.8.0 x 2,303 ops/sec ±0.15% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec +``` + +# License + +MIT diff --git a/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3dff372170b960b5d2cfd1af0cdc86f1a4fdbda0 --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +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; +} +// Provide a fallback for older environments. +const 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; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..236fd120afd5fbbcbdb65ff3dbc72d91e2ed0cca --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CAClB;AAED;AACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;sBACd,IAAI,WAAW,EAAE;MACjC,OAAO,MAAM,KAAK,WAAW;UAC7B;YACE,MAAM,CAAC,GAAe;gBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;gBACpE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;aACvB;SACF;UACD;YACE,MAAM,CAAC,GAAe;gBACpB,IAAI,GAAG,GAAG,EAAE,CAAC;gBACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;oBACnC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;iBACpC;gBACD,OAAO,GAAG,CAAC;aACZ;SACF,CAAC;SAEQ,MAAM,CAAC,QAAgB;IACrC,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;IACjF,MAAM,OAAO,GAAsB,EAAE,CAAC;IAEtC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,GAAG;QACD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QACtC,MAAM,IAAI,GAAkB,EAAE,CAAC;QAC/B,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,IAAI,OAAO,GAAG,CAAC,CAAC;QAChB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAEb,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;YACjC,IAAI,GAAqB,CAAC;YAE1B,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;YACzC,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YACrB,IAAI,GAAG,GAAG,OAAO;gBAAE,MAAM,GAAG,KAAK,CAAC;YAClC,OAAO,GAAG,GAAG,CAAC;YAEd,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;gBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBAEzC,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;oBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzC,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;iBACrD;qBAAM;oBACL,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;iBAC3C;aACF;iBAAM;gBACL,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;aACb;YAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAChB;QAED,IAAI,CAAC,MAAM;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACxB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnB,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC;KAClB,QAAQ,KAAK,IAAI,QAAQ,CAAC,MAAM,EAAE;IAEnC,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,OAAO,CAAC,QAAgB,EAAE,KAAa;IAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,GAAG,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;AAC5C,CAAC;AAED,SAAS,aAAa,CAAC,QAAgB,EAAE,GAAW,EAAE,KAAuB,EAAE,CAAS;IACtF,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,OAAO,GAAG,CAAC,CAAC;IAEhB,GAAG;QACD,MAAM,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC;QACrC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;QACvB,KAAK,IAAI,CAAC,OAAO,GAAG,EAAE,KAAK,KAAK,CAAC;QACjC,KAAK,IAAI,CAAC,CAAC;KACZ,QAAQ,OAAO,GAAG,EAAE,EAAE;IAEvB,MAAM,YAAY,GAAG,KAAK,GAAG,CAAC,CAAC;IAC/B,KAAK,MAAM,CAAC,CAAC;IAEb,IAAI,YAAY,EAAE;QAChB,KAAK,GAAG,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC;KAC9B;IAED,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;IAClB,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,QAAgB,EAAE,CAAS,EAAE,MAAc;IAC7D,IAAI,CAAC,IAAI,MAAM;QAAE,OAAO,KAAK,CAAC;IAC9B,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC;AAC1C,CAAC;AAED,SAAS,IAAI,CAAC,IAAwB;IACpC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AAC5B,CAAC;AAED,SAAS,cAAc,CAAC,CAAmB,EAAE,CAAmB;IAC9D,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACrB,CAAC;SAIe,MAAM,CAAC,OAAoC;IACzD,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;IAC5B,MAAM,SAAS,GAAG,SAAS,GAAG,EAAE,CAAC;IACjC,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC;IACtC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;IACvC,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,GAAG,GAAG,EAAE,CAAC;IAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACvC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,GAAG,CAAC,EAAE;YACT,IAAI,GAAG,KAAK,SAAS,EAAE;gBACrB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACtB,GAAG,GAAG,CAAC,CAAC;aACT;YACD,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC;SACxB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QAEhC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;;;YAGxB,IAAI,GAAG,GAAG,SAAS,EAAE;gBACnB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACtB,GAAG,CAAC,UAAU,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;gBAClC,GAAG,IAAI,SAAS,CAAC;aAClB;YACD,IAAI,CAAC,GAAG,CAAC;gBAAE,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;YAE9B,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;SAClD;KACF;IAED,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;IAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..bec92a9c61a0cd462aa53fa4a2f0cf94a6f8436e --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + 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; + } + // Provide a fallback for older environments. + const 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; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b6b2003c28231e42132857de86e34116b547ac58 --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClB;IAED;IACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;0BACd,IAAI,WAAW,EAAE;UACjC,OAAO,MAAM,KAAK,WAAW;cAC7B;gBACE,MAAM,CAAC,GAAe;oBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;oBACpE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;iBACvB;aACF;cACD;gBACE,MAAM,CAAC,GAAe;oBACpB,IAAI,GAAG,GAAG,EAAE,CAAC;oBACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;wBACnC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;qBACpC;oBACD,OAAO,GAAG,CAAC;iBACZ;aACF,CAAC;aAEQ,MAAM,CAAC,QAAgB;QACrC,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;QACjF,MAAM,OAAO,GAAsB,EAAE,CAAC;QAEtC,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,GAAG;YACD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;YACtC,MAAM,IAAI,GAAkB,EAAE,CAAC;YAC/B,IAAI,MAAM,GAAG,IAAI,CAAC;YAClB,IAAI,OAAO,GAAG,CAAC,CAAC;YAChB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAEb,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;gBACjC,IAAI,GAAqB,CAAC;gBAE1B,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBACzC,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;gBACrB,IAAI,GAAG,GAAG,OAAO;oBAAE,MAAM,GAAG,KAAK,CAAC;gBAClC,OAAO,GAAG,GAAG,CAAC;gBAEd,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;oBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBAEzC,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;wBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;wBACzC,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;qBACrD;yBAAM;wBACL,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;qBAC3C;iBACF;qBAAM;oBACL,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;iBACb;gBAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;aAChB;YAED,IAAI,CAAC,MAAM;gBAAE,IAAI,CAAC,IAAI,CAAC,CAAC;YACxB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC;SAClB,QAAQ,KAAK,IAAI,QAAQ,CAAC,MAAM,EAAE;QAEnC,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,SAAS,OAAO,CAAC,QAAgB,EAAE,KAAa;QAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACzC,OAAO,GAAG,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;IAC5C,CAAC;IAED,SAAS,aAAa,CAAC,QAAgB,EAAE,GAAW,EAAE,KAAuB,EAAE,CAAS;QACtF,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,OAAO,GAAG,CAAC,CAAC;QAEhB,GAAG;YACD,MAAM,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC;YACrC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;YACvB,KAAK,IAAI,CAAC,OAAO,GAAG,EAAE,KAAK,KAAK,CAAC;YACjC,KAAK,IAAI,CAAC,CAAC;SACZ,QAAQ,OAAO,GAAG,EAAE,EAAE;QAEvB,MAAM,YAAY,GAAG,KAAK,GAAG,CAAC,CAAC;QAC/B,KAAK,MAAM,CAAC,CAAC;QAEb,IAAI,YAAY,EAAE;YAChB,KAAK,GAAG,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC;SAC9B;QAED,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;QAClB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,SAAS,UAAU,CAAC,QAAgB,EAAE,CAAS,EAAE,MAAc;QAC7D,IAAI,CAAC,IAAI,MAAM;YAAE,OAAO,KAAK,CAAC;QAC9B,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC;IAC1C,CAAC;IAED,SAAS,IAAI,CAAC,IAAwB;QACpC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC5B,CAAC;IAED,SAAS,cAAc,CAAC,CAAmB,EAAE,CAAmB;QAC9D,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACrB,CAAC;aAIe,MAAM,CAAC,OAAoC;QACzD,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;QACjF,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;QAC5B,MAAM,SAAS,GAAG,SAAS,GAAG,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC;QACtC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,GAAG,GAAG,CAAC,CAAC;QACZ,IAAI,GAAG,GAAG,EAAE,CAAC;QAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACvC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YACxB,IAAI,CAAC,GAAG,CAAC,EAAE;gBACT,IAAI,GAAG,KAAK,SAAS,EAAE;oBACrB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACtB,GAAG,GAAG,CAAC,CAAC;iBACT;gBACD,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC;aACxB;YACD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YAEhC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACpC,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;;;gBAGxB,IAAI,GAAG,GAAG,SAAS,EAAE;oBACnB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACtB,GAAG,CAAC,UAAU,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;oBAClC,GAAG,IAAI,SAAS,CAAC;iBAClB;gBACD,IAAI,CAAC,GAAG,CAAC;oBAAE,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;gBAE9B,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;aAClD;SACF;QAED,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;QAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;QAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;QAC3C,GAAG;YACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC7B,GAAG,MAAM,CAAC,CAAC;YACX,IAAI,GAAG,GAAG,CAAC;gBAAE,OAAO,IAAI,QAAQ,CAAC;YACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/web/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/web/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..410d3202f4748a61a199f829a4bc6b35f5572c91 --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/web/node_modules/@jridgewell/sourcemap-codec/package.json b/web/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000000000000000000000000000000000000..578448f1ce9ca0762f828ac2b76ce0b72b262a09 --- /dev/null +++ b/web/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,74 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.4.15", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "require": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "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", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "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" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "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.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "typescript": "4.5.4" + } +} diff --git a/web/node_modules/@rollup/rollup-win32-x64-msvc/README.md b/web/node_modules/@rollup/rollup-win32-x64-msvc/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7382dbc4f9247d26a8df8339bad027ee46f01a8d --- /dev/null +++ b/web/node_modules/@rollup/rollup-win32-x64-msvc/README.md @@ -0,0 +1,3 @@ +# `@rollup/rollup-win32-x64-msvc` + +This is the **x86_64-pc-windows-msvc** binary for `rollup` diff --git a/web/node_modules/@rollup/rollup-win32-x64-msvc/package.json b/web/node_modules/@rollup/rollup-win32-x64-msvc/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7d9d95df10e4eed8a1113b6dd048cb5e3fe133fe --- /dev/null +++ b/web/node_modules/@rollup/rollup-win32-x64-msvc/package.json @@ -0,0 +1,19 @@ +{ + "name": "@rollup/rollup-win32-x64-msvc", + "version": "4.12.0", + "os": [ + "win32" + ], + "cpu": [ + "x64" + ], + "files": [ + "rollup.win32-x64-msvc.node" + ], + "description": "Native bindings for Rollup", + "author": "Lukas Taegert-Atkinson", + "homepage": "https://rollupjs.org/", + "license": "MIT", + "repository": "rollup/rollup", + "main": "./rollup.win32-x64-msvc.node" +} \ No newline at end of file diff --git a/web/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node b/web/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node new file mode 100644 index 0000000000000000000000000000000000000000..40a4940ad5791ae432429815c2c0ec7f385e833f --- /dev/null +++ b/web/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59370607e288b7d958db425a9b78f7c3b186156e63e39d46f07e5b458b399673 +size 3443200 diff --git a/web/node_modules/@sinclair/typebox/compiler/compiler.d.ts b/web/node_modules/@sinclair/typebox/compiler/compiler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f35f75f5572354dfba08417c538441f802cc8bb0 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/compiler/compiler.d.ts @@ -0,0 +1,35 @@ +import * as Types from '../typebox'; +import { ValueErrorIterator } from '../errors/index'; +export type CheckFunction = (value: unknown) => boolean; +export declare class TypeCheck { + private readonly schema; + private readonly references; + private readonly checkFunc; + private readonly code; + constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string); + /** Returns the generated assertion code used to validate this type. */ + Code(): string; + /** Returns an iterator for each error in this value. */ + Errors(value: unknown): ValueErrorIterator; + /** Returns true if the value matches the compiled type. */ + Check(value: unknown): value is Types.Static; +} +export declare class TypeCompilerUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class TypeCompilerDereferenceError extends Error { + readonly schema: Types.TRef; + constructor(schema: Types.TRef); +} +export declare class TypeCompilerTypeGuardError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +/** Compiles Types for Runtime Type Checking */ +export declare namespace TypeCompiler { + /** Returns the generated assertion code used to validate this type. */ + function Code(schema: T, references?: Types.TSchema[]): string; + /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */ + function Compile(schema: T, references?: Types.TSchema[]): TypeCheck; +} diff --git a/web/node_modules/@sinclair/typebox/compiler/compiler.js b/web/node_modules/@sinclair/typebox/compiler/compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..b318e7d85b86b7d4a574a09627da00e1a1b9b1d6 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/compiler/compiler.js @@ -0,0 +1,577 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/compiler + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeCompiler = exports.TypeCompilerTypeGuardError = exports.TypeCompilerDereferenceError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0; +const Types = require("../typebox"); +const index_1 = require("../errors/index"); +const index_2 = require("../system/index"); +const hash_1 = require("../value/hash"); +// ------------------------------------------------------------------- +// TypeCheck +// ------------------------------------------------------------------- +class TypeCheck { + constructor(schema, references, checkFunc, code) { + this.schema = schema; + this.references = references; + this.checkFunc = checkFunc; + this.code = code; + } + /** Returns the generated assertion code used to validate this type. */ + Code() { + return this.code; + } + /** Returns an iterator for each error in this value. */ + Errors(value) { + return index_1.ValueErrors.Errors(this.schema, this.references, value); + } + /** Returns true if the value matches the compiled type. */ + Check(value) { + return this.checkFunc(value); + } +} +exports.TypeCheck = TypeCheck; +// ------------------------------------------------------------------- +// Character +// ------------------------------------------------------------------- +var Character; +(function (Character) { + function DollarSign(code) { + return code === 36; + } + Character.DollarSign = DollarSign; + function IsUnderscore(code) { + return code === 95; + } + Character.IsUnderscore = IsUnderscore; + function IsAlpha(code) { + return (code >= 65 && code <= 90) || (code >= 97 && code <= 122); + } + Character.IsAlpha = IsAlpha; + function IsNumeric(code) { + return code >= 48 && code <= 57; + } + Character.IsNumeric = IsNumeric; +})(Character || (Character = {})); +// ------------------------------------------------------------------- +// MemberExpression +// ------------------------------------------------------------------- +var MemberExpression; +(function (MemberExpression) { + function IsFirstCharacterNumeric(value) { + if (value.length === 0) + return false; + return Character.IsNumeric(value.charCodeAt(0)); + } + function IsAccessor(value) { + if (IsFirstCharacterNumeric(value)) + return false; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + const check = Character.IsAlpha(code) || Character.IsNumeric(code) || Character.DollarSign(code) || Character.IsUnderscore(code); + if (!check) + return false; + } + return true; + } + function EscapeHyphen(key) { + return key.replace(/'/g, "\\'"); + } + function Encode(object, key) { + return IsAccessor(key) ? `${object}.${key}` : `${object}['${EscapeHyphen(key)}']`; + } + MemberExpression.Encode = Encode; +})(MemberExpression || (MemberExpression = {})); +// ------------------------------------------------------------------- +// Identifier +// ------------------------------------------------------------------- +var Identifier; +(function (Identifier) { + function Encode($id) { + const buffer = []; + for (let i = 0; i < $id.length; i++) { + const code = $id.charCodeAt(i); + if (Character.IsNumeric(code) || Character.IsAlpha(code)) { + buffer.push($id.charAt(i)); + } + else { + buffer.push(`_${code}_`); + } + } + return buffer.join('').replace(/__/g, '_'); + } + Identifier.Encode = Encode; +})(Identifier || (Identifier = {})); +// ------------------------------------------------------------------- +// TypeCompiler +// ------------------------------------------------------------------- +class TypeCompilerUnknownTypeError extends Error { + constructor(schema) { + super('TypeCompiler: Unknown type'); + this.schema = schema; + } +} +exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError; +class TypeCompilerDereferenceError extends Error { + constructor(schema) { + super(`TypeCompiler: Unable to dereference schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.TypeCompilerDereferenceError = TypeCompilerDereferenceError; +class TypeCompilerTypeGuardError extends Error { + constructor(schema) { + super('TypeCompiler: Preflight validation check failed to guard for the given schema'); + this.schema = schema; + } +} +exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError; +/** Compiles Types for Runtime Type Checking */ +var TypeCompiler; +(function (TypeCompiler) { + // ------------------------------------------------------------------- + // Guards + // ------------------------------------------------------------------- + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsNumber(value) { + return typeof value === 'number' && globalThis.Number.isFinite(value); + } + function IsString(value) { + return typeof value === 'string'; + } + // ------------------------------------------------------------------- + // Polices + // ------------------------------------------------------------------- + function IsExactOptionalProperty(value, key, expression) { + return index_2.TypeSystem.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`; + } + function IsObjectCheck(value) { + return !index_2.TypeSystem.AllowArrayObjects ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`; + } + function IsRecordCheck(value) { + return !index_2.TypeSystem.AllowArrayObjects + ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}) && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))` + : `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`; + } + function IsNumberCheck(value) { + return !index_2.TypeSystem.AllowNaN ? `(typeof ${value} === 'number' && Number.isFinite(${value}))` : `typeof ${value} === 'number'`; + } + function IsVoidCheck(value) { + return index_2.TypeSystem.AllowVoidNull ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`; + } + // ------------------------------------------------------------------- + // Types + // ------------------------------------------------------------------- + function* Any(schema, references, value) { + yield 'true'; + } + function* Array(schema, references, value) { + const expression = CreateExpression(schema.items, references, 'value'); + yield `Array.isArray(${value}) && ${value}.every(value => ${expression})`; + if (IsNumber(schema.minItems)) + yield `${value}.length >= ${schema.minItems}`; + if (IsNumber(schema.maxItems)) + yield `${value}.length <= ${schema.maxItems}`; + if (schema.uniqueItems === true) + yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`; + } + function* BigInt(schema, references, value) { + yield `(typeof ${value} === 'bigint')`; + if (IsBigInt(schema.multipleOf)) + yield `(${value} % BigInt(${schema.multipleOf})) === 0`; + if (IsBigInt(schema.exclusiveMinimum)) + yield `${value} > BigInt(${schema.exclusiveMinimum})`; + if (IsBigInt(schema.exclusiveMaximum)) + yield `${value} < BigInt(${schema.exclusiveMaximum})`; + if (IsBigInt(schema.minimum)) + yield `${value} >= BigInt(${schema.minimum})`; + if (IsBigInt(schema.maximum)) + yield `${value} <= BigInt(${schema.maximum})`; + } + function* Boolean(schema, references, value) { + yield `typeof ${value} === 'boolean'`; + } + function* Constructor(schema, references, value) { + yield* Visit(schema.returns, references, `${value}.prototype`); + } + function* Date(schema, references, value) { + yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`; + if (IsNumber(schema.exclusiveMinimumTimestamp)) + yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`; + if (IsNumber(schema.exclusiveMaximumTimestamp)) + yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`; + if (IsNumber(schema.minimumTimestamp)) + yield `${value}.getTime() >= ${schema.minimumTimestamp}`; + if (IsNumber(schema.maximumTimestamp)) + yield `${value}.getTime() <= ${schema.maximumTimestamp}`; + } + function* Function(schema, references, value) { + yield `typeof ${value} === 'function'`; + } + function* Integer(schema, references, value) { + yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`; + if (IsNumber(schema.multipleOf)) + yield `(${value} % ${schema.multipleOf}) === 0`; + if (IsNumber(schema.exclusiveMinimum)) + yield `${value} > ${schema.exclusiveMinimum}`; + if (IsNumber(schema.exclusiveMaximum)) + yield `${value} < ${schema.exclusiveMaximum}`; + if (IsNumber(schema.minimum)) + yield `${value} >= ${schema.minimum}`; + if (IsNumber(schema.maximum)) + yield `${value} <= ${schema.maximum}`; + } + function* Intersect(schema, references, value) { + if (schema.unevaluatedProperties === undefined) { + const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value)); + yield `${expressions.join(' && ')}`; + } + else if (schema.unevaluatedProperties === false) { + // prettier-ignore + const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', '); + const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value)); + const expression1 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key))`; + yield `${expressions.join(' && ')} && ${expression1}`; + } + else if (typeof schema.unevaluatedProperties === 'object') { + // prettier-ignore + const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', '); + const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value)); + const expression1 = CreateExpression(schema.unevaluatedProperties, references, 'value[key]'); + const expression2 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key) || ${expression1})`; + yield `${expressions.join(' && ')} && ${expression2}`; + } + } + function* Literal(schema, references, value) { + if (typeof schema.const === 'number' || typeof schema.const === 'boolean') { + yield `${value} === ${schema.const}`; + } + else { + yield `${value} === '${schema.const}'`; + } + } + function* Never(schema, references, value) { + yield `false`; + } + function* Not(schema, references, value) { + const left = CreateExpression(schema.allOf[0].not, references, value); + const right = CreateExpression(schema.allOf[1], references, value); + yield `!${left} && ${right}`; + } + function* Null(schema, references, value) { + yield `${value} === null`; + } + function* Number(schema, references, value) { + yield IsNumberCheck(value); + if (IsNumber(schema.multipleOf)) + yield `(${value} % ${schema.multipleOf}) === 0`; + if (IsNumber(schema.exclusiveMinimum)) + yield `${value} > ${schema.exclusiveMinimum}`; + if (IsNumber(schema.exclusiveMaximum)) + yield `${value} < ${schema.exclusiveMaximum}`; + if (IsNumber(schema.minimum)) + yield `${value} >= ${schema.minimum}`; + if (IsNumber(schema.maximum)) + yield `${value} <= ${schema.maximum}`; + } + function* Object(schema, references, value) { + yield IsObjectCheck(value); + if (IsNumber(schema.minProperties)) + yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`; + if (IsNumber(schema.maxProperties)) + yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`; + const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties); + for (const knownKey of knownKeys) { + const memberExpression = MemberExpression.Encode(value, knownKey); + const property = schema.properties[knownKey]; + if (schema.required && schema.required.includes(knownKey)) { + yield* Visit(property, references, memberExpression); + if (Types.ExtendsUndefined.Check(property)) + yield `('${knownKey}' in ${value})`; + } + else { + const expression = CreateExpression(property, references, memberExpression); + yield IsExactOptionalProperty(value, knownKey, expression); + } + } + if (schema.additionalProperties === false) { + if (schema.required && schema.required.length === knownKeys.length) { + yield `Object.getOwnPropertyNames(${value}).length === ${knownKeys.length}`; + } + else { + const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`; + yield `Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key))`; + } + } + if (typeof schema.additionalProperties === 'object') { + const expression = CreateExpression(schema.additionalProperties, references, 'value[key]'); + const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`; + yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`; + } + } + function* Promise(schema, references, value) { + yield `(typeof value === 'object' && typeof ${value}.then === 'function')`; + } + function* Record(schema, references, value) { + yield IsRecordCheck(value); + if (IsNumber(schema.minProperties)) + yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`; + if (IsNumber(schema.maxProperties)) + yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`; + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + const local = PushLocal(`new RegExp(/${keyPattern}/)`); + yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`; + const expression = CreateExpression(valueSchema, references, 'value'); + yield `Object.values(${value}).every(value => ${expression})`; + } + function* Ref(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new TypeCompilerDereferenceError(schema); + const target = references[index]; + // Reference: If we have seen this reference before we can just yield and return + // the function call. If this isn't the case we defer to visit to generate and + // set the function for subsequent passes. Consider for refactor. + if (state_local_function_names.has(schema.$ref)) + return yield `${CreateFunctionName(schema.$ref)}(${value})`; + yield* Visit(target, references, value); + } + function* String(schema, references, value) { + yield `(typeof ${value} === 'string')`; + if (IsNumber(schema.minLength)) + yield `${value}.length >= ${schema.minLength}`; + if (IsNumber(schema.maxLength)) + yield `${value}.length <= ${schema.maxLength}`; + if (schema.pattern !== undefined) { + const local = PushLocal(`${new RegExp(schema.pattern)};`); + yield `${local}.test(${value})`; + } + if (schema.format !== undefined) { + yield `format('${schema.format}', ${value})`; + } + } + function* Symbol(schema, references, value) { + yield `(typeof ${value} === 'symbol')`; + } + function* TemplateLiteral(schema, references, value) { + yield `(typeof ${value} === 'string')`; + const local = PushLocal(`${new RegExp(schema.pattern)};`); + yield `${local}.test(${value})`; + } + function* This(schema, references, value) { + const func = CreateFunctionName(schema.$ref); + yield `${func}(${value})`; + } + function* Tuple(schema, references, value) { + yield `(Array.isArray(${value}))`; + if (schema.items === undefined) + return yield `${value}.length === 0`; + yield `(${value}.length === ${schema.maxItems})`; + for (let i = 0; i < schema.items.length; i++) { + const expression = CreateExpression(schema.items[i], references, `${value}[${i}]`); + yield `${expression}`; + } + } + function* Undefined(schema, references, value) { + yield `${value} === undefined`; + } + function* Union(schema, references, value) { + const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value)); + yield `(${expressions.join(' || ')})`; + } + function* Uint8Array(schema, references, value) { + yield `${value} instanceof Uint8Array`; + if (IsNumber(schema.maxByteLength)) + yield `(${value}.length <= ${schema.maxByteLength})`; + if (IsNumber(schema.minByteLength)) + yield `(${value}.length >= ${schema.minByteLength})`; + } + function* Unknown(schema, references, value) { + yield 'true'; + } + function* Void(schema, references, value) { + yield IsVoidCheck(value); + } + function* UserDefined(schema, references, value) { + const schema_key = `schema_key_${state_remote_custom_types.size}`; + state_remote_custom_types.set(schema_key, schema); + yield `custom('${schema[Types.Kind]}', '${schema_key}', ${value})`; + } + function* Visit(schema, references, value) { + const references_ = IsString(schema.$id) ? [...references, schema] : references; + const schema_ = schema; + // Reference: Referenced schemas can originate from either additional schemas + // or inline in the schema itself. Ideally the recursive path should align to + // reference path. Consider for refactor. + if (IsString(schema.$id) && !state_local_function_names.has(schema.$id)) { + state_local_function_names.add(schema.$id); + const name = CreateFunctionName(schema.$id); + const body = CreateFunction(name, schema, references, 'value'); + PushFunction(body); + yield `${name}(${value})`; + return; + } + switch (schema_[Types.Kind]) { + case 'Any': + return yield* Any(schema_, references_, value); + case 'Array': + return yield* Array(schema_, references_, value); + case 'BigInt': + return yield* BigInt(schema_, references_, value); + case 'Boolean': + return yield* Boolean(schema_, references_, value); + case 'Constructor': + return yield* Constructor(schema_, references_, value); + case 'Date': + return yield* Date(schema_, references_, value); + case 'Function': + return yield* Function(schema_, references_, value); + case 'Integer': + return yield* Integer(schema_, references_, value); + case 'Intersect': + return yield* Intersect(schema_, references_, value); + case 'Literal': + return yield* Literal(schema_, references_, value); + case 'Never': + return yield* Never(schema_, references_, value); + case 'Not': + return yield* Not(schema_, references_, value); + case 'Null': + return yield* Null(schema_, references_, value); + case 'Number': + return yield* Number(schema_, references_, value); + case 'Object': + return yield* Object(schema_, references_, value); + case 'Promise': + return yield* Promise(schema_, references_, value); + case 'Record': + return yield* Record(schema_, references_, value); + case 'Ref': + return yield* Ref(schema_, references_, value); + case 'String': + return yield* String(schema_, references_, value); + case 'Symbol': + return yield* Symbol(schema_, references_, value); + case 'TemplateLiteral': + return yield* TemplateLiteral(schema_, references_, value); + case 'This': + return yield* This(schema_, references_, value); + case 'Tuple': + return yield* Tuple(schema_, references_, value); + case 'Undefined': + return yield* Undefined(schema_, references_, value); + case 'Union': + return yield* Union(schema_, references_, value); + case 'Uint8Array': + return yield* Uint8Array(schema_, references_, value); + case 'Unknown': + return yield* Unknown(schema_, references_, value); + case 'Void': + return yield* Void(schema_, references_, value); + default: + if (!Types.TypeRegistry.Has(schema_[Types.Kind])) + throw new TypeCompilerUnknownTypeError(schema); + return yield* UserDefined(schema_, references_, value); + } + } + // ------------------------------------------------------------------- + // Compiler State + // ------------------------------------------------------------------- + const state_local_variables = new Set(); // local variables and functions + const state_local_function_names = new Set(); // local function names used call ref validators + const state_remote_custom_types = new Map(); // remote custom types used during compilation + function ResetCompiler() { + state_local_variables.clear(); + state_local_function_names.clear(); + state_remote_custom_types.clear(); + } + function CreateExpression(schema, references, value) { + return `(${[...Visit(schema, references, value)].join(' && ')})`; + } + function CreateFunctionName($id) { + return `check_${Identifier.Encode($id)}`; + } + function CreateFunction(name, schema, references, value) { + const expression = [...Visit(schema, references, value)].map((condition) => ` ${condition}`).join(' &&\n'); + return `function ${name}(value) {\n return (\n${expression}\n )\n}`; + } + function PushFunction(functionBody) { + state_local_variables.add(functionBody); + } + function PushLocal(expression) { + const local = `local_${state_local_variables.size}`; + state_local_variables.add(`const ${local} = ${expression}`); + return local; + } + function GetLocals() { + return [...state_local_variables.values()]; + } + // ------------------------------------------------------------------- + // Compile + // ------------------------------------------------------------------- + function Build(schema, references) { + ResetCompiler(); + const check = CreateFunction('check', schema, references, 'value'); + const locals = GetLocals(); + return `${locals.join('\n')}\nreturn ${check}`; + } + /** Returns the generated assertion code used to validate this type. */ + function Code(schema, references = []) { + if (!Types.TypeGuard.TSchema(schema)) + throw new TypeCompilerTypeGuardError(schema); + for (const schema of references) + if (!Types.TypeGuard.TSchema(schema)) + throw new TypeCompilerTypeGuardError(schema); + return Build(schema, references); + } + TypeCompiler.Code = Code; + /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */ + function Compile(schema, references = []) { + const code = Code(schema, references); + const custom_schemas = new Map(state_remote_custom_types); + const compiledFunction = globalThis.Function('custom', 'format', 'hash', code); + const checkFunction = compiledFunction((kind, schema_key, value) => { + if (!Types.TypeRegistry.Has(kind) || !custom_schemas.has(schema_key)) + return false; + const schema = custom_schemas.get(schema_key); + const func = Types.TypeRegistry.Get(kind); + return func(schema, value); + }, (format, value) => { + if (!Types.FormatRegistry.Has(format)) + return false; + const func = Types.FormatRegistry.Get(format); + return func(value); + }, (value) => { + return hash_1.ValueHash.Create(value); + }); + return new TypeCheck(schema, references, checkFunction, code); + } + TypeCompiler.Compile = Compile; +})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {})); diff --git a/web/node_modules/@sinclair/typebox/compiler/index.d.ts b/web/node_modules/@sinclair/typebox/compiler/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4062a62f8366369104fc094fe5d1f517225561d0 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/compiler/index.d.ts @@ -0,0 +1,2 @@ +export { ValueError, ValueErrorType } from '../errors/index'; +export * from './compiler'; diff --git a/web/node_modules/@sinclair/typebox/compiler/index.js b/web/node_modules/@sinclair/typebox/compiler/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7a013c3ed15b564a6c5ff3e838bd272ed0596b85 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/compiler/index.js @@ -0,0 +1,47 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/compiler + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +var __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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueErrorType = void 0; +var index_1 = require("../errors/index"); +Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } }); +__exportStar(require("./compiler"), exports); diff --git a/web/node_modules/@sinclair/typebox/errors/errors.d.ts b/web/node_modules/@sinclair/typebox/errors/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..89786c61bc6a24733ed423199fd1f47f24354d55 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/errors/errors.d.ts @@ -0,0 +1,88 @@ +import * as Types from '../typebox'; +export declare enum ValueErrorType { + Array = 0, + ArrayMinItems = 1, + ArrayMaxItems = 2, + ArrayUniqueItems = 3, + BigInt = 4, + BigIntMultipleOf = 5, + BigIntExclusiveMinimum = 6, + BigIntExclusiveMaximum = 7, + BigIntMinimum = 8, + BigIntMaximum = 9, + Boolean = 10, + Date = 11, + DateExclusiveMinimumTimestamp = 12, + DateExclusiveMaximumTimestamp = 13, + DateMinimumTimestamp = 14, + DateMaximumTimestamp = 15, + Function = 16, + Integer = 17, + IntegerMultipleOf = 18, + IntegerExclusiveMinimum = 19, + IntegerExclusiveMaximum = 20, + IntegerMinimum = 21, + IntegerMaximum = 22, + Intersect = 23, + IntersectUnevaluatedProperties = 24, + Literal = 25, + Never = 26, + Not = 27, + Null = 28, + Number = 29, + NumberMultipleOf = 30, + NumberExclusiveMinimum = 31, + NumberExclusiveMaximum = 32, + NumberMinumum = 33, + NumberMaximum = 34, + Object = 35, + ObjectMinProperties = 36, + ObjectMaxProperties = 37, + ObjectAdditionalProperties = 38, + ObjectRequiredProperties = 39, + Promise = 40, + RecordKeyNumeric = 41, + RecordKeyString = 42, + String = 43, + StringMinLength = 44, + StringMaxLength = 45, + StringPattern = 46, + StringFormatUnknown = 47, + StringFormat = 48, + Symbol = 49, + TupleZeroLength = 50, + TupleLength = 51, + Undefined = 52, + Union = 53, + Uint8Array = 54, + Uint8ArrayMinByteLength = 55, + Uint8ArrayMaxByteLength = 56, + Void = 57, + Custom = 58 +} +export interface ValueError { + type: ValueErrorType; + schema: Types.TSchema; + path: string; + value: unknown; + message: string; +} +export declare class ValueErrorIterator { + private readonly iterator; + constructor(iterator: IterableIterator); + [Symbol.iterator](): IterableIterator; + /** Returns the first value error or undefined if no errors */ + First(): ValueError | undefined; +} +export declare class ValueErrorsUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueErrorsDereferenceError extends Error { + readonly schema: Types.TRef | Types.TThis; + constructor(schema: Types.TRef | Types.TThis); +} +/** Provides functionality to generate a sequence of errors against a TypeBox type. */ +export declare namespace ValueErrors { + function Errors(schema: T, references: Types.TSchema[], value: any): ValueErrorIterator; +} diff --git a/web/node_modules/@sinclair/typebox/errors/errors.js b/web/node_modules/@sinclair/typebox/errors/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..4f7210ba337903c7f68689bf63652067f4815a1a --- /dev/null +++ b/web/node_modules/@sinclair/typebox/errors/errors.js @@ -0,0 +1,609 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueErrors = exports.ValueErrorsDereferenceError = exports.ValueErrorsUnknownTypeError = exports.ValueErrorIterator = exports.ValueErrorType = void 0; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/errors + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +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. + +---------------------------------------------------------------------------*/ +const Types = require("../typebox"); +const index_1 = require("../system/index"); +const hash_1 = require("../value/hash"); +// ------------------------------------------------------------------- +// ValueErrorType +// ------------------------------------------------------------------- +var ValueErrorType; +(function (ValueErrorType) { + ValueErrorType[ValueErrorType["Array"] = 0] = "Array"; + ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems"; + ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems"; + ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems"; + ValueErrorType[ValueErrorType["BigInt"] = 4] = "BigInt"; + ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 5] = "BigIntMultipleOf"; + ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 6] = "BigIntExclusiveMinimum"; + ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 7] = "BigIntExclusiveMaximum"; + ValueErrorType[ValueErrorType["BigIntMinimum"] = 8] = "BigIntMinimum"; + ValueErrorType[ValueErrorType["BigIntMaximum"] = 9] = "BigIntMaximum"; + ValueErrorType[ValueErrorType["Boolean"] = 10] = "Boolean"; + ValueErrorType[ValueErrorType["Date"] = 11] = "Date"; + ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 12] = "DateExclusiveMinimumTimestamp"; + ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 13] = "DateExclusiveMaximumTimestamp"; + ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 14] = "DateMinimumTimestamp"; + ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 15] = "DateMaximumTimestamp"; + ValueErrorType[ValueErrorType["Function"] = 16] = "Function"; + ValueErrorType[ValueErrorType["Integer"] = 17] = "Integer"; + ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 18] = "IntegerMultipleOf"; + ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 19] = "IntegerExclusiveMinimum"; + ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 20] = "IntegerExclusiveMaximum"; + ValueErrorType[ValueErrorType["IntegerMinimum"] = 21] = "IntegerMinimum"; + ValueErrorType[ValueErrorType["IntegerMaximum"] = 22] = "IntegerMaximum"; + ValueErrorType[ValueErrorType["Intersect"] = 23] = "Intersect"; + ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 24] = "IntersectUnevaluatedProperties"; + ValueErrorType[ValueErrorType["Literal"] = 25] = "Literal"; + ValueErrorType[ValueErrorType["Never"] = 26] = "Never"; + ValueErrorType[ValueErrorType["Not"] = 27] = "Not"; + ValueErrorType[ValueErrorType["Null"] = 28] = "Null"; + ValueErrorType[ValueErrorType["Number"] = 29] = "Number"; + ValueErrorType[ValueErrorType["NumberMultipleOf"] = 30] = "NumberMultipleOf"; + ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 31] = "NumberExclusiveMinimum"; + ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 32] = "NumberExclusiveMaximum"; + ValueErrorType[ValueErrorType["NumberMinumum"] = 33] = "NumberMinumum"; + ValueErrorType[ValueErrorType["NumberMaximum"] = 34] = "NumberMaximum"; + ValueErrorType[ValueErrorType["Object"] = 35] = "Object"; + ValueErrorType[ValueErrorType["ObjectMinProperties"] = 36] = "ObjectMinProperties"; + ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 37] = "ObjectMaxProperties"; + ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 38] = "ObjectAdditionalProperties"; + ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 39] = "ObjectRequiredProperties"; + ValueErrorType[ValueErrorType["Promise"] = 40] = "Promise"; + ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 41] = "RecordKeyNumeric"; + ValueErrorType[ValueErrorType["RecordKeyString"] = 42] = "RecordKeyString"; + ValueErrorType[ValueErrorType["String"] = 43] = "String"; + ValueErrorType[ValueErrorType["StringMinLength"] = 44] = "StringMinLength"; + ValueErrorType[ValueErrorType["StringMaxLength"] = 45] = "StringMaxLength"; + ValueErrorType[ValueErrorType["StringPattern"] = 46] = "StringPattern"; + ValueErrorType[ValueErrorType["StringFormatUnknown"] = 47] = "StringFormatUnknown"; + ValueErrorType[ValueErrorType["StringFormat"] = 48] = "StringFormat"; + ValueErrorType[ValueErrorType["Symbol"] = 49] = "Symbol"; + ValueErrorType[ValueErrorType["TupleZeroLength"] = 50] = "TupleZeroLength"; + ValueErrorType[ValueErrorType["TupleLength"] = 51] = "TupleLength"; + ValueErrorType[ValueErrorType["Undefined"] = 52] = "Undefined"; + ValueErrorType[ValueErrorType["Union"] = 53] = "Union"; + ValueErrorType[ValueErrorType["Uint8Array"] = 54] = "Uint8Array"; + ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 55] = "Uint8ArrayMinByteLength"; + ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 56] = "Uint8ArrayMaxByteLength"; + ValueErrorType[ValueErrorType["Void"] = 57] = "Void"; + ValueErrorType[ValueErrorType["Custom"] = 58] = "Custom"; +})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {})); +// ------------------------------------------------------------------- +// ValueErrorIterator +// ------------------------------------------------------------------- +class ValueErrorIterator { + constructor(iterator) { + this.iterator = iterator; + } + [Symbol.iterator]() { + return this.iterator; + } + /** Returns the first value error or undefined if no errors */ + First() { + const next = this.iterator.next(); + return next.done ? undefined : next.value; + } +} +exports.ValueErrorIterator = ValueErrorIterator; +// ------------------------------------------------------------------- +// ValueErrors +// ------------------------------------------------------------------- +class ValueErrorsUnknownTypeError extends Error { + constructor(schema) { + super('ValueErrors: Unknown type'); + this.schema = schema; + } +} +exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError; +class ValueErrorsDereferenceError extends Error { + constructor(schema) { + super(`ValueErrors: Unable to dereference schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueErrorsDereferenceError = ValueErrorsDereferenceError; +/** Provides functionality to generate a sequence of errors against a TypeBox type. */ +var ValueErrors; +(function (ValueErrors) { + // ---------------------------------------------------------------------- + // Guards + // ---------------------------------------------------------------------- + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsInteger(value) { + return globalThis.Number.isInteger(value); + } + function IsString(value) { + return typeof value === 'string'; + } + function IsDefined(value) { + return value !== undefined; + } + // ---------------------------------------------------------------------- + // Policies + // ---------------------------------------------------------------------- + function IsExactOptionalProperty(value, key) { + return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined; + } + function IsObject(value) { + const result = typeof value === 'object' && value !== null; + return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value); + } + function IsRecordObject(value) { + return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array); + } + function IsNumber(value) { + const result = typeof value === 'number'; + return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value); + } + function IsVoid(value) { + const result = value === undefined; + return index_1.TypeSystem.AllowVoidNull ? result || value === null : result; + } + // ---------------------------------------------------------------------- + // Types + // ---------------------------------------------------------------------- + function* Any(schema, references, path, value) { } + function* Array(schema, references, path, value) { + if (!globalThis.Array.isArray(value)) { + return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` }; + } + if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) { + yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` }; + } + if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) { + yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` }; + } + // prettier-ignore + if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) { + const hashed = hash_1.ValueHash.Create(element); + if (set.has(hashed)) { + return false; + } + else { + set.add(hashed); + } + } return true; })())) { + yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` }; + } + for (let i = 0; i < value.length; i++) { + yield* Visit(schema.items, references, `${path}/${i}`, value[i]); + } + } + function* BigInt(schema, references, path, value) { + if (!IsBigInt(value)) { + return yield { type: ValueErrorType.BigInt, schema, path, value, message: `Expected bigint` }; + } + if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) { + yield { type: ValueErrorType.BigIntMultipleOf, schema, path, value, message: `Expected bigint to be a multiple of ${schema.multipleOf}` }; + } + if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) { + yield { type: ValueErrorType.BigIntExclusiveMinimum, schema, path, value, message: `Expected bigint to be greater than ${schema.exclusiveMinimum}` }; + } + if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) { + yield { type: ValueErrorType.BigIntExclusiveMaximum, schema, path, value, message: `Expected bigint to be less than ${schema.exclusiveMaximum}` }; + } + if (IsDefined(schema.minimum) && !(value >= schema.minimum)) { + yield { type: ValueErrorType.BigIntMinimum, schema, path, value, message: `Expected bigint to be greater or equal to ${schema.minimum}` }; + } + if (IsDefined(schema.maximum) && !(value <= schema.maximum)) { + yield { type: ValueErrorType.BigIntMaximum, schema, path, value, message: `Expected bigint to be less or equal to ${schema.maximum}` }; + } + } + function* Boolean(schema, references, path, value) { + if (!(typeof value === 'boolean')) { + return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` }; + } + } + function* Constructor(schema, references, path, value) { + yield* Visit(schema.returns, references, path, value.prototype); + } + function* Date(schema, references, path, value) { + if (!(value instanceof globalThis.Date)) { + return yield { type: ValueErrorType.Date, schema, path, value, message: `Expected Date object` }; + } + if (!globalThis.isFinite(value.getTime())) { + return yield { type: ValueErrorType.Date, schema, path, value, message: `Invalid Date` }; + } + if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) { + yield { type: ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater than ${schema.exclusiveMinimum}` }; + } + if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) { + yield { type: ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less than ${schema.exclusiveMaximum}` }; + } + if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) { + yield { type: ValueErrorType.DateMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater or equal to ${schema.minimum}` }; + } + if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) { + yield { type: ValueErrorType.DateMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less or equal to ${schema.maximum}` }; + } + } + function* Function(schema, references, path, value) { + if (!(typeof value === 'function')) { + return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` }; + } + } + function* Integer(schema, references, path, value) { + if (!IsInteger(value)) { + return yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` }; + } + if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) { + yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` }; + } + if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) { + yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` }; + } + if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) { + yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` }; + } + if (IsDefined(schema.minimum) && !(value >= schema.minimum)) { + yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` }; + } + if (IsDefined(schema.maximum) && !(value <= schema.maximum)) { + yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` }; + } + } + function* Intersect(schema, references, path, value) { + for (const subschema of schema.allOf) { + const next = Visit(subschema, references, path, value).next(); + if (!next.done) { + yield next.value; + yield { type: ValueErrorType.Intersect, schema, path, value, message: `Expected all sub schemas to be valid` }; + return; + } + } + if (schema.unevaluatedProperties === false) { + const schemaKeys = Types.KeyResolver.Resolve(schema); + const valueKeys = globalThis.Object.getOwnPropertyNames(value); + for (const valueKey of valueKeys) { + if (!schemaKeys.includes(valueKey)) { + yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Unexpected property` }; + } + } + } + if (typeof schema.unevaluatedProperties === 'object') { + const schemaKeys = Types.KeyResolver.Resolve(schema); + const valueKeys = globalThis.Object.getOwnPropertyNames(value); + for (const valueKey of valueKeys) { + if (!schemaKeys.includes(valueKey)) { + const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next(); + if (!next.done) { + yield next.value; + yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Invalid additional property` }; + return; + } + } + } + } + } + function* Literal(schema, references, path, value) { + if (!(value === schema.const)) { + const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const; + return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` }; + } + } + function* Never(schema, references, path, value) { + yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` }; + } + function* Not(schema, references, path, value) { + if (Visit(schema.allOf[0].not, references, path, value).next().done === true) { + yield { type: ValueErrorType.Not, schema, path, value, message: `Value should not validate` }; + } + yield* Visit(schema.allOf[1], references, path, value); + } + function* Null(schema, references, path, value) { + if (!(value === null)) { + return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` }; + } + } + function* Number(schema, references, path, value) { + if (!IsNumber(value)) { + return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` }; + } + if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) { + yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` }; + } + if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) { + yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` }; + } + if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) { + yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` }; + } + if (IsDefined(schema.minimum) && !(value >= schema.minimum)) { + yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` }; + } + if (IsDefined(schema.maximum) && !(value <= schema.maximum)) { + yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${schema.maximum}` }; + } + } + function* Object(schema, references, path, value) { + if (!IsObject(value)) { + return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` }; + } + if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) { + yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` }; + } + if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) { + yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` }; + } + const requiredKeys = globalThis.Array.isArray(schema.required) ? schema.required : []; + const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties); + const unknownKeys = globalThis.Object.getOwnPropertyNames(value); + for (const knownKey of knownKeys) { + const property = schema.properties[knownKey]; + if (schema.required && schema.required.includes(knownKey)) { + yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]); + if (Types.ExtendsUndefined.Check(schema) && !(knownKey in value)) { + yield { type: ValueErrorType.ObjectRequiredProperties, schema: property, path: `${path}/${knownKey}`, value: undefined, message: `Expected required property` }; + } + } + else { + if (IsExactOptionalProperty(value, knownKey)) { + yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]); + } + } + } + for (const requiredKey of requiredKeys) { + if (unknownKeys.includes(requiredKey)) + continue; + yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` }; + } + if (schema.additionalProperties === false) { + for (const valueKey of unknownKeys) { + if (!knownKeys.includes(valueKey)) { + yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${valueKey}`, value: value[valueKey], message: `Unexpected property` }; + } + } + } + if (typeof schema.additionalProperties === 'object') { + for (const valueKey of unknownKeys) { + if (knownKeys.includes(valueKey)) + continue; + yield* Visit(schema.additionalProperties, references, `${path}/${valueKey}`, value[valueKey]); + } + } + } + function* Promise(schema, references, path, value) { + if (!(typeof value === 'object' && typeof value.then === 'function')) { + yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` }; + } + } + function* Record(schema, references, path, value) { + if (!IsRecordObject(value)) { + return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected record object` }; + } + if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) { + yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` }; + } + if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) { + yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` }; + } + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + const regex = new RegExp(keyPattern); + if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) { + const numeric = keyPattern === Types.PatternNumberExact; + const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString; + const message = numeric ? 'Expected all object property keys to be numeric' : 'Expected all object property keys to be strings'; + return yield { type, schema, path, value, message }; + } + for (const [propKey, propValue] of globalThis.Object.entries(value)) { + yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue); + } + } + function* Ref(schema, references, path, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueErrorsDereferenceError(schema); + const target = references[index]; + yield* Visit(target, references, path, value); + } + function* String(schema, references, path, value) { + if (!IsString(value)) { + return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' }; + } + if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) { + yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` }; + } + if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) { + yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` }; + } + if (schema.pattern !== undefined) { + const regex = new RegExp(schema.pattern); + if (!regex.test(value)) { + yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` }; + } + } + if (schema.format !== undefined) { + if (!Types.FormatRegistry.Has(schema.format)) { + yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` }; + } + else { + const format = Types.FormatRegistry.Get(schema.format); + if (!format(value)) { + yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` }; + } + } + } + } + function* Symbol(schema, references, path, value) { + if (!(typeof value === 'symbol')) { + return yield { type: ValueErrorType.Symbol, schema, path, value, message: 'Expected symbol' }; + } + } + function* TemplateLiteral(schema, references, path, value) { + if (!IsString(value)) { + return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' }; + } + const regex = new RegExp(schema.pattern); + if (!regex.test(value)) { + yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` }; + } + } + function* This(schema, references, path, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueErrorsDereferenceError(schema); + const target = references[index]; + yield* Visit(target, references, path, value); + } + function* Tuple(schema, references, path, value) { + if (!globalThis.Array.isArray(value)) { + return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' }; + } + if (schema.items === undefined && !(value.length === 0)) { + return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' }; + } + if (!(value.length === schema.maxItems)) { + yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` }; + } + if (!schema.items) { + return; + } + for (let i = 0; i < schema.items.length; i++) { + yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]); + } + } + function* Undefined(schema, references, path, value) { + if (!(value === undefined)) { + yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` }; + } + } + function* Union(schema, references, path, value) { + const errors = []; + for (const inner of schema.anyOf) { + const variantErrors = [...Visit(inner, references, path, value)]; + if (variantErrors.length === 0) + return; + errors.push(...variantErrors); + } + if (errors.length > 0) { + yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' }; + } + for (const error of errors) { + yield error; + } + } + function* Uint8Array(schema, references, path, value) { + if (!(value instanceof globalThis.Uint8Array)) { + return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` }; + } + if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) { + yield { type: ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length less or equal to ${schema.maxByteLength}` }; + } + if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) { + yield { type: ValueErrorType.Uint8ArrayMinByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length greater or equal to ${schema.maxByteLength}` }; + } + } + function* Unknown(schema, references, path, value) { } + function* Void(schema, references, path, value) { + if (!IsVoid(value)) { + return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected void` }; + } + } + function* UserDefined(schema, references, path, value) { + const check = Types.TypeRegistry.Get(schema[Types.Kind]); + if (!check(schema, value)) { + return yield { type: ValueErrorType.Custom, schema, path, value, message: `Expected kind ${schema[Types.Kind]}` }; + } + } + function* Visit(schema, references, path, value) { + const references_ = IsDefined(schema.$id) ? [...references, schema] : references; + const schema_ = schema; + switch (schema_[Types.Kind]) { + case 'Any': + return yield* Any(schema_, references_, path, value); + case 'Array': + return yield* Array(schema_, references_, path, value); + case 'BigInt': + return yield* BigInt(schema_, references_, path, value); + case 'Boolean': + return yield* Boolean(schema_, references_, path, value); + case 'Constructor': + return yield* Constructor(schema_, references_, path, value); + case 'Date': + return yield* Date(schema_, references_, path, value); + case 'Function': + return yield* Function(schema_, references_, path, value); + case 'Integer': + return yield* Integer(schema_, references_, path, value); + case 'Intersect': + return yield* Intersect(schema_, references_, path, value); + case 'Literal': + return yield* Literal(schema_, references_, path, value); + case 'Never': + return yield* Never(schema_, references_, path, value); + case 'Not': + return yield* Not(schema_, references_, path, value); + case 'Null': + return yield* Null(schema_, references_, path, value); + case 'Number': + return yield* Number(schema_, references_, path, value); + case 'Object': + return yield* Object(schema_, references_, path, value); + case 'Promise': + return yield* Promise(schema_, references_, path, value); + case 'Record': + return yield* Record(schema_, references_, path, value); + case 'Ref': + return yield* Ref(schema_, references_, path, value); + case 'String': + return yield* String(schema_, references_, path, value); + case 'Symbol': + return yield* Symbol(schema_, references_, path, value); + case 'TemplateLiteral': + return yield* TemplateLiteral(schema_, references_, path, value); + case 'This': + return yield* This(schema_, references_, path, value); + case 'Tuple': + return yield* Tuple(schema_, references_, path, value); + case 'Undefined': + return yield* Undefined(schema_, references_, path, value); + case 'Union': + return yield* Union(schema_, references_, path, value); + case 'Uint8Array': + return yield* Uint8Array(schema_, references_, path, value); + case 'Unknown': + return yield* Unknown(schema_, references_, path, value); + case 'Void': + return yield* Void(schema_, references_, path, value); + default: + if (!Types.TypeRegistry.Has(schema_[Types.Kind])) + throw new ValueErrorsUnknownTypeError(schema); + return yield* UserDefined(schema_, references_, path, value); + } + } + function Errors(schema, references, value) { + const iterator = Visit(schema, references, '', value); + return new ValueErrorIterator(iterator); + } + ValueErrors.Errors = Errors; +})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {})); diff --git a/web/node_modules/@sinclair/typebox/errors/index.d.ts b/web/node_modules/@sinclair/typebox/errors/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f72bc43e28cad220d270da2cf4674036807975b9 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/errors/index.d.ts @@ -0,0 +1 @@ +export * from './errors'; diff --git a/web/node_modules/@sinclair/typebox/errors/index.js b/web/node_modules/@sinclair/typebox/errors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9637155fc7ba172ea9b0d1a0d192c1054cb1eb32 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/errors/index.js @@ -0,0 +1,44 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/errors + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +var __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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./errors"), exports); diff --git a/web/node_modules/@sinclair/typebox/license b/web/node_modules/@sinclair/typebox/license new file mode 100644 index 0000000000000000000000000000000000000000..08641fd64607abb3d392d87edbdf7cb0c0c21103 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/license @@ -0,0 +1,23 @@ +TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +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/web/node_modules/@sinclair/typebox/package.json b/web/node_modules/@sinclair/typebox/package.json new file mode 100644 index 0000000000000000000000000000000000000000..eeff01d95b6972812f345565fd7336a0894f0ee5 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/package.json @@ -0,0 +1,47 @@ +{ + "name": "@sinclair/typebox", + "version": "0.27.8", + "description": "JSONSchema Type Builder with Static Type Resolution for TypeScript", + "keywords": [ + "typescript", + "json-schema", + "validate", + "typecheck" + ], + "author": "sinclairzx81", + "license": "MIT", + "main": "./typebox.js", + "types": "./typebox.d.ts", + "exports": { + "./compiler": "./compiler/index.js", + "./errors": "./errors/index.js", + "./system": "./system/index.js", + "./value": "./value/index.js", + ".": "./typebox.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/sinclairzx81/typebox" + }, + "scripts": { + "clean": "hammer task clean", + "format": "hammer task format", + "start": "hammer task start", + "test": "hammer task test", + "benchmark": "hammer task benchmark", + "build": "hammer task build", + "publish": "hammer task publish" + }, + "devDependencies": { + "@sinclair/hammer": "^0.17.1", + "@types/chai": "^4.3.3", + "@types/mocha": "^9.1.1", + "@types/node": "^18.11.9", + "ajv": "^8.12.0", + "ajv-formats": "^2.1.1", + "chai": "^4.3.6", + "mocha": "^9.2.2", + "prettier": "^2.7.1", + "typescript": "^5.0.2" + } +} diff --git a/web/node_modules/@sinclair/typebox/readme.md b/web/node_modules/@sinclair/typebox/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..c5120a9d5b2e40699023850453ff7f6db64b1b27 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/readme.md @@ -0,0 +1,1424 @@ +
+ +

TypeBox

+ +

JSON Schema Type Builder with Static Type Resolution for TypeScript

+ + + +
+
+ +[![npm version](https://badge.fury.io/js/%40sinclair%2Ftypebox.svg)](https://badge.fury.io/js/%40sinclair%2Ftypebox) +[![Downloads](https://img.shields.io/npm/dm/%40sinclair%2Ftypebox.svg)](https://www.npmjs.com/package/%40sinclair%2Ftypebox) +[![GitHub CI](https://github.com/sinclairzx81/typebox/workflows/GitHub%20CI/badge.svg)](https://github.com/sinclairzx81/typebox/actions) + +
+ + + +## Install + +#### Npm +```bash +$ npm install @sinclair/typebox --save +``` + +#### Deno +```typescript +import { Static, Type } from 'npm:@sinclair/typebox' +``` + +#### Esm + +```typescript +import { Static, Type } from 'https://esm.sh/@sinclair/typebox' +``` + +## Example + +```typescript +import { Static, Type } from '@sinclair/typebox' + +const T = Type.Object({ // const T = { + x: Type.Number(), // type: 'object', + y: Type.Number(), // required: ['x', 'y', 'z'], + z: Type.Number() // properties: { +}) // x: { type: 'number' }, + // y: { type: 'number' }, + // z: { type: 'number' } + // } + // } + +type T = Static // type T = { + // x: number, + // y: number, + // z: number + // } +``` + + + + +## Overview + +TypeBox is a runtime type builder that creates in-memory JSON Schema objects that can be statically inferred as TypeScript types. The schemas produced by this library are designed to match the static type assertion rules of the TypeScript compiler. TypeBox enables one to create a unified type that can be statically checked by TypeScript and runtime asserted using standard JSON Schema validation. + +This library is designed to enable JSON schema to compose with the same flexibility as TypeScript's type system. It can be used as a simple tool to build up complex schemas or integrated into REST or RPC services to help validate data received over the wire. + +License MIT + +## Contents +- [Install](#install) +- [Overview](#overview) +- [Usage](#usage) +- [Types](#types) + - [Standard](#types-standard) + - [Extended](#types-extended) + - [Modifiers](#types-modifiers) + - [Options](#types-options) + - [Generics](#types-generics) + - [References](#types-references) + - [Recursive](#types-recursive) + - [Conditional](#types-conditional) + - [Template Literal](#types-template-literal) + - [Guards](#types-guards) + - [Unsafe](#types-unsafe) + - [Strict](#types-strict) +- [Values](#values) + - [Create](#values-create) + - [Clone](#values-clone) + - [Check](#values-check) + - [Convert](#values-convert) + - [Cast](#values-cast) + - [Equal](#values-equal) + - [Hash](#values-hash) + - [Diff](#values-diff) + - [Patch](#values-patch) + - [Errors](#values-errors) + - [Mutate](#values-mutate) + - [Pointer](#values-pointer) +- [TypeCheck](#typecheck) + - [Ajv](#typecheck-ajv) + - [TypeCompiler](#typecheck-typecompiler) +- [TypeSystem](#typesystem) + - [Types](#typesystem-types) + - [Formats](#typesystem-formats) + - [Policies](#typesystem-policies) +- [Benchmark](#benchmark) + - [Compile](#benchmark-compile) + - [Validate](#benchmark-validate) + - [Compression](#benchmark-compression) +- [Contribute](#contribute) + + + +## Usage + +The following shows general usage. + +```typescript +import { Static, Type } from '@sinclair/typebox' + +//-------------------------------------------------------------------------------------------- +// +// Let's say you have the following type ... +// +//-------------------------------------------------------------------------------------------- + +type T = { + id: string, + name: string, + timestamp: number +} + +//-------------------------------------------------------------------------------------------- +// +// ... you can express this type in the following way. +// +//-------------------------------------------------------------------------------------------- + +const T = Type.Object({ // const T = { + id: Type.String(), // type: 'object', + name: Type.String(), // properties: { + timestamp: Type.Integer() // id: { +}) // type: 'string' + // }, + // name: { + // type: 'string' + // }, + // timestamp: { + // type: 'integer' + // } + // }, + // required: [ + // 'id', + // 'name', + // 'timestamp' + // ] + // } + +//-------------------------------------------------------------------------------------------- +// +// ... then infer back to the original static type this way. +// +//-------------------------------------------------------------------------------------------- + +type T = Static // type T = { + // id: string, + // name: string, + // timestamp: number + // } + +//-------------------------------------------------------------------------------------------- +// +// ... then use the type both as JSON schema and as a TypeScript type. +// +//-------------------------------------------------------------------------------------------- + +import { Value } from '@sinclair/typebox/value' + +function receive(value: T) { // ... as a Static Type + + if(Value.Check(T, value)) { // ... as a JSON Schema + + // ok... + } +} +``` + + + +## Types + +TypeBox types are JSON schema fragments that can be composed into more complex types. Each fragment is structured such that a JSON schema compliant validator can runtime assert a value the same way TypeScript will statically assert a type. TypeBox provides a set of Standard types which are used create JSON schema compliant schematics as well as an Extended type set used to create schematics for constructs native to JavaScript. + + + +### Standard Types + +The following table lists the Standard TypeBox types. These types are fully compatible with the JSON Schema Draft 6 specification. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ JSON Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Any() │ type T = any │ const T = { } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Unknown() │ type T = unknown │ const T = { } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.String() │ type T = string │ const T = { │ +│ │ │ type: 'string' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Number() │ type T = number │ const T = { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Integer() │ type T = number │ const T = { │ +│ │ │ type: 'integer' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Boolean() │ type T = boolean │ const T = { │ +│ │ │ type: 'boolean' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Null() │ type T = null │ const T = { │ +│ │ │ type: 'null' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Literal(42) │ type T = 42 │ const T = { │ +│ │ │ const: 42, │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Array( │ type T = number[] │ const T = { │ +│ Type.Number() │ │ type: 'array', │ +│ ) │ │ items: { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ x: Type.Number(), │ x: number, │ type: 'object', │ +│ y: Type.Number() │ y: number │ required: ['x', 'y'], │ +│ }) │ } │ properties: { │ +│ │ │ x: { │ +│ │ │ type: 'number' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Tuple([ │ type T = [number, number] │ const T = { │ +│ Type.Number(), │ │ type: 'array', │ +│ Type.Number() │ │ items: [{ │ +│ ]) │ │ type: 'number' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }], │ +│ │ │ additionalItems: false, │ +│ │ │ minItems: 2, │ +│ │ │ maxItems: 2 │ +│ │ │ } │ +│ │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ enum Foo { │ enum Foo { │ const T = { │ +│ A, │ A, │ anyOf: [{ │ +│ B │ B │ type: 'number', │ +│ } │ } │ const: 0 │ +│ │ │ }, { │ +│ const T = Type.Enum(Foo) │ type T = Foo │ type: 'number', │ +│ │ │ const: 1 │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.KeyOf( │ type T = keyof { │ const T = { │ +│ Type.Object({ │ x: number, │ anyOf: [{ │ +│ x: Type.Number(), │ y: number │ type: 'string', │ +│ y: Type.Number() │ } │ const: 'x' │ +│ }) │ │ }, { │ +│ ) │ │ type: 'string', │ +│ │ │ const: 'y' │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Union([ │ type T = string | number │ const T = { │ +│ Type.String(), │ │ anyOf: [{ │ +│ Type.Number() │ │ type: 'string' │ +│ ]) │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Intersect([ │ type T = { │ const T = { │ +│ Type.Object({ │ x: number │ allOf: [{ │ +│ x: Type.Number() │ } & { │ type: 'object', │ +│ }), │ y: number │ required: ['x'], │ +│ Type.Object({ │ } │ properties: { │ +│ y: Type.Number() │ │ x: { │ +│ ]) │ │ type: 'number' │ +│ ]) │ │ } │ +│ │ │ } │ +│ │ │ }, { │ +│ │ │ type: 'object', | +│ │ │ required: ['y'], │ +│ │ │ properties: { │ +│ │ │ y: { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Composite([ │ type I = { │ const T = { │ +│ Type.Object({ │ x: number │ type: 'object', │ +│ x: Type.Number() │ } & { │ required: ['x', 'y'], │ +│ }), │ y: number │ properties: { │ +│ Type.Object({ │ } │ x: { │ +│ y: Type.Number() │ │ type: 'number' │ +│ }) │ type T = { │ }, │ +│ ]) │ [K in keyof I]: I[K] │ y: { │ +│ │ } │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Never() │ type T = never │ const T = { │ +│ │ │ not: {} │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Not( | type T = string │ const T = { │ +| Type.Union([ │ │ allOf: [{ │ +│ Type.Literal('x'), │ │ not: { │ +│ Type.Literal('y'), │ │ anyOf: [ │ +│ Type.Literal('z') │ │ { const: 'x' }, │ +│ ]), │ │ { const: 'y' }, │ +│ Type.String() │ │ { const: 'z' } │ +│ ) │ │ ] │ +│ │ │ } │ +│ │ │ }, { │ +│ │ │ type: 'string' │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Extends( │ type T = │ const T = { │ +│ Type.String(), │ string extends number │ const: false, │ +│ Type.Number(), │ true : false │ type: 'boolean' │ +│ Type.Literal(true), │ │ } │ +│ Type.Literal(false) │ │ │ +│ ) │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Extract( │ type T = Extract< │ const T = { │ +│ Type.Union([ │ string | number, │ type: 'string' │ +│ Type.String(), │ string │ } │ +│ Type.Number(), │ > │ │ +│ ]), │ │ │ +│ Type.String() │ │ │ +│ ) │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Exclude( │ type T = Exclude< │ const T = { │ +│ Type.Union([ │ string | number, │ type: 'number' │ +│ Type.String(), │ string │ } │ +│ Type.Number(), │ > │ │ +│ ]), │ │ │ +│ Type.String() │ │ │ +│ ) │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const U = Type.Union([ │ type U = 'open' | 'close' │ const T = { │ +│ Type.Literal('open'), │ │ type: 'string', │ +│ Type.Literal('close') │ type T = `on${U}` │ pattern: '^on(open|close)$' │ +│ ]) │ │ } │ +│ │ │ │ +│ const T = Type │ │ │ +│ .TemplateLiteral([ │ │ │ +│ Type.Literal('on'), │ │ │ +│ U │ │ │ +│ ]) │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Record( │ type T = Record< │ const T = { │ +│ Type.String(), │ string, │ type: 'object', │ +│ Type.Number() │ number │ patternProperties: { │ +│ ) │ > │ '^.*$': { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Partial( │ type T = Partial<{ │ const T = { │ +│ Type.Object({ │ x: number, │ type: 'object', │ +│ x: Type.Number(), │ y: number │ properties: { │ +│ y: Type.Number() | }> │ x: { │ +│ }) │ │ type: 'number' │ +│ ) │ │ }, │ +│ │ │ y: { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Required( │ type T = Required<{ │ const T = { │ +│ Type.Object({ │ x?: number, │ type: 'object', │ +│ x: Type.Optional( │ y?: number │ required: ['x', 'y'], │ +│ Type.Number() | }> │ properties: { │ +│ ), │ │ x: { │ +│ y: Type.Optional( │ │ type: 'number' │ +│ Type.Number() │ │ }, │ +│ ) │ │ y: { │ +│ }) │ │ type: 'number' │ +│ ) │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Pick( │ type T = Pick<{ │ const T = { │ +│ Type.Object({ │ x: number, │ type: 'object', │ +│ x: Type.Number(), │ y: number │ required: ['x'], │ +│ y: Type.Number() │ }, 'x'> │ properties: { │ +│ }), ['x'] | │ x: { │ +│ ) │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Omit( │ type T = Omit<{ │ const T = { │ +│ Type.Object({ │ x: number, │ type: 'object', │ +│ x: Type.Number(), │ y: number │ required: ['y'], │ +│ y: Type.Number() │ }, 'x'> │ properties: { │ +│ }), ['x'] | │ y: { │ +│ ) │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const R = { │ +│ x: Type.Number(), │ x: number, │ $ref: 'T' │ +│ y: Type.Number() │ y: number │ } │ +│ }, { $id: 'T' }) | } │ │ +│ │ │ │ +│ const R = Type.Ref(T) │ type R = T │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Extended Types + +TypeBox provides several extended types that can be used to produce schematics for common JavaScript constructs. These types can not be used with standard JSON schema validators; but are useful to help frame schematics for RPC interfaces that may receive JSON validated data. Extended types are prefixed with the `[Extended]` doc comment for convenience. The following table lists the supported types. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ Extended Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Constructor([ │ type T = new ( │ const T = { │ +│ Type.String(), │ arg0: string, │ type: 'object', │ +│ Type.Number() │ arg1: number │ instanceOf: 'Constructor', │ +│ ], Type.Boolean()) │ ) => boolean │ parameters: [{ │ +│ │ │ type: 'string' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }], │ +│ │ │ return: { │ +│ │ │ type: 'boolean' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Function([ │ type T = ( │ const T = { │ +| Type.String(), │ arg0: string, │ type : 'object', │ +│ Type.Number() │ arg1: number │ instanceOf: 'Function', │ +│ ], Type.Boolean()) │ ) => boolean │ parameters: [{ │ +│ │ │ type: 'string' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }], │ +│ │ │ return: { │ +│ │ │ type: 'boolean' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Promise( │ type T = Promise │ const T = { │ +│ Type.String() │ │ type: 'object', │ +│ ) │ │ instanceOf: 'Promise', │ +│ │ │ item: { │ +│ │ │ type: 'string' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Uint8Array() │ type T = Uint8Array │ const T = { │ +│ │ │ type: 'object', │ +│ │ │ instanceOf: 'Uint8Array' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Date() │ type T = Date │ const T = { │ +│ │ │ type: 'object', │ +│ │ │ instanceOf: 'Date' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Undefined() │ type T = undefined │ const T = { │ +│ │ │ type: 'null', │ +│ │ │ typeOf: 'Undefined' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.RegEx(/foo/) │ type T = string │ const T = { │ +│ │ │ type: 'string', │ +│ │ │ pattern: 'foo' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Symbol() │ type T = symbol │ const T = { │ +│ │ │ type: 'null', │ +│ │ │ typeOf: 'Symbol' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.BigInt() │ type T = bigint │ const T = { │ +│ │ │ type: 'null', │ +│ │ │ typeOf: 'BigInt' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Void() │ type T = void │ const T = { │ +│ │ │ type: 'null' │ +│ │ │ typeOf: 'Void' │ +│ │ │ } │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Modifiers + +TypeBox provides modifiers that allow schema properties to be statically inferred as `readonly` or `optional`. The following table shows the supported modifiers and how they map between TypeScript and JSON Schema. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ JSON Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ name: Type.Optional( │ name?: string │ type: 'object', │ +│ Type.String() │ } │ properties: { │ +│ ) │ │ name: { │ +│ }) │ │ type: 'string' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ name: Type.Readonly( │ readonly name: string │ type: 'object', │ +│ Type.String() │ } │ properties: { │ +│ ) │ │ name: { │ +│ }) │ │ type: 'string' │ +│ │ │ } │ +│ │ │ }, │ +│ │ │ required: ['name'] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ name: Type.ReadonlyOptional( │ readonly name?: string │ type: 'object', │ +│ Type.String() │ } │ properties: { │ +│ ) │ │ name: { │ +│ }) │ │ type: 'string' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Options + +You can pass JSON Schema options on the last argument of any type. Option hints specific to each type are provided for convenience. + +```typescript +// String must be an email +const T = Type.String({ // const T = { + format: 'email' // type: 'string', +}) // format: 'email' + // } + +// Mumber must be a multiple of 2 +const T = Type.Number({ // const T = { + multipleOf: 2 // type: 'number', +}) // multipleOf: 2 + // } + +// Array must have at least 5 integer values +const T = Type.Array(Type.Integer(), { // const T = { + minItems: 5 // type: 'array', +}) // minItems: 5, + // items: { + // type: 'integer' + // } + // } + +``` + + + +### Generic Types + +Generic types can be created with generic functions constrained to type `TSchema`. The following creates a generic `Vector` type. + +```typescript +import { Type, Static, TSchema } from '@sinclair/typebox' + +const Vector = (t: T) => Type.Object({ x: t, y: t, z: t }) + +const NumberVector = Vector(Type.Number()) // const NumberVector = { + // type: 'object', + // required: ['x', 'y', 'z'], + // properties: { + // x: { type: 'number' }, + // y: { type: 'number' }, + // z: { type: 'number' } + // } + // } + +type NumberVector = Static // type NumberVector = { + // x: number, + // y: number, + // z: number + // } + +const BooleanVector = Vector(Type.Boolean()) // const BooleanVector = { + // type: 'object', + // required: ['x', 'y', 'z'], + // properties: { + // x: { type: 'boolean' }, + // y: { type: 'boolean' }, + // z: { type: 'boolean' } + // } + // } + +type BooleanVector = Static // type BooleanVector = { + // x: boolean, + // y: boolean, + // z: boolean + // } +``` + +The following creates a generic `Nullable` type. + +```typescript +const Nullable = (schema: T) => Type.Union([schema, Type.Null()]) + +const T = Nullable(Type.String()) // const T = { + // anyOf: [ + // { type: 'string' }, + // { type: 'null' } + // ] + // } + +type T = Static // type T = string | null +``` + + + +### Reference Types + +Reference types are supported with `Type.Ref`. The target type must specify a valid `$id`. + +```typescript +const T = Type.String({ $id: 'T' }) // const T = { + // $id: 'T', + // type: 'string' + // } + +const R = Type.Ref(T) // const R = { + // $ref: 'T' + // } +``` + + + +### Recursive Types + +Recursive types are supported with `Type.Recursive` + +```typescript +const Node = Type.Recursive(Node => Type.Object({ // const Node = { + id: Type.String(), // $id: 'Node', + nodes: Type.Array(Node) // type: 'object', +}), { $id: 'Node' }) // properties: { + // id: { + // type: 'string' + // }, + // nodes: { + // type: 'array', + // items: { + // $ref: 'Node' + // } + // } + // }, + // required: [ + // 'id', + // 'nodes' + // ] + // } + +type Node = Static // type Node = { + // id: string + // nodes: Node[] + // } + +function test(node: Node) { + const id = node.nodes[0].nodes[0].id // id is string +} +``` + + + +### Conditional Types + +Conditional types are supported with `Type.Extends`, `Type.Exclude` and `Type.Extract` + +```typescript +// TypeScript + +type T0 = string extends number ? true : false // type T0 = false + +type T1 = Extract // type T1 = number + +type T2 = Exclude // type T2 = string + +// TypeBox + +const T0 = Type.Extends(Type.String(), Type.Number(), Type.Literal(true), Type.Literal(false)) + +const T1 = Type.Extract(Type.Union([Type.String(), Type.Number()]), Type.Number()) + +const T2 = Type.Exclude(Type.Union([Type.String(), Type.Number()]), Type.Number()) + + +type T0 = Static // type T0 = false + +type T1 = Static // type T1 = number + +type T2 = Static // type T2 = string +``` + + + +### Template Literal Types + +Template Literal types are supported with `Type.TemplateLiteral` + +```typescript +// TypeScript + +type T = `option${'A'|'B'}` // type T = 'optionA' | 'optionB' + +type R = Record // type R = { + // optionA: string + // optionB: string + // } + +// TypeBox + +const T = Type.TemplateLiteral([ // const T = { + Type.Literal('option'), // pattern: '^option(A|B)$', + Type.Union([ // type: 'string' + Type.Literal('A'), // } + Type.Literal('B') + ]) +]) + +const R = Type.Record(T, Type.String()) // const R = { + // type: 'object', + // required: ['optionA', 'optionB'], + // properties: { + // optionA: { + // type: 'string' + // }, + // optionB: { + // type: 'string' + // } + // } + // } + +type T = Static // type T = 'optionA' | 'optionB' + +type R = Static // type R = { + // optionA: string + // optionB: string + // } +``` + + + +### Unsafe + +Use `Type.Unsafe` to create custom schematics with user defined inference rules. + +```typescript +const T = Type.Unsafe({ type: 'number' }) // const T = { + // type: 'number' + // } + +type T = Static // type T = string +``` + +The `Type.Unsafe` type can be useful to express specific OpenAPI schema representations. + +```typescript +import { Type, Static, TSchema } from '@sinclair/typebox' + +// Nullable + +function Nullable(schema: T) { + return Type.Unsafe | null>({ ...schema, nullable: true }) +} + +const T = Nullable(Type.String()) // const T = { + // type: 'string', + // nullable: true + // } + +type T = Static // type T = string | null + +// StringEnum + +function StringEnum(values: [...T]) { + return Type.Unsafe({ type: 'string', enum: values }) +} + +const T = StringEnum(['A', 'B', 'C']) // const T = { + // enum: ['A', 'B', 'C'] + // } + +type T = Static // type T = 'A' | 'B' | 'C' +``` + + + +### Guards + +TypeBox provides a `TypeGuard` module that can be used for reflection and asserting values as types. + +```typescript +import { Type, TypeGuard } from '@sinclair/typebox' + +const T = Type.String() + +if(TypeGuard.TString(T)) { + + // T is TString +} +``` + + + +### Strict + +TypeBox schemas contain the `Kind` and `Modifier` symbol properties. These properties are used for type composition and reflection. These properties are not strictly valid JSON schema; so in some cases it may be desirable to omit them. TypeBox provides a `Type.Strict` function that will omit these properties if necessary. + +```typescript +const T = Type.Object({ // const T = { + name: Type.Optional(Type.String()) // [Kind]: 'Object', +}) // type: 'object', + // properties: { + // name: { + // [Kind]: 'String', + // type: 'string', + // [Modifier]: 'Optional' + // } + // } + // } + +const U = Type.Strict(T) // const U = { + // type: 'object', + // properties: { + // name: { + // type: 'string' + // } + // } + // } +``` + + + +## Values + +TypeBox provides an optional utility module that can be used to perform common operations on JavaScript values. This module includes functionality to create, check and cast values from types as well as check equality, clone, diff and patch JavaScript values. This module is provided via optional import. + +```typescript +import { Value } from '@sinclair/typebox/value' +``` + + + +### Create + +Use the Create function to create a value from a type. TypeBox will use default values if specified. + +```typescript +const T = Type.Object({ x: Type.Number(), y: Type.Number({ default: 42 }) }) + +const A = Value.Create(T) // const A = { x: 0, y: 42 } +``` + + + +### Clone + +Use the Clone function to deeply clone a value + +```typescript +const A = Value.Clone({ x: 1, y: 2, z: 3 }) // const A = { x: 1, y: 2, z: 3 } +``` + + + +### Check + +Use the Check function to type check a value + +```typescript +const T = Type.Object({ x: Type.Number() }) + +const R = Value.Check(T, { x: 1 }) // const R = true +``` + + + +### Convert + +Use the Convert function to convert a value into its target type if a reasonable conversion is possible. + +```typescript +const T = Type.Object({ x: Type.Number() }) + +const R1 = Value.Convert(T, { x: '3.14' }) // const R1 = { x: 3.14 } + +const R2 = Value.Convert(T, { x: 'not a number' }) // const R2 = { x: 'not a number' } +``` + + + +### Cast + +Use the Cast function to cast a value into a type. The cast function will retain as much information as possible from the original value. + +```typescript +const T = Type.Object({ x: Type.Number(), y: Type.Number() }, { additionalProperties: false }) + +const X = Value.Cast(T, null) // const X = { x: 0, y: 0 } + +const Y = Value.Cast(T, { x: 1 }) // const Y = { x: 1, y: 0 } + +const Z = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const Z = { x: 1, y: 2 } +``` + + + +### Equal + +Use the Equal function to deeply check for value equality. + +```typescript +const R = Value.Equal( // const R = true + { x: 1, y: 2, z: 3 }, + { x: 1, y: 2, z: 3 } +) +``` + + + +### Hash + +Use the Hash function to create a [FNV1A-64](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function) non cryptographic hash of a value. + +```typescript +const A = Value.Hash({ x: 1, y: 2, z: 3 }) // const A = 2910466848807138541n + +const B = Value.Hash({ x: 1, y: 4, z: 3 }) // const B = 1418369778807423581n +``` + + + +### Diff + +Use the Diff function to produce a sequence of edits to transform one value into another. + +```typescript +const E = Value.Diff( // const E = [ + { x: 1, y: 2, z: 3 }, // { type: 'update', path: '/y', value: 4 }, + { y: 4, z: 5, w: 6 } // { type: 'update', path: '/z', value: 5 }, +) // { type: 'insert', path: '/w', value: 6 }, + // { type: 'delete', path: '/x' } + // ] +``` + + + +### Patch + +Use the Patch function to apply edits + +```typescript +const A = { x: 1, y: 2 } + +const B = { x: 3 } + +const E = Value.Diff(A, B) // const E = [ + // { type: 'update', path: '/x', value: 3 }, + // { type: 'delete', path: '/y' } + // ] + +const C = Value.Patch(A, E) // const C = { x: 3 } +``` + + + +### Errors + +Use the Errors function enumerate validation errors. + +```typescript +const T = Type.Object({ x: Type.Number(), y: Type.Number() }) + +const R = [...Value.Errors(T, { x: '42' })] // const R = [{ + // schema: { type: 'number' }, + // path: '/x', + // value: '42', + // message: 'Expected number' + // }, { + // schema: { type: 'number' }, + // path: '/y', + // value: undefined, + // message: 'Expected number' + // }] +``` + + + +### Mutate + +Use the Mutate function to perform a deep mutable value assignment while retaining internal references. + +```typescript +const Y = { z: 1 } // const Y = { z: 1 } + +const X = { y: Y } // const X = { y: { z: 1 } } + +const A = { x: X } // const A = { x: { y: { z: 1 } } } + + +Value.Mutate(A, { x: { y: { z: 2 } } }) // const A' = { x: { y: { z: 2 } } } + +const R0 = A.x.y.z === 2 // const R0 = 2 + +const R1 = A.x.y === Y // const R1 = true + +const R2 = A.x === X // const R2 = true +``` + + + +### Pointer + +Use ValuePointer to perform mutable updates on existing values using [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) JSON Pointers. + +```typescript +import { ValuePointer } from '@sinclair/typebox/value' + +const A = { x: 0, y: 0, z: 0 } + +ValuePointer.Set(A, '/x', 1) // const A' = { x: 1, y: 0, z: 0 } + +ValuePointer.Set(A, '/y', 1) // const A' = { x: 1, y: 1, z: 0 } + +ValuePointer.Set(A, '/z', 1) // const A' = { x: 1, y: 1, z: 1 } +``` + + + +## TypeCheck + +TypeBox types target JSON Schema draft 6 so are compatible with any validator that supports this specification. TypeBox also provides a built in type checking compiler designed specifically for high performance compilation and value assertion. + +The following sections detail using Ajv and TypeBox's compiler infrastructure. + + + +## Ajv + +The following shows the recommended setup for Ajv. + +```bash +$ npm install ajv ajv-formats --save +``` + +```typescript +import { Type } from '@sinclair/typebox' +import addFormats from 'ajv-formats' +import Ajv from 'ajv' + +const ajv = addFormats(new Ajv({}), [ + 'date-time', + 'time', + 'date', + 'email', + 'hostname', + 'ipv4', + 'ipv6', + 'uri', + 'uri-reference', + 'uuid', + 'uri-template', + 'json-pointer', + 'relative-json-pointer', + 'regex' +]) + +const C = ajv.compile(Type.Object({ + x: Type.Number(), + y: Type.Number(), + z: Type.Number() +})) + +const R = C({ x: 1, y: 2, z: 3 }) // const R = true +``` + + + +### TypeCompiler + +The TypeBox TypeCompiler is a high performance JIT compiler that transforms TypeBox types into optimized JavaScript validation routines. The compiler is tuned for fast compilation as well as fast value assertion. It is designed to serve as a validation backend that can be integrated into larger applications; but can also be used as a general purpose validator. + +The TypeCompiler is provided as an optional import. + +```typescript +import { TypeCompiler } from '@sinclair/typebox/compiler' +``` + +Use the `Compile(...)` function to compile a type. + +```typescript +const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck> + +const R = C.Check({ x: 1, y: 2, z: 3 }) // const R = true +``` + +Use the `Errors(...)` function to produce diagnostic errors for a value. The `Errors(...)` function will return an iterator that if enumerated; will perform an exhaustive check across the entire value and yield any error found. For performance, this function should only be called after failed `Check(...)`. Applications may also choose to yield only the first value to avoid exhaustive error generation. + +```typescript +const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck> + +const value = { } + +const errors = [...C.Errors(value)] // const errors = [{ + // schema: { type: 'number' }, + // path: '/x', + // value: undefined, + // message: 'Expected number' + // }, { + // schema: { type: 'number' }, + // path: '/y', + // value: undefined, + // message: 'Expected number' + // }, { + // schema: { type: 'number' }, + // path: '/z', + // value: undefined, + // message: 'Expected number' + // }] +``` + +Compiled routines can be inspected with the `.Code()` function. + +```typescript +const C = TypeCompiler.Compile(Type.String()) // const C: TypeCheck + +console.log(C.Code()) // return function check(value) { + // return ( + // (typeof value === 'string') + // ) + // } +``` + + + +## TypeSystem + +The TypeBox TypeSystem module provides functionality to define types above and beyond the Standard and Extended type sets as well as control various assertion polices. Configurations made to the TypeSystem module are observed by both `TypeCompiler` and `Value` modules. + +The TypeSystem module is provided as an optional import. + +```typescript +import { TypeSystem } from '@sinclair/typebox/system' +``` + + + +### Types + +Use the `Type(...)` function to create a custom type. This function will return a type factory function that can be used to construct the type. The following creates a Point type. + +```typescript +type PointOptions = { } // The Type Options + +type PointType = { x: number, y: number } // The Static Type + +const Point = TypeSystem.Type('Point', (options, value) => { + return ( + typeof value === 'object' && value !== null && + typeof value.x === 'number' && + typeof value.y === 'number' + ) +}) + +const T = Point() + +type T = Static // type T = { x: number, y: number } + +const R = Value.Check(T, { x: 1, y: 2 }) // const R = true +``` + + + +### Formats + +Use the `Format(...)` function to create a custom string format. The following creates a format that checks for lowercase strings. + +```typescript +TypeSystem.Format('lowercase', value => value === value.toLowerCase()) // format should be lowercase + +const T = Type.String({ format: 'lowercase' }) + +const A = Value.Check(T, 'Hello') // const A = false + +const B = Value.Check(T, 'hello') // const B = true +``` + + + +### Policies + +TypeBox validates using JSON Schema assertion policies by default. It is possible to override these policies and have TypeBox assert using TypeScript policies. The following overrides are available. + +```typescript +// Allow arrays to validate as object types (default is false) +// +// const A: {} = [] - allowed in TS + +TypeSystem.AllowArrayObjects = true + +// Allow numeric values to be NaN or + or - Infinity (default is false) +// +// const A: number = NaN - allowed in TS + +TypeSystem.AllowNaN = true +``` + + + +## Benchmark + +This project maintains a set of benchmarks that measure Ajv, Value and TypeCompiler compilation and validation performance. These benchmarks can be run locally by cloning this repository and running `npm run benchmark`. The results below show for Ajv version 8.12.0. + +For additional comparative benchmarks, please refer to [typescript-runtime-type-benchmarks](https://moltar.github.io/typescript-runtime-type-benchmarks/). + + + +### Compile + +This benchmark measures compilation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/compile.ts). + +```typescript +┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┐ +│ (index) │ Iterations │ Ajv │ TypeCompiler │ Performance │ +├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┤ +│ Literal_String │ 1000 │ ' 257 ms' │ ' 8 ms' │ ' 32.13 x' │ +│ Literal_Number │ 1000 │ ' 203 ms' │ ' 4 ms' │ ' 50.75 x' │ +│ Literal_Boolean │ 1000 │ ' 183 ms' │ ' 4 ms' │ ' 45.75 x' │ +│ Primitive_Number │ 1000 │ ' 174 ms' │ ' 8 ms' │ ' 21.75 x' │ +│ Primitive_String │ 1000 │ ' 158 ms' │ ' 9 ms' │ ' 17.56 x' │ +│ Primitive_String_Pattern │ 1000 │ ' 213 ms' │ ' 13 ms' │ ' 16.38 x' │ +│ Primitive_Boolean │ 1000 │ ' 136 ms' │ ' 6 ms' │ ' 22.67 x' │ +│ Primitive_Null │ 1000 │ ' 144 ms' │ ' 6 ms' │ ' 24.00 x' │ +│ Object_Unconstrained │ 1000 │ ' 1176 ms' │ ' 38 ms' │ ' 30.95 x' │ +│ Object_Constrained │ 1000 │ ' 1181 ms' │ ' 31 ms' │ ' 38.10 x' │ +│ Object_Vector3 │ 1000 │ ' 387 ms' │ ' 8 ms' │ ' 48.38 x' │ +│ Object_Box3D │ 1000 │ ' 1693 ms' │ ' 25 ms' │ ' 67.72 x' │ +│ Tuple_Primitive │ 1000 │ ' 470 ms' │ ' 15 ms' │ ' 31.33 x' │ +│ Tuple_Object │ 1000 │ ' 1206 ms' │ ' 17 ms' │ ' 70.94 x' │ +│ Composite_Intersect │ 1000 │ ' 567 ms' │ ' 20 ms' │ ' 28.35 x' │ +│ Composite_Union │ 1000 │ ' 515 ms' │ ' 21 ms' │ ' 24.52 x' │ +│ Math_Vector4 │ 1000 │ ' 787 ms' │ ' 10 ms' │ ' 78.70 x' │ +│ Math_Matrix4 │ 1000 │ ' 386 ms' │ ' 8 ms' │ ' 48.25 x' │ +│ Array_Primitive_Number │ 1000 │ ' 349 ms' │ ' 7 ms' │ ' 49.86 x' │ +│ Array_Primitive_String │ 1000 │ ' 336 ms' │ ' 4 ms' │ ' 84.00 x' │ +│ Array_Primitive_Boolean │ 1000 │ ' 284 ms' │ ' 3 ms' │ ' 94.67 x' │ +│ Array_Object_Unconstrained │ 1000 │ ' 1704 ms' │ ' 19 ms' │ ' 89.68 x' │ +│ Array_Object_Constrained │ 1000 │ ' 1456 ms' │ ' 18 ms' │ ' 80.89 x' │ +│ Array_Tuple_Primitive │ 1000 │ ' 792 ms' │ ' 15 ms' │ ' 52.80 x' │ +│ Array_Tuple_Object │ 1000 │ ' 1552 ms' │ ' 17 ms' │ ' 91.29 x' │ +│ Array_Composite_Intersect │ 1000 │ ' 744 ms' │ ' 18 ms' │ ' 41.33 x' │ +│ Array_Composite_Union │ 1000 │ ' 783 ms' │ ' 15 ms' │ ' 52.20 x' │ +│ Array_Math_Vector4 │ 1000 │ ' 1093 ms' │ ' 14 ms' │ ' 78.07 x' │ +│ Array_Math_Matrix4 │ 1000 │ ' 684 ms' │ ' 6 ms' │ ' 114.00 x' │ +└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┘ +``` + + + +### Validate + +This benchmark measures validation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/check.ts). + +```typescript +┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐ +│ (index) │ Iterations │ ValueCheck │ Ajv │ TypeCompiler │ Performance │ +├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤ +│ Literal_String │ 1000000 │ ' 27 ms' │ ' 6 ms' │ ' 5 ms' │ ' 1.20 x' │ +│ Literal_Number │ 1000000 │ ' 23 ms' │ ' 21 ms' │ ' 11 ms' │ ' 1.91 x' │ +│ Literal_Boolean │ 1000000 │ ' 21 ms' │ ' 20 ms' │ ' 10 ms' │ ' 2.00 x' │ +│ Primitive_Number │ 1000000 │ ' 26 ms' │ ' 19 ms' │ ' 11 ms' │ ' 1.73 x' │ +│ Primitive_String │ 1000000 │ ' 25 ms' │ ' 19 ms' │ ' 10 ms' │ ' 1.90 x' │ +│ Primitive_String_Pattern │ 1000000 │ ' 155 ms' │ ' 49 ms' │ ' 43 ms' │ ' 1.14 x' │ +│ Primitive_Boolean │ 1000000 │ ' 23 ms' │ ' 19 ms' │ ' 10 ms' │ ' 1.90 x' │ +│ Primitive_Null │ 1000000 │ ' 24 ms' │ ' 19 ms' │ ' 10 ms' │ ' 1.90 x' │ +│ Object_Unconstrained │ 1000000 │ ' 804 ms' │ ' 35 ms' │ ' 28 ms' │ ' 1.25 x' │ +│ Object_Constrained │ 1000000 │ ' 1041 ms' │ ' 55 ms' │ ' 41 ms' │ ' 1.34 x' │ +│ Object_Vector3 │ 1000000 │ ' 380 ms' │ ' 26 ms' │ ' 20 ms' │ ' 1.30 x' │ +│ Object_Box3D │ 1000000 │ ' 1785 ms' │ ' 65 ms' │ ' 52 ms' │ ' 1.25 x' │ +│ Object_Recursive │ 1000000 │ ' 4984 ms' │ ' 396 ms' │ ' 114 ms' │ ' 3.47 x' │ +│ Tuple_Primitive │ 1000000 │ ' 168 ms' │ ' 24 ms' │ ' 16 ms' │ ' 1.50 x' │ +│ Tuple_Object │ 1000000 │ ' 673 ms' │ ' 30 ms' │ ' 26 ms' │ ' 1.15 x' │ +│ Composite_Intersect │ 1000000 │ ' 751 ms' │ ' 28 ms' │ ' 20 ms' │ ' 1.40 x' │ +│ Composite_Union │ 1000000 │ ' 489 ms' │ ' 24 ms' │ ' 16 ms' │ ' 1.50 x' │ +│ Math_Vector4 │ 1000000 │ ' 259 ms' │ ' 23 ms' │ ' 13 ms' │ ' 1.77 x' │ +│ Math_Matrix4 │ 1000000 │ ' 1002 ms' │ ' 40 ms' │ ' 30 ms' │ ' 1.33 x' │ +│ Array_Primitive_Number │ 1000000 │ ' 252 ms' │ ' 22 ms' │ ' 15 ms' │ ' 1.47 x' │ +│ Array_Primitive_String │ 1000000 │ ' 227 ms' │ ' 22 ms' │ ' 18 ms' │ ' 1.22 x' │ +│ Array_Primitive_Boolean │ 1000000 │ ' 150 ms' │ ' 23 ms' │ ' 22 ms' │ ' 1.05 x' │ +│ Array_Object_Unconstrained │ 1000000 │ ' 4754 ms' │ ' 71 ms' │ ' 64 ms' │ ' 1.11 x' │ +│ Array_Object_Constrained │ 1000000 │ ' 4787 ms' │ ' 142 ms' │ ' 123 ms' │ ' 1.15 x' │ +│ Array_Object_Recursive │ 1000000 │ ' 19088 ms' │ ' 1735 ms' │ ' 314 ms' │ ' 5.53 x' │ +│ Array_Tuple_Primitive │ 1000000 │ ' 650 ms' │ ' 41 ms' │ ' 31 ms' │ ' 1.32 x' │ +│ Array_Tuple_Object │ 1000000 │ ' 2770 ms' │ ' 67 ms' │ ' 55 ms' │ ' 1.22 x' │ +│ Array_Composite_Intersect │ 1000000 │ ' 2693 ms' │ ' 50 ms' │ ' 39 ms' │ ' 1.28 x' │ +│ Array_Composite_Union │ 1000000 │ ' 1982 ms' │ ' 72 ms' │ ' 33 ms' │ ' 2.18 x' │ +│ Array_Math_Vector4 │ 1000000 │ ' 1068 ms' │ ' 40 ms' │ ' 26 ms' │ ' 1.54 x' │ +│ Array_Math_Matrix4 │ 1000000 │ ' 4609 ms' │ ' 115 ms' │ ' 88 ms' │ ' 1.31 x' │ +└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘ +``` + + + +### Compression + +The following table lists esbuild compiled and minified sizes for each TypeBox module. + +```typescript +┌──────────────────────┬────────────┬────────────┬─────────────┐ +│ (index) │ Compiled │ Minified │ Compression │ +├──────────────────────┼────────────┼────────────┼─────────────┤ +│ typebox/compiler │ '124.3 kb' │ ' 55.7 kb' │ '2.23 x' │ +│ typebox/errors │ '107.8 kb' │ ' 47.9 kb' │ '2.25 x' │ +│ typebox/system │ ' 73.3 kb' │ ' 30.2 kb' │ '2.43 x' │ +│ typebox/value │ '170.7 kb' │ ' 74.2 kb' │ '2.30 x' │ +│ typebox │ ' 72.0 kb' │ ' 29.7 kb' │ '2.43 x' │ +└──────────────────────┴────────────┴────────────┴─────────────┘ +``` + + + +## Contribute + +TypeBox is open to community contribution. Please ensure you submit an open issue before submitting your pull request. The TypeBox project preferences open community discussion prior to accepting new features. diff --git a/web/node_modules/@sinclair/typebox/system/index.d.ts b/web/node_modules/@sinclair/typebox/system/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b58cda6152954c6f7772fe557e3e765fe07fed5 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/system/index.d.ts @@ -0,0 +1 @@ +export * from './system'; diff --git a/web/node_modules/@sinclair/typebox/system/index.js b/web/node_modules/@sinclair/typebox/system/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3c5107f1943384c33415ac4defdd90afd4ca53b9 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/system/index.js @@ -0,0 +1,44 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/system + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +var __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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./system"), exports); diff --git a/web/node_modules/@sinclair/typebox/system/system.d.ts b/web/node_modules/@sinclair/typebox/system/system.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43084544c8a22842cef48ba438275c45cf58071f --- /dev/null +++ b/web/node_modules/@sinclair/typebox/system/system.d.ts @@ -0,0 +1,26 @@ +import * as Types from '../typebox'; +export declare class TypeSystemDuplicateTypeKind extends Error { + constructor(kind: string); +} +export declare class TypeSystemDuplicateFormat extends Error { + constructor(kind: string); +} +/** Creates user defined types and formats and provides overrides for value checking behaviours */ +export declare namespace TypeSystem { + /** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */ + let ExactOptionalPropertyTypes: boolean; + /** Sets whether arrays should be treated as a kind of objects. The default is `false` */ + let AllowArrayObjects: boolean; + /** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */ + let AllowNaN: boolean; + /** Sets whether `null` should validate for void types. The default is `false` */ + let AllowVoidNull: boolean; + /** Creates a new type */ + function Type(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial) => Types.TUnsafe; + /** Creates a new string format */ + function Format(format: F, check: (value: string) => boolean): F; + /** @deprecated Use `TypeSystem.Type()` instead. */ + function CreateType(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial) => Types.TUnsafe; + /** @deprecated Use `TypeSystem.Format()` instead. */ + function CreateFormat(format: F, check: (value: string) => boolean): F; +} diff --git a/web/node_modules/@sinclair/typebox/system/system.js b/web/node_modules/@sinclair/typebox/system/system.js new file mode 100644 index 0000000000000000000000000000000000000000..44911a48fcc1adfef2b210acb3754a5e4092f48b --- /dev/null +++ b/web/node_modules/@sinclair/typebox/system/system.js @@ -0,0 +1,90 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/system + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeSystem = exports.TypeSystemDuplicateFormat = exports.TypeSystemDuplicateTypeKind = void 0; +const Types = require("../typebox"); +class TypeSystemDuplicateTypeKind extends Error { + constructor(kind) { + super(`Duplicate type kind '${kind}' detected`); + } +} +exports.TypeSystemDuplicateTypeKind = TypeSystemDuplicateTypeKind; +class TypeSystemDuplicateFormat extends Error { + constructor(kind) { + super(`Duplicate string format '${kind}' detected`); + } +} +exports.TypeSystemDuplicateFormat = TypeSystemDuplicateFormat; +/** Creates user defined types and formats and provides overrides for value checking behaviours */ +var TypeSystem; +(function (TypeSystem) { + // ------------------------------------------------------------------------ + // Assertion Policies + // ------------------------------------------------------------------------ + /** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */ + TypeSystem.ExactOptionalPropertyTypes = false; + /** Sets whether arrays should be treated as a kind of objects. The default is `false` */ + TypeSystem.AllowArrayObjects = false; + /** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */ + TypeSystem.AllowNaN = false; + /** Sets whether `null` should validate for void types. The default is `false` */ + TypeSystem.AllowVoidNull = false; + // ------------------------------------------------------------------------ + // String Formats and Types + // ------------------------------------------------------------------------ + /** Creates a new type */ + function Type(kind, check) { + if (Types.TypeRegistry.Has(kind)) + throw new TypeSystemDuplicateTypeKind(kind); + Types.TypeRegistry.Set(kind, check); + return (options = {}) => Types.Type.Unsafe({ ...options, [Types.Kind]: kind }); + } + TypeSystem.Type = Type; + /** Creates a new string format */ + function Format(format, check) { + if (Types.FormatRegistry.Has(format)) + throw new TypeSystemDuplicateFormat(format); + Types.FormatRegistry.Set(format, check); + return format; + } + TypeSystem.Format = Format; + // ------------------------------------------------------------------------ + // Deprecated + // ------------------------------------------------------------------------ + /** @deprecated Use `TypeSystem.Type()` instead. */ + function CreateType(kind, check) { + return Type(kind, check); + } + TypeSystem.CreateType = CreateType; + /** @deprecated Use `TypeSystem.Format()` instead. */ + function CreateFormat(format, check) { + return Format(format, check); + } + TypeSystem.CreateFormat = CreateFormat; +})(TypeSystem = exports.TypeSystem || (exports.TypeSystem = {})); diff --git a/web/node_modules/@sinclair/typebox/typebox.d.ts b/web/node_modules/@sinclair/typebox/typebox.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1632b96586a0e1f6ba152909030cd27db5616a85 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/typebox.d.ts @@ -0,0 +1,723 @@ +export declare const Modifier: unique symbol; +export declare const Hint: unique symbol; +export declare const Kind: unique symbol; +export declare const PatternBoolean = "(true|false)"; +export declare const PatternNumber = "(0|[1-9][0-9]*)"; +export declare const PatternString = "(.*)"; +export declare const PatternBooleanExact: string; +export declare const PatternNumberExact: string; +export declare const PatternStringExact: string; +export type TupleToIntersect = T extends [infer I] ? I : T extends [infer I, ...infer R] ? I & TupleToIntersect : never; +export type TupleToUnion = { + [K in keyof T]: T[K]; +}[number]; +export type UnionToIntersect = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never; +export type UnionLast = UnionToIntersect 0 : never> extends (x: infer L) => 0 ? L : never; +export type UnionToTuple> = [U] extends [never] ? [] : [...UnionToTuple>, L]; +export type Assert = T extends E ? T : never; +export type Evaluate = T extends infer O ? { + [K in keyof O]: O[K]; +} : never; +export type Ensure = T extends infer U ? U : never; +export type TModifier = TReadonlyOptional | TOptional | TReadonly; +export type TReadonly = T & { + [Modifier]: 'Readonly'; +}; +export type TOptional = T & { + [Modifier]: 'Optional'; +}; +export type TReadonlyOptional = T & { + [Modifier]: 'ReadonlyOptional'; +}; +export interface SchemaOptions { + $schema?: string; + /** Id for this schema */ + $id?: string; + /** Title of this schema */ + title?: string; + /** Description of this schema */ + description?: string; + /** Default value for this schema */ + default?: any; + /** Example values matching this schema */ + examples?: any; + [prop: string]: any; +} +export interface TKind { + [Kind]: string; +} +export interface TSchema extends SchemaOptions, TKind { + [Modifier]?: string; + [Hint]?: string; + params: unknown[]; + static: unknown; +} +export type TAnySchema = TSchema | TAny | TArray | TBigInt | TBoolean | TConstructor | TDate | TEnum | TFunction | TInteger | TIntersect | TLiteral | TNot | TNull | TNumber | TObject | TPromise | TRecord | TRef | TString | TSymbol | TTemplateLiteral | TThis | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid; +export type TNumeric = TInteger | TNumber; +export interface NumericOptions extends SchemaOptions { + exclusiveMaximum?: N; + exclusiveMinimum?: N; + maximum?: N; + minimum?: N; + multipleOf?: N; +} +export interface TAny extends TSchema { + [Kind]: 'Any'; + static: any; +} +export interface ArrayOptions extends SchemaOptions { + uniqueItems?: boolean; + minItems?: number; + maxItems?: number; +} +export interface TArray extends TSchema, ArrayOptions { + [Kind]: 'Array'; + static: Static[]; + type: 'array'; + items: T; +} +export interface TBigInt extends TSchema, NumericOptions { + [Kind]: 'BigInt'; + static: bigint; + type: 'null'; + typeOf: 'BigInt'; +} +export interface TBoolean extends TSchema { + [Kind]: 'Boolean'; + static: boolean; + type: 'boolean'; +} +export type TConstructorParameters> = TTuple; +export type TInstanceType> = T['returns']; +export type TCompositeEvaluateArray = { + [K in keyof T]: T[K] extends TSchema ? Static : never; +}; +export type TCompositeArray = { + [K in keyof T]: T[K] extends TObject ? P : {}; +}; +export type TCompositeProperties = Evaluate : I extends object ? I : {}>; +export interface TComposite extends TObject { + [Hint]: 'Composite'; + static: Evaluate>>; + properties: TCompositeProperties>; +} +export type TConstructorParameterArray = [...{ + [K in keyof T]: Static, P>; +}]; +export interface TConstructor extends TSchema { + [Kind]: 'Constructor'; + static: new (...param: TConstructorParameterArray) => Static; + type: 'object'; + instanceOf: 'Constructor'; + parameters: T; + returns: U; +} +export interface DateOptions extends SchemaOptions { + exclusiveMaximumTimestamp?: number; + exclusiveMinimumTimestamp?: number; + maximumTimestamp?: number; + minimumTimestamp?: number; +} +export interface TDate extends TSchema, DateOptions { + [Kind]: 'Date'; + static: Date; + type: 'object'; + instanceOf: 'Date'; +} +export interface TEnumOption { + type: 'number' | 'string'; + const: T; +} +export interface TEnum = Record> extends TSchema { + [Kind]: 'Union'; + static: T[keyof T]; + anyOf: TLiteral[]; +} +export type TExtends = (Static extends Static ? T : U) extends infer O ? UnionToTuple extends [infer X, infer Y] ? TUnion<[Assert, Assert]> : Assert : never; +export type TExcludeTemplateLiteralResult = TUnionResult; +}[T]>, TSchema[]>>; +export type TExcludeTemplateLiteral = Exclude, Static> extends infer S ? TExcludeTemplateLiteralResult> : never; +export type TExcludeArray = Assert> extends Static ? never : T[K]; +}[number]>, TSchema[]> extends infer R ? TUnionResult> : never; +export type TExclude = T extends TTemplateLiteral ? TExcludeTemplateLiteral : T extends TUnion ? TExcludeArray : T extends U ? TNever : T; +export type TExtractTemplateLiteralResult = TUnionResult; +}[T]>, TSchema[]>>; +export type TExtractTemplateLiteral = Extract, Static> extends infer S ? TExtractTemplateLiteralResult> : never; +export type TExtractArray = Assert> extends Static ? T[K] : never; +}[number]>, TSchema[]> extends infer R ? TUnionResult> : never; +export type TExtract = T extends TTemplateLiteral ? TExtractTemplateLiteral : T extends TUnion ? TExtractArray : T extends U ? T : T; +export type TFunctionParameters = [...{ + [K in keyof T]: Static, P>; +}]; +export interface TFunction extends TSchema { + [Kind]: 'Function'; + static: (...param: TFunctionParameters) => Static; + type: 'object'; + instanceOf: 'Function'; + parameters: T; + returns: U; +} +export interface TInteger extends TSchema, NumericOptions { + [Kind]: 'Integer'; + static: number; + type: 'integer'; +} +export type TUnevaluatedProperties = undefined | TSchema | boolean; +export interface IntersectOptions extends SchemaOptions { + unevaluatedProperties?: TUnevaluatedProperties; +} +export interface TIntersect extends TSchema, IntersectOptions { + [Kind]: 'Intersect'; + static: TupleToIntersect<{ + [K in keyof T]: Static, this['params']>; + }>; + type?: 'object'; + allOf: [...T]; +} +export type TKeyOfTuple = { + [K in keyof Static]: TLiteral>; +} extends infer U ? UnionToTuple> : never; +export type TKeyOf = (T extends TRecursive ? TKeyOfTuple : T extends TComposite ? TKeyOfTuple : T extends TIntersect ? TKeyOfTuple : T extends TUnion ? TKeyOfTuple : T extends TObject ? TKeyOfTuple : T extends TRecord ? [K] : [ +]) extends infer R ? TUnionResult> : never; +export type TLiteralValue = string | number | boolean; +export interface TLiteral extends TSchema { + [Kind]: 'Literal'; + static: T; + const: T; +} +export interface TNever extends TSchema { + [Kind]: 'Never'; + static: never; + not: {}; +} +export interface TNot extends TSchema { + [Kind]: 'Not'; + static: Static; + allOf: [{ + not: Not; + }, T]; +} +export interface TNull extends TSchema { + [Kind]: 'Null'; + static: null; + type: 'null'; +} +export interface TNumber extends TSchema, NumericOptions { + [Kind]: 'Number'; + static: number; + type: 'number'; +} +export type ReadonlyOptionalPropertyKeys = { + [K in keyof T]: T[K] extends TReadonlyOptional ? K : never; +}[keyof T]; +export type ReadonlyPropertyKeys = { + [K in keyof T]: T[K] extends TReadonly ? K : never; +}[keyof T]; +export type OptionalPropertyKeys = { + [K in keyof T]: T[K] extends TOptional ? K : never; +}[keyof T]; +export type RequiredPropertyKeys = keyof Omit | ReadonlyPropertyKeys | OptionalPropertyKeys>; +export type PropertiesReducer> = Evaluate<(Readonly>>> & Readonly>> & Partial>> & Required>>)>; +export type PropertiesReduce = PropertiesReducer; +}>; +export type TProperties = Record; +export type ObjectProperties = T extends TObject ? U : never; +export type ObjectPropertyKeys = T extends TObject ? keyof U : never; +export type TAdditionalProperties = undefined | TSchema | boolean; +export interface ObjectOptions extends SchemaOptions { + additionalProperties?: TAdditionalProperties; + minProperties?: number; + maxProperties?: number; +} +export interface TObject extends TSchema, ObjectOptions { + [Kind]: 'Object'; + static: PropertiesReduce; + additionalProperties?: TAdditionalProperties; + type: 'object'; + properties: T; + required?: string[]; +} +export type TOmitArray = Assert<{ + [K2 in keyof T]: TOmit, K>; +}, TSchema[]>; +export type TOmitProperties = Evaluate, TProperties>>; +export type TOmit = T extends TRecursive ? TRecursive> : T extends TComposite ? TComposite> : T extends TIntersect ? TIntersect> : T extends TUnion ? TUnion> : T extends TObject ? TObject> : T; +export type TParameters = TTuple; +export type TPartialObjectArray = Assert<{ + [K in keyof T]: TPartial>; +}, TObject[]>; +export type TPartialArray = Assert<{ + [K in keyof T]: TPartial>; +}, TSchema[]>; +export type TPartialProperties = Evaluate ? TReadonlyOptional : T[K] extends TReadonly ? TReadonlyOptional : T[K] extends TOptional ? TOptional : TOptional; +}, TProperties>>; +export type TPartial = T extends TRecursive ? TRecursive> : T extends TComposite ? TComposite> : T extends TIntersect ? TIntersect> : T extends TUnion ? TUnion> : T extends TObject ? TObject> : T; +export type TPickArray = { + [K2 in keyof T]: TPick, K>; +}; +export type TPickProperties = Pick, keyof T>> extends infer R ? ({ + [K in keyof R]: Assert extends TSchema ? R[K] : never; +}) : never; +export type TPick = T extends TRecursive ? TRecursive> : T extends TComposite ? TComposite> : T extends TIntersect ? TIntersect> : T extends TUnion ? TUnion> : T extends TObject ? TObject> : T; +export interface TPromise extends TSchema { + [Kind]: 'Promise'; + static: Promise>; + type: 'object'; + instanceOf: 'Promise'; + item: TSchema; +} +export type RecordTemplateLiteralObjectType = Ensure]: T; +}>>>; +export type RecordTemplateLiteralType = IsTemplateLiteralFinite extends true ? RecordTemplateLiteralObjectType : TRecord; +export type RecordUnionLiteralType[]>, T extends TSchema> = Static extends string ? Ensure]: T; +}>> : never; +export type RecordLiteralType, T extends TSchema> = Ensure>; +export type RecordNumberType = Ensure>; +export type RecordStringType = Ensure>; +export type RecordKey = TUnion[]> | TLiteral | TTemplateLiteral | TInteger | TNumber | TString; +export interface TRecord extends TSchema { + [Kind]: 'Record'; + static: Record, Static>; + type: 'object'; + patternProperties: { + [pattern: string]: T; + }; + additionalProperties: false; +} +export interface TThis extends TSchema { + [Kind]: 'This'; + static: this['params'][0]; + $ref: string; +} +export type TRecursiveReduce = Static]>; +export interface TRecursive extends TSchema { + [Hint]: 'Recursive'; + static: TRecursiveReduce; +} +export interface TRef extends TSchema { + [Kind]: 'Ref'; + static: Static; + $ref: string; +} +export type TReturnType = T['returns']; +export type TRequiredArray = Assert<{ + [K in keyof T]: TRequired>; +}, TSchema[]>; +export type TRequiredProperties = Evaluate ? TReadonly : T[K] extends TReadonly ? TReadonly : T[K] extends TOptional ? U : T[K]; +}, TProperties>>; +export type TRequired = T extends TRecursive ? TRecursive> : T extends TComposite ? TComposite> : T extends TIntersect ? TIntersect> : T extends TUnion ? TUnion> : T extends TObject ? TObject> : T; +export type StringFormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex'; +export interface StringOptions extends SchemaOptions { + minLength?: number; + maxLength?: number; + pattern?: string; + format?: Format; + contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64'; + contentMediaType?: string; +} +export interface TString extends TSchema, StringOptions { + [Kind]: 'String'; + static: string; + type: 'string'; +} +export type SymbolValue = string | number | undefined; +export interface TSymbol extends TSchema, SchemaOptions { + [Kind]: 'Symbol'; + static: symbol; + type: 'null'; + typeOf: 'Symbol'; +} +export type IsTemplateLiteralFiniteCheck = T extends TTemplateLiteral ? IsTemplateLiteralFiniteArray> : T extends TUnion ? IsTemplateLiteralFiniteArray> : T extends TString ? false : T extends TBoolean ? false : T extends TNumber ? false : T extends TInteger ? false : T extends TBigInt ? false : T extends TLiteral ? true : false; +export type IsTemplateLiteralFiniteArray = T extends [infer L, ...infer R] ? IsTemplateLiteralFiniteCheck extends false ? false : IsTemplateLiteralFiniteArray> : T extends [infer L] ? IsTemplateLiteralFiniteCheck extends false ? false : true : true; +export type IsTemplateLiteralFinite = T extends TTemplateLiteral ? IsTemplateLiteralFiniteArray : false; +export type TTemplateLiteralKind = TUnion | TLiteral | TInteger | TTemplateLiteral | TNumber | TBigInt | TString | TBoolean | TNever; +export type TTemplateLiteralConst = T extends TUnion ? { + [K in keyof U]: TTemplateLiteralUnion, Acc>; +}[number] : T extends TTemplateLiteral ? `${Static}` : T extends TLiteral ? `${U}` : T extends TString ? `${string}` : T extends TNumber ? `${number}` : T extends TBigInt ? `${bigint}` : T extends TBoolean ? `${boolean}` : never; +export type TTemplateLiteralUnion = T extends [infer L, ...infer R] ? `${TTemplateLiteralConst}${TTemplateLiteralUnion, Acc>}` : T extends [infer L] ? `${TTemplateLiteralConst}${Acc}` : Acc; +export interface TTemplateLiteral extends TSchema { + [Kind]: 'TemplateLiteral'; + static: TTemplateLiteralUnion; + type: 'string'; + pattern: string; +} +export type TTupleIntoArray> = T extends TTuple ? Assert : never; +export interface TTuple extends TSchema { + [Kind]: 'Tuple'; + static: { + [K in keyof T]: T[K] extends TSchema ? Static : T[K]; + }; + type: 'array'; + items?: T; + additionalItems?: false; + minItems: number; + maxItems: number; +} +export interface TUndefined extends TSchema { + [Kind]: 'Undefined'; + static: undefined; + type: 'null'; + typeOf: 'Undefined'; +} +export type TUnionOfLiteralArray[]> = { + [K in keyof T]: Assert['const']; +}[number]; +export type TUnionOfLiteral[]>> = TUnionOfLiteralArray; +export type TUnionResult = T extends [] ? TNever : T extends [infer S] ? S : TUnion; +export type TUnionTemplateLiteral> = Ensure; +}[S]>, TLiteral[]>>>; +export interface TUnion extends TSchema { + [Kind]: 'Union'; + static: { + [K in keyof T]: T[K] extends TSchema ? Static : never; + }[number]; + anyOf: T; +} +export interface Uint8ArrayOptions extends SchemaOptions { + maxByteLength?: number; + minByteLength?: number; +} +export interface TUint8Array extends TSchema, Uint8ArrayOptions { + [Kind]: 'Uint8Array'; + static: Uint8Array; + instanceOf: 'Uint8Array'; + type: 'object'; +} +export interface TUnknown extends TSchema { + [Kind]: 'Unknown'; + static: unknown; +} +export interface UnsafeOptions extends SchemaOptions { + [Kind]?: string; +} +export interface TUnsafe extends TSchema { + [Kind]: string; + static: T; +} +export interface TVoid extends TSchema { + [Kind]: 'Void'; + static: void; + type: 'null'; + typeOf: 'Void'; +} +/** Creates a TypeScript static type from a TypeBox type */ +export type Static = (T & { + params: P; +})['static']; +export type TypeRegistryValidationFunction = (schema: TSchema, value: unknown) => boolean; +/** A registry for user defined types */ +export declare namespace TypeRegistry { + /** Returns the entries in this registry */ + function Entries(): Map>; + /** Clears all user defined types */ + function Clear(): void; + /** Returns true if this registry contains this kind */ + function Has(kind: string): boolean; + /** Sets a validation function for a user defined type */ + function Set(kind: string, func: TypeRegistryValidationFunction): void; + /** Gets a custom validation function for a user defined type */ + function Get(kind: string): TypeRegistryValidationFunction | undefined; +} +export type FormatRegistryValidationFunction = (value: string) => boolean; +/** A registry for user defined string formats */ +export declare namespace FormatRegistry { + /** Returns the entries in this registry */ + function Entries(): Map; + /** Clears all user defined string formats */ + function Clear(): void; + /** Returns true if the user defined string format exists */ + function Has(format: string): boolean; + /** Sets a validation function for a user defined string format */ + function Set(format: string, func: FormatRegistryValidationFunction): void; + /** Gets a validation function for a user defined string format */ + function Get(format: string): FormatRegistryValidationFunction | undefined; +} +export declare class TypeGuardUnknownTypeError extends Error { + readonly schema: unknown; + constructor(schema: unknown); +} +/** Provides functions to test if JavaScript values are TypeBox types */ +export declare namespace TypeGuard { + /** Returns true if the given schema is TAny */ + function TAny(schema: unknown): schema is TAny; + /** Returns true if the given schema is TArray */ + function TArray(schema: unknown): schema is TArray; + /** Returns true if the given schema is TBigInt */ + function TBigInt(schema: unknown): schema is TBigInt; + /** Returns true if the given schema is TBoolean */ + function TBoolean(schema: unknown): schema is TBoolean; + /** Returns true if the given schema is TConstructor */ + function TConstructor(schema: unknown): schema is TConstructor; + /** Returns true if the given schema is TDate */ + function TDate(schema: unknown): schema is TDate; + /** Returns true if the given schema is TFunction */ + function TFunction(schema: unknown): schema is TFunction; + /** Returns true if the given schema is TInteger */ + function TInteger(schema: unknown): schema is TInteger; + /** Returns true if the given schema is TIntersect */ + function TIntersect(schema: unknown): schema is TIntersect; + /** Returns true if the given schema is TKind */ + function TKind(schema: unknown): schema is Record; + /** Returns true if the given schema is TLiteral */ + function TLiteral(schema: unknown): schema is TLiteral; + /** Returns true if the given schema is TNever */ + function TNever(schema: unknown): schema is TNever; + /** Returns true if the given schema is TNot */ + function TNot(schema: unknown): schema is TNot; + /** Returns true if the given schema is TNull */ + function TNull(schema: unknown): schema is TNull; + /** Returns true if the given schema is TNumber */ + function TNumber(schema: unknown): schema is TNumber; + /** Returns true if the given schema is TObject */ + function TObject(schema: unknown): schema is TObject; + /** Returns true if the given schema is TPromise */ + function TPromise(schema: unknown): schema is TPromise; + /** Returns true if the given schema is TRecord */ + function TRecord(schema: unknown): schema is TRecord; + /** Returns true if the given schema is TRef */ + function TRef(schema: unknown): schema is TRef; + /** Returns true if the given schema is TString */ + function TString(schema: unknown): schema is TString; + /** Returns true if the given schema is TSymbol */ + function TSymbol(schema: unknown): schema is TSymbol; + /** Returns true if the given schema is TTemplateLiteral */ + function TTemplateLiteral(schema: unknown): schema is TTemplateLiteral; + /** Returns true if the given schema is TThis */ + function TThis(schema: unknown): schema is TThis; + /** Returns true if the given schema is TTuple */ + function TTuple(schema: unknown): schema is TTuple; + /** Returns true if the given schema is TUndefined */ + function TUndefined(schema: unknown): schema is TUndefined; + /** Returns true if the given schema is TUnion */ + function TUnion(schema: unknown): schema is TUnion; + /** Returns true if the given schema is TUnion[]> */ + function TUnionLiteral(schema: unknown): schema is TUnion[]>; + /** Returns true if the given schema is TUint8Array */ + function TUint8Array(schema: unknown): schema is TUint8Array; + /** Returns true if the given schema is TUnknown */ + function TUnknown(schema: unknown): schema is TUnknown; + /** Returns true if the given schema is a raw TUnsafe */ + function TUnsafe(schema: unknown): schema is TUnsafe; + /** Returns true if the given schema is TVoid */ + function TVoid(schema: unknown): schema is TVoid; + /** Returns true if this schema has the ReadonlyOptional modifier */ + function TReadonlyOptional(schema: T): schema is TReadonlyOptional; + /** Returns true if this schema has the Readonly modifier */ + function TReadonly(schema: T): schema is TReadonly; + /** Returns true if this schema has the Optional modifier */ + function TOptional(schema: T): schema is TOptional; + /** Returns true if the given schema is TSchema */ + function TSchema(schema: unknown): schema is TSchema; +} +/** Fast undefined check used for properties of type undefined */ +export declare namespace ExtendsUndefined { + function Check(schema: TSchema): boolean; +} +export declare enum TypeExtendsResult { + Union = 0, + True = 1, + False = 2 +} +export declare namespace TypeExtends { + function Extends(left: TSchema, right: TSchema): TypeExtendsResult; +} +/** Specialized Clone for Types */ +export declare namespace TypeClone { + /** Clones a type. */ + function Clone(schema: T, options: SchemaOptions): T; +} +export declare namespace ObjectMap { + function Map(schema: TSchema, callback: (object: TObject) => TObject, options: SchemaOptions): T; +} +export declare namespace KeyResolver { + function Resolve(schema: T): string[]; +} +export declare namespace TemplateLiteralPattern { + function Create(kinds: TTemplateLiteralKind[]): string; +} +export declare namespace TemplateLiteralResolver { + function Resolve(template: TTemplateLiteral): TString | TUnion | TLiteral; +} +export declare class TemplateLiteralParserError extends Error { + constructor(message: string); +} +export declare namespace TemplateLiteralParser { + type Expression = And | Or | Const; + type Const = { + type: 'const'; + const: string; + }; + type And = { + type: 'and'; + expr: Expression[]; + }; + type Or = { + type: 'or'; + expr: Expression[]; + }; + /** Parses a pattern and returns an expression tree */ + function Parse(pattern: string): Expression; + /** Parses a pattern and strips forward and trailing ^ and $ */ + function ParseExact(pattern: string): Expression; +} +export declare namespace TemplateLiteralFinite { + function Check(expression: TemplateLiteralParser.Expression): boolean; +} +export declare namespace TemplateLiteralGenerator { + function Generate(expression: TemplateLiteralParser.Expression): IterableIterator; +} +export declare class TypeBuilder { + /** `[Utility]` Creates a schema without `static` and `params` types */ + protected Create(schema: Omit): T; + /** `[Standard]` Omits compositing symbols from this schema */ + Strict(schema: T): T; +} +export declare class StandardTypeBuilder extends TypeBuilder { + /** `[Modifier]` Creates a Optional property */ + Optional(schema: T): TOptional; + /** `[Modifier]` Creates a ReadonlyOptional property */ + ReadonlyOptional(schema: T): TReadonlyOptional; + /** `[Modifier]` Creates a Readonly object or property */ + Readonly(schema: T): TReadonly; + /** `[Standard]` Creates an Any type */ + Any(options?: SchemaOptions): TAny; + /** `[Standard]` Creates an Array type */ + Array(items: T, options?: ArrayOptions): TArray; + /** `[Standard]` Creates a Boolean type */ + Boolean(options?: SchemaOptions): TBoolean; + /** `[Standard]` Creates a Composite object type. */ + Composite(objects: [...T], options?: ObjectOptions): TComposite; + /** `[Standard]` Creates a Enum type */ + Enum>(item: T, options?: SchemaOptions): TEnum; + /** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */ + Extends(left: L, right: R, trueType: T, falseType: U, options?: SchemaOptions): TExtends; + /** `[Standard]` Excludes from the left type any type that is not assignable to the right */ + Exclude(left: L, right: R, options?: SchemaOptions): TExclude; + /** `[Standard]` Extracts from the left type any type that is assignable to the right */ + Extract(left: L, right: R, options?: SchemaOptions): TExtract; + /** `[Standard]` Creates an Integer type */ + Integer(options?: NumericOptions): TInteger; + /** `[Standard]` Creates a Intersect type */ + Intersect(allOf: [], options?: SchemaOptions): TNever; + /** `[Standard]` Creates a Intersect type */ + Intersect(allOf: [...T], options?: SchemaOptions): T[0]; + Intersect(allOf: [...T], options?: IntersectOptions): TIntersect; + /** `[Standard]` Creates a KeyOf type */ + KeyOf(schema: T, options?: SchemaOptions): TKeyOf; + /** `[Standard]` Creates a Literal type */ + Literal(value: T, options?: SchemaOptions): TLiteral; + /** `[Standard]` Creates a Never type */ + Never(options?: SchemaOptions): TNever; + /** `[Standard]` Creates a Not type. The first argument is the disallowed type, the second is the allowed. */ + Not(not: N, schema: T, options?: SchemaOptions): TNot; + /** `[Standard]` Creates a Null type */ + Null(options?: SchemaOptions): TNull; + /** `[Standard]` Creates a Number type */ + Number(options?: NumericOptions): TNumber; + /** `[Standard]` Creates an Object type */ + Object(properties: T, options?: ObjectOptions): TObject; + /** `[Standard]` Creates a mapped type whose keys are omitted from the given type */ + Omit)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TOmit; + /** `[Standard]` Creates a mapped type whose keys are omitted from the given type */ + Omit[]>>(schema: T, keys: K, options?: SchemaOptions): TOmit>; + /** `[Standard]` Creates a mapped type whose keys are omitted from the given type */ + Omit>(schema: T, key: K, options?: SchemaOptions): TOmit; + /** `[Standard]` Creates a mapped type whose keys are omitted from the given type */ + Omit(schema: T, key: K, options?: SchemaOptions): TOmit; + /** `[Standard]` Creates a mapped type where all properties are Optional */ + Partial(schema: T, options?: ObjectOptions): TPartial; + /** `[Standard]` Creates a mapped type whose keys are picked from the given type */ + Pick)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TPick; + /** `[Standard]` Creates a mapped type whose keys are picked from the given type */ + Pick[]>>(schema: T, keys: K, options?: SchemaOptions): TPick>; + /** `[Standard]` Creates a mapped type whose keys are picked from the given type */ + Pick>(schema: T, key: K, options?: SchemaOptions): TPick; + /** `[Standard]` Creates a mapped type whose keys are picked from the given type */ + Pick(schema: T, key: K, options?: SchemaOptions): TPick; + /** `[Standard]` Creates a Record type */ + Record[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordUnionLiteralType; + /** `[Standard]` Creates a Record type */ + Record, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordLiteralType; + /** `[Standard]` Creates a Record type */ + Record(key: K, schema: T, options?: ObjectOptions): RecordTemplateLiteralType; + /** `[Standard]` Creates a Record type */ + Record(key: K, schema: T, options?: ObjectOptions): RecordNumberType; + /** `[Standard]` Creates a Record type */ + Record(key: K, schema: T, options?: ObjectOptions): RecordStringType; + /** `[Standard]` Creates a Recursive type */ + Recursive(callback: (thisType: TThis) => T, options?: SchemaOptions): TRecursive; + /** `[Standard]` Creates a Ref type. The referenced type must contain a $id */ + Ref(schema: T, options?: SchemaOptions): TRef; + /** `[Standard]` Creates a mapped type where all properties are Required */ + Required(schema: T, options?: SchemaOptions): TRequired; + /** `[Standard]` Creates a String type */ + String(options?: StringOptions): TString; + /** `[Standard]` Creates a template literal type */ + TemplateLiteral(kinds: [...T], options?: SchemaOptions): TTemplateLiteral; + /** `[Standard]` Creates a Tuple type */ + Tuple(items: [...T], options?: SchemaOptions): TTuple; + /** `[Standard]` Creates a Union type */ + Union(anyOf: [], options?: SchemaOptions): TNever; + /** `[Standard]` Creates a Union type */ + Union(anyOf: [...T], options?: SchemaOptions): T[0]; + /** `[Standard]` Creates a Union type */ + Union(anyOf: [...T], options?: SchemaOptions): TUnion; + /** `[Experimental]` Remaps a TemplateLiteral into a Union representation. This function is known to cause TS compiler crashes for finite templates with large generation counts. Use with caution. */ + Union(template: T): TUnionTemplateLiteral; + /** `[Standard]` Creates an Unknown type */ + Unknown(options?: SchemaOptions): TUnknown; + /** `[Standard]` Creates a Unsafe type that infers for the generic argument */ + Unsafe(options?: UnsafeOptions): TUnsafe; +} +export declare class ExtendedTypeBuilder extends StandardTypeBuilder { + /** `[Extended]` Creates a BigInt type */ + BigInt(options?: NumericOptions): TBigInt; + /** `[Extended]` Extracts the ConstructorParameters from the given Constructor type */ + ConstructorParameters>(schema: T, options?: SchemaOptions): TConstructorParameters; + /** `[Extended]` Creates a Constructor type */ + Constructor, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor, U>; + /** `[Extended]` Creates a Constructor type */ + Constructor(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor; + /** `[Extended]` Creates a Date type */ + Date(options?: DateOptions): TDate; + /** `[Extended]` Creates a Function type */ + Function, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction, U>; + /** `[Extended]` Creates a Function type */ + Function(parameters: [...T], returns: U, options?: SchemaOptions): TFunction; + /** `[Extended]` Extracts the InstanceType from the given Constructor */ + InstanceType>(schema: T, options?: SchemaOptions): TInstanceType; + /** `[Extended]` Extracts the Parameters from the given Function type */ + Parameters>(schema: T, options?: SchemaOptions): TParameters; + /** `[Extended]` Creates a Promise type */ + Promise(item: T, options?: SchemaOptions): TPromise; + /** `[Extended]` Creates a regular expression type */ + RegEx(regex: RegExp, options?: SchemaOptions): TString; + /** `[Extended]` Extracts the ReturnType from the given Function */ + ReturnType>(schema: T, options?: SchemaOptions): TReturnType; + /** `[Extended]` Creates a Symbol type */ + Symbol(options?: SchemaOptions): TSymbol; + /** `[Extended]` Creates a Undefined type */ + Undefined(options?: SchemaOptions): TUndefined; + /** `[Extended]` Creates a Uint8Array type */ + Uint8Array(options?: Uint8ArrayOptions): TUint8Array; + /** `[Extended]` Creates a Void type */ + Void(options?: SchemaOptions): TVoid; +} +/** JSON Schema TypeBuilder with Static Resolution for TypeScript */ +export declare const StandardType: StandardTypeBuilder; +/** JSON Schema TypeBuilder with Static Resolution for TypeScript */ +export declare const Type: ExtendedTypeBuilder; diff --git a/web/node_modules/@sinclair/typebox/typebox.js b/web/node_modules/@sinclair/typebox/typebox.js new file mode 100644 index 0000000000000000000000000000000000000000..c8953c35dbab0004a3c3900959d532441b02904b --- /dev/null +++ b/web/node_modules/@sinclair/typebox/typebox.js @@ -0,0 +1,2220 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Type = exports.StandardType = exports.ExtendedTypeBuilder = exports.StandardTypeBuilder = exports.TypeBuilder = exports.TemplateLiteralGenerator = exports.TemplateLiteralFinite = exports.TemplateLiteralParser = exports.TemplateLiteralParserError = exports.TemplateLiteralResolver = exports.TemplateLiteralPattern = exports.KeyResolver = exports.ObjectMap = exports.TypeClone = exports.TypeExtends = exports.TypeExtendsResult = exports.ExtendsUndefined = exports.TypeGuard = exports.TypeGuardUnknownTypeError = exports.FormatRegistry = exports.TypeRegistry = exports.PatternStringExact = exports.PatternNumberExact = exports.PatternBooleanExact = exports.PatternString = exports.PatternNumber = exports.PatternBoolean = exports.Kind = exports.Hint = exports.Modifier = void 0; +// -------------------------------------------------------------------------- +// Symbols +// -------------------------------------------------------------------------- +exports.Modifier = Symbol.for('TypeBox.Modifier'); +exports.Hint = Symbol.for('TypeBox.Hint'); +exports.Kind = Symbol.for('TypeBox.Kind'); +// -------------------------------------------------------------------------- +// Patterns +// -------------------------------------------------------------------------- +exports.PatternBoolean = '(true|false)'; +exports.PatternNumber = '(0|[1-9][0-9]*)'; +exports.PatternString = '(.*)'; +exports.PatternBooleanExact = `^${exports.PatternBoolean}$`; +exports.PatternNumberExact = `^${exports.PatternNumber}$`; +exports.PatternStringExact = `^${exports.PatternString}$`; +/** A registry for user defined types */ +var TypeRegistry; +(function (TypeRegistry) { + const map = new Map(); + /** Returns the entries in this registry */ + function Entries() { + return new Map(map); + } + TypeRegistry.Entries = Entries; + /** Clears all user defined types */ + function Clear() { + return map.clear(); + } + TypeRegistry.Clear = Clear; + /** Returns true if this registry contains this kind */ + function Has(kind) { + return map.has(kind); + } + TypeRegistry.Has = Has; + /** Sets a validation function for a user defined type */ + function Set(kind, func) { + map.set(kind, func); + } + TypeRegistry.Set = Set; + /** Gets a custom validation function for a user defined type */ + function Get(kind) { + return map.get(kind); + } + TypeRegistry.Get = Get; +})(TypeRegistry = exports.TypeRegistry || (exports.TypeRegistry = {})); +/** A registry for user defined string formats */ +var FormatRegistry; +(function (FormatRegistry) { + const map = new Map(); + /** Returns the entries in this registry */ + function Entries() { + return new Map(map); + } + FormatRegistry.Entries = Entries; + /** Clears all user defined string formats */ + function Clear() { + return map.clear(); + } + FormatRegistry.Clear = Clear; + /** Returns true if the user defined string format exists */ + function Has(format) { + return map.has(format); + } + FormatRegistry.Has = Has; + /** Sets a validation function for a user defined string format */ + function Set(format, func) { + map.set(format, func); + } + FormatRegistry.Set = Set; + /** Gets a validation function for a user defined string format */ + function Get(format) { + return map.get(format); + } + FormatRegistry.Get = Get; +})(FormatRegistry = exports.FormatRegistry || (exports.FormatRegistry = {})); +// -------------------------------------------------------------------------- +// TypeGuard +// -------------------------------------------------------------------------- +class TypeGuardUnknownTypeError extends Error { + constructor(schema) { + super('TypeGuard: Unknown type'); + this.schema = schema; + } +} +exports.TypeGuardUnknownTypeError = TypeGuardUnknownTypeError; +/** Provides functions to test if JavaScript values are TypeBox types */ +var TypeGuard; +(function (TypeGuard) { + function IsObject(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); + } + function IsArray(value) { + return typeof value === 'object' && value !== null && Array.isArray(value); + } + function IsPattern(value) { + try { + new RegExp(value); + return true; + } + catch { + return false; + } + } + function IsControlCharacterFree(value) { + if (typeof value !== 'string') + return false; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if ((code >= 7 && code <= 13) || code === 27 || code === 127) { + return false; + } + } + return true; + } + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsString(value) { + return typeof value === 'string'; + } + function IsNumber(value) { + return typeof value === 'number' && globalThis.Number.isFinite(value); + } + function IsBoolean(value) { + return typeof value === 'boolean'; + } + function IsOptionalBigInt(value) { + return value === undefined || (value !== undefined && IsBigInt(value)); + } + function IsOptionalNumber(value) { + return value === undefined || (value !== undefined && IsNumber(value)); + } + function IsOptionalBoolean(value) { + return value === undefined || (value !== undefined && IsBoolean(value)); + } + function IsOptionalString(value) { + return value === undefined || (value !== undefined && IsString(value)); + } + function IsOptionalPattern(value) { + return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value)); + } + function IsOptionalFormat(value) { + return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value)); + } + function IsOptionalSchema(value) { + return value === undefined || TSchema(value); + } + /** Returns true if the given schema is TAny */ + function TAny(schema) { + return TKind(schema) && schema[exports.Kind] === 'Any' && IsOptionalString(schema.$id); + } + TypeGuard.TAny = TAny; + /** Returns true if the given schema is TArray */ + function TArray(schema) { + return (TKind(schema) && + schema[exports.Kind] === 'Array' && + schema.type === 'array' && + IsOptionalString(schema.$id) && + TSchema(schema.items) && + IsOptionalNumber(schema.minItems) && + IsOptionalNumber(schema.maxItems) && + IsOptionalBoolean(schema.uniqueItems)); + } + TypeGuard.TArray = TArray; + /** Returns true if the given schema is TBigInt */ + function TBigInt(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'BigInt' && + schema.type === 'null' && + schema.typeOf === 'BigInt' && + IsOptionalString(schema.$id) && + IsOptionalBigInt(schema.multipleOf) && + IsOptionalBigInt(schema.minimum) && + IsOptionalBigInt(schema.maximum) && + IsOptionalBigInt(schema.exclusiveMinimum) && + IsOptionalBigInt(schema.exclusiveMaximum)); + } + TypeGuard.TBigInt = TBigInt; + /** Returns true if the given schema is TBoolean */ + function TBoolean(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Boolean' && + schema.type === 'boolean' && + IsOptionalString(schema.$id)); + } + TypeGuard.TBoolean = TBoolean; + /** Returns true if the given schema is TConstructor */ + function TConstructor(schema) { + // prettier-ignore + if (!(TKind(schema) && + schema[exports.Kind] === 'Constructor' && + schema.type === 'object' && + schema.instanceOf === 'Constructor' && + IsOptionalString(schema.$id) && + IsArray(schema.parameters) && + TSchema(schema.returns))) { + return false; + } + for (const parameter of schema.parameters) { + if (!TSchema(parameter)) + return false; + } + return true; + } + TypeGuard.TConstructor = TConstructor; + /** Returns true if the given schema is TDate */ + function TDate(schema) { + return (TKind(schema) && + schema[exports.Kind] === 'Date' && + schema.type === 'object' && + schema.instanceOf === 'Date' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.minimumTimestamp) && + IsOptionalNumber(schema.maximumTimestamp) && + IsOptionalNumber(schema.exclusiveMinimumTimestamp) && + IsOptionalNumber(schema.exclusiveMaximumTimestamp)); + } + TypeGuard.TDate = TDate; + /** Returns true if the given schema is TFunction */ + function TFunction(schema) { + // prettier-ignore + if (!(TKind(schema) && + schema[exports.Kind] === 'Function' && + schema.type === 'object' && + schema.instanceOf === 'Function' && + IsOptionalString(schema.$id) && + IsArray(schema.parameters) && + TSchema(schema.returns))) { + return false; + } + for (const parameter of schema.parameters) { + if (!TSchema(parameter)) + return false; + } + return true; + } + TypeGuard.TFunction = TFunction; + /** Returns true if the given schema is TInteger */ + function TInteger(schema) { + return (TKind(schema) && + schema[exports.Kind] === 'Integer' && + schema.type === 'integer' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.multipleOf) && + IsOptionalNumber(schema.minimum) && + IsOptionalNumber(schema.maximum) && + IsOptionalNumber(schema.exclusiveMinimum) && + IsOptionalNumber(schema.exclusiveMaximum)); + } + TypeGuard.TInteger = TInteger; + /** Returns true if the given schema is TIntersect */ + function TIntersect(schema) { + // prettier-ignore + if (!(TKind(schema) && + schema[exports.Kind] === 'Intersect' && + IsArray(schema.allOf) && + IsOptionalString(schema.type) && + (IsOptionalBoolean(schema.unevaluatedProperties) || IsOptionalSchema(schema.unevaluatedProperties)) && + IsOptionalString(schema.$id))) { + return false; + } + if ('type' in schema && schema.type !== 'object') { + return false; + } + for (const inner of schema.allOf) { + if (!TSchema(inner)) + return false; + } + return true; + } + TypeGuard.TIntersect = TIntersect; + /** Returns true if the given schema is TKind */ + function TKind(schema) { + return IsObject(schema) && exports.Kind in schema && typeof schema[exports.Kind] === 'string'; // TS 4.1.5: any required for symbol indexer + } + TypeGuard.TKind = TKind; + /** Returns true if the given schema is TLiteral */ + function TLiteral(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Literal' && + IsOptionalString(schema.$id) && + (IsString(schema.const) || + IsNumber(schema.const) || + IsBoolean(schema.const) || + IsBigInt(schema.const))); + } + TypeGuard.TLiteral = TLiteral; + /** Returns true if the given schema is TNever */ + function TNever(schema) { + return TKind(schema) && schema[exports.Kind] === 'Never' && IsObject(schema.not) && globalThis.Object.getOwnPropertyNames(schema.not).length === 0; + } + TypeGuard.TNever = TNever; + /** Returns true if the given schema is TNot */ + function TNot(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Not' && + IsArray(schema.allOf) && + schema.allOf.length === 2 && + IsObject(schema.allOf[0]) && + TSchema(schema.allOf[0].not) && + TSchema(schema.allOf[1])); + } + TypeGuard.TNot = TNot; + /** Returns true if the given schema is TNull */ + function TNull(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Null' && + schema.type === 'null' && + IsOptionalString(schema.$id)); + } + TypeGuard.TNull = TNull; + /** Returns true if the given schema is TNumber */ + function TNumber(schema) { + return (TKind(schema) && + schema[exports.Kind] === 'Number' && + schema.type === 'number' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.multipleOf) && + IsOptionalNumber(schema.minimum) && + IsOptionalNumber(schema.maximum) && + IsOptionalNumber(schema.exclusiveMinimum) && + IsOptionalNumber(schema.exclusiveMaximum)); + } + TypeGuard.TNumber = TNumber; + /** Returns true if the given schema is TObject */ + function TObject(schema) { + if (!(TKind(schema) && + schema[exports.Kind] === 'Object' && + schema.type === 'object' && + IsOptionalString(schema.$id) && + IsObject(schema.properties) && + (IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) && + IsOptionalNumber(schema.minProperties) && + IsOptionalNumber(schema.maxProperties))) { + return false; + } + for (const [key, value] of Object.entries(schema.properties)) { + if (!IsControlCharacterFree(key)) + return false; + if (!TSchema(value)) + return false; + } + return true; + } + TypeGuard.TObject = TObject; + /** Returns true if the given schema is TPromise */ + function TPromise(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Promise' && + schema.type === 'object' && + schema.instanceOf === 'Promise' && + IsOptionalString(schema.$id) && + TSchema(schema.item)); + } + TypeGuard.TPromise = TPromise; + /** Returns true if the given schema is TRecord */ + function TRecord(schema) { + // prettier-ignore + if (!(TKind(schema) && + schema[exports.Kind] === 'Record' && + schema.type === 'object' && + IsOptionalString(schema.$id) && + schema.additionalProperties === false && + IsObject(schema.patternProperties))) { + return false; + } + const keys = Object.keys(schema.patternProperties); + if (keys.length !== 1) { + return false; + } + if (!IsPattern(keys[0])) { + return false; + } + if (!TSchema(schema.patternProperties[keys[0]])) { + return false; + } + return true; + } + TypeGuard.TRecord = TRecord; + /** Returns true if the given schema is TRef */ + function TRef(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Ref' && + IsOptionalString(schema.$id) && + IsString(schema.$ref)); + } + TypeGuard.TRef = TRef; + /** Returns true if the given schema is TString */ + function TString(schema) { + return (TKind(schema) && + schema[exports.Kind] === 'String' && + schema.type === 'string' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.minLength) && + IsOptionalNumber(schema.maxLength) && + IsOptionalPattern(schema.pattern) && + IsOptionalFormat(schema.format)); + } + TypeGuard.TString = TString; + /** Returns true if the given schema is TSymbol */ + function TSymbol(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Symbol' && + schema.type === 'null' && + schema.typeOf === 'Symbol' && + IsOptionalString(schema.$id)); + } + TypeGuard.TSymbol = TSymbol; + /** Returns true if the given schema is TTemplateLiteral */ + function TTemplateLiteral(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'TemplateLiteral' && + schema.type === 'string' && + IsString(schema.pattern) && + schema.pattern[0] === '^' && + schema.pattern[schema.pattern.length - 1] === '$'); + } + TypeGuard.TTemplateLiteral = TTemplateLiteral; + /** Returns true if the given schema is TThis */ + function TThis(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'This' && + IsOptionalString(schema.$id) && + IsString(schema.$ref)); + } + TypeGuard.TThis = TThis; + /** Returns true if the given schema is TTuple */ + function TTuple(schema) { + // prettier-ignore + if (!(TKind(schema) && + schema[exports.Kind] === 'Tuple' && + schema.type === 'array' && + IsOptionalString(schema.$id) && + IsNumber(schema.minItems) && + IsNumber(schema.maxItems) && + schema.minItems === schema.maxItems)) { + return false; + } + if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) { + return true; + } + if (!IsArray(schema.items)) { + return false; + } + for (const inner of schema.items) { + if (!TSchema(inner)) + return false; + } + return true; + } + TypeGuard.TTuple = TTuple; + /** Returns true if the given schema is TUndefined */ + function TUndefined(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Undefined' && + schema.type === 'null' && + schema.typeOf === 'Undefined' && + IsOptionalString(schema.$id)); + } + TypeGuard.TUndefined = TUndefined; + /** Returns true if the given schema is TUnion */ + function TUnion(schema) { + // prettier-ignore + if (!(TKind(schema) && + schema[exports.Kind] === 'Union' && + IsArray(schema.anyOf) && + IsOptionalString(schema.$id))) { + return false; + } + for (const inner of schema.anyOf) { + if (!TSchema(inner)) + return false; + } + return true; + } + TypeGuard.TUnion = TUnion; + /** Returns true if the given schema is TUnion[]> */ + function TUnionLiteral(schema) { + return TUnion(schema) && schema.anyOf.every((schema) => TLiteral(schema) && typeof schema.const === 'string'); + } + TypeGuard.TUnionLiteral = TUnionLiteral; + /** Returns true if the given schema is TUint8Array */ + function TUint8Array(schema) { + return TKind(schema) && schema[exports.Kind] === 'Uint8Array' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.instanceOf === 'Uint8Array' && IsOptionalNumber(schema.minByteLength) && IsOptionalNumber(schema.maxByteLength); + } + TypeGuard.TUint8Array = TUint8Array; + /** Returns true if the given schema is TUnknown */ + function TUnknown(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Unknown' && + IsOptionalString(schema.$id)); + } + TypeGuard.TUnknown = TUnknown; + /** Returns true if the given schema is a raw TUnsafe */ + function TUnsafe(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Unsafe'); + } + TypeGuard.TUnsafe = TUnsafe; + /** Returns true if the given schema is TVoid */ + function TVoid(schema) { + // prettier-ignore + return (TKind(schema) && + schema[exports.Kind] === 'Void' && + schema.type === 'null' && + schema.typeOf === 'Void' && + IsOptionalString(schema.$id)); + } + TypeGuard.TVoid = TVoid; + /** Returns true if this schema has the ReadonlyOptional modifier */ + function TReadonlyOptional(schema) { + return IsObject(schema) && schema[exports.Modifier] === 'ReadonlyOptional'; + } + TypeGuard.TReadonlyOptional = TReadonlyOptional; + /** Returns true if this schema has the Readonly modifier */ + function TReadonly(schema) { + return IsObject(schema) && schema[exports.Modifier] === 'Readonly'; + } + TypeGuard.TReadonly = TReadonly; + /** Returns true if this schema has the Optional modifier */ + function TOptional(schema) { + return IsObject(schema) && schema[exports.Modifier] === 'Optional'; + } + TypeGuard.TOptional = TOptional; + /** Returns true if the given schema is TSchema */ + function TSchema(schema) { + return (typeof schema === 'object' && + (TAny(schema) || + TArray(schema) || + TBoolean(schema) || + TBigInt(schema) || + TConstructor(schema) || + TDate(schema) || + TFunction(schema) || + TInteger(schema) || + TIntersect(schema) || + TLiteral(schema) || + TNever(schema) || + TNot(schema) || + TNull(schema) || + TNumber(schema) || + TObject(schema) || + TPromise(schema) || + TRecord(schema) || + TRef(schema) || + TString(schema) || + TSymbol(schema) || + TTemplateLiteral(schema) || + TThis(schema) || + TTuple(schema) || + TUndefined(schema) || + TUnion(schema) || + TUint8Array(schema) || + TUnknown(schema) || + TUnsafe(schema) || + TVoid(schema) || + (TKind(schema) && TypeRegistry.Has(schema[exports.Kind])))); + } + TypeGuard.TSchema = TSchema; +})(TypeGuard = exports.TypeGuard || (exports.TypeGuard = {})); +// -------------------------------------------------------------------------- +// ExtendsUndefined +// -------------------------------------------------------------------------- +/** Fast undefined check used for properties of type undefined */ +var ExtendsUndefined; +(function (ExtendsUndefined) { + function Check(schema) { + if (schema[exports.Kind] === 'Undefined') + return true; + if (schema[exports.Kind] === 'Union') { + const union = schema; + return union.anyOf.some((schema) => Check(schema)); + } + return false; + } + ExtendsUndefined.Check = Check; +})(ExtendsUndefined = exports.ExtendsUndefined || (exports.ExtendsUndefined = {})); +// -------------------------------------------------------------------------- +// TypeExtends +// -------------------------------------------------------------------------- +var TypeExtendsResult; +(function (TypeExtendsResult) { + TypeExtendsResult[TypeExtendsResult["Union"] = 0] = "Union"; + TypeExtendsResult[TypeExtendsResult["True"] = 1] = "True"; + TypeExtendsResult[TypeExtendsResult["False"] = 2] = "False"; +})(TypeExtendsResult = exports.TypeExtendsResult || (exports.TypeExtendsResult = {})); +var TypeExtends; +(function (TypeExtends) { + // -------------------------------------------------------------------------- + // IntoBooleanResult + // -------------------------------------------------------------------------- + function IntoBooleanResult(result) { + return result === TypeExtendsResult.False ? TypeExtendsResult.False : TypeExtendsResult.True; + } + // -------------------------------------------------------------------------- + // Any + // -------------------------------------------------------------------------- + function AnyRight(left, right) { + return TypeExtendsResult.True; + } + function Any(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right) && right.anyOf.some((schema) => TypeGuard.TAny(schema) || TypeGuard.TUnknown(schema))) + return TypeExtendsResult.True; + if (TypeGuard.TUnion(right)) + return TypeExtendsResult.Union; + if (TypeGuard.TUnknown(right)) + return TypeExtendsResult.True; + if (TypeGuard.TAny(right)) + return TypeExtendsResult.True; + return TypeExtendsResult.Union; + } + // -------------------------------------------------------------------------- + // Array + // -------------------------------------------------------------------------- + function ArrayRight(left, right) { + if (TypeGuard.TUnknown(left)) + return TypeExtendsResult.False; + if (TypeGuard.TAny(left)) + return TypeExtendsResult.Union; + if (TypeGuard.TNever(left)) + return TypeExtendsResult.True; + return TypeExtendsResult.False; + } + function Array(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right) && IsObjectArrayLike(right)) + return TypeExtendsResult.True; + if (!TypeGuard.TArray(right)) + return TypeExtendsResult.False; + return IntoBooleanResult(Visit(left.items, right.items)); + } + // -------------------------------------------------------------------------- + // BigInt + // -------------------------------------------------------------------------- + function BigInt(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TBigInt(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Boolean + // -------------------------------------------------------------------------- + function BooleanRight(left, right) { + if (TypeGuard.TLiteral(left) && typeof left.const === 'boolean') + return TypeExtendsResult.True; + return TypeGuard.TBoolean(left) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Boolean(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TBoolean(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Constructor + // -------------------------------------------------------------------------- + function Constructor(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (!TypeGuard.TConstructor(right)) + return TypeExtendsResult.False; + if (left.parameters.length > right.parameters.length) + return TypeExtendsResult.False; + if (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === TypeExtendsResult.True)) { + return TypeExtendsResult.False; + } + return IntoBooleanResult(Visit(left.returns, right.returns)); + } + // -------------------------------------------------------------------------- + // Date + // -------------------------------------------------------------------------- + function Date(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TDate(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Function + // -------------------------------------------------------------------------- + function Function(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (!TypeGuard.TFunction(right)) + return TypeExtendsResult.False; + if (left.parameters.length > right.parameters.length) + return TypeExtendsResult.False; + if (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === TypeExtendsResult.True)) { + return TypeExtendsResult.False; + } + return IntoBooleanResult(Visit(left.returns, right.returns)); + } + // -------------------------------------------------------------------------- + // Integer + // -------------------------------------------------------------------------- + function IntegerRight(left, right) { + if (TypeGuard.TLiteral(left) && typeof left.const === 'number') + return TypeExtendsResult.True; + return TypeGuard.TNumber(left) || TypeGuard.TInteger(left) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Integer(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TInteger(right) || TypeGuard.TNumber(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Intersect + // -------------------------------------------------------------------------- + function IntersectRight(left, right) { + return right.allOf.every((schema) => Visit(left, schema) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Intersect(left, right) { + return left.allOf.some((schema) => Visit(schema, right) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Literal + // -------------------------------------------------------------------------- + function IsLiteralString(schema) { + return typeof schema.const === 'string'; + } + function IsLiteralNumber(schema) { + return typeof schema.const === 'number'; + } + function IsLiteralBoolean(schema) { + return typeof schema.const === 'boolean'; + } + function Literal(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + if (TypeGuard.TString(right)) + return StringRight(left, right); + if (TypeGuard.TNumber(right)) + return NumberRight(left, right); + if (TypeGuard.TInteger(right)) + return IntegerRight(left, right); + if (TypeGuard.TBoolean(right)) + return BooleanRight(left, right); + return TypeGuard.TLiteral(right) && right.const === left.const ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Never + // -------------------------------------------------------------------------- + function NeverRight(left, right) { + return TypeExtendsResult.False; + } + function Never(left, right) { + return TypeExtendsResult.True; + } + // -------------------------------------------------------------------------- + // Null + // -------------------------------------------------------------------------- + function Null(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TNull(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Number + // -------------------------------------------------------------------------- + function NumberRight(left, right) { + if (TypeGuard.TLiteral(left) && IsLiteralNumber(left)) + return TypeExtendsResult.True; + return TypeGuard.TNumber(left) || TypeGuard.TInteger(left) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Number(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TInteger(right) || TypeGuard.TNumber(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Object + // -------------------------------------------------------------------------- + function IsObjectPropertyCount(schema, count) { + return globalThis.Object.keys(schema.properties).length === count; + } + function IsObjectStringLike(schema) { + return IsObjectArrayLike(schema); + } + function IsObjectSymbolLike(schema) { + // prettier-ignore + return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'description' in schema.properties && TypeGuard.TUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && ((TypeGuard.TString(schema.properties.description.anyOf[0]) && + TypeGuard.TUndefined(schema.properties.description.anyOf[1])) || (TypeGuard.TString(schema.properties.description.anyOf[1]) && + TypeGuard.TUndefined(schema.properties.description.anyOf[0])))); + } + function IsObjectNumberLike(schema) { + return IsObjectPropertyCount(schema, 0); + } + function IsObjectBooleanLike(schema) { + return IsObjectPropertyCount(schema, 0); + } + function IsObjectBigIntLike(schema) { + return IsObjectPropertyCount(schema, 0); + } + function IsObjectDateLike(schema) { + return IsObjectPropertyCount(schema, 0); + } + function IsObjectUint8ArrayLike(schema) { + return IsObjectArrayLike(schema); + } + function IsObjectFunctionLike(schema) { + const length = exports.Type.Number(); + return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === TypeExtendsResult.True); + } + function IsObjectConstructorLike(schema) { + return IsObjectPropertyCount(schema, 0); + } + function IsObjectArrayLike(schema) { + const length = exports.Type.Number(); + return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === TypeExtendsResult.True); + } + function IsObjectPromiseLike(schema) { + const then = exports.Type.Function([exports.Type.Any()], exports.Type.Any()); + return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'then' in schema.properties && IntoBooleanResult(Visit(schema.properties['then'], then)) === TypeExtendsResult.True); + } + // -------------------------------------------------------------------------- + // Property + // -------------------------------------------------------------------------- + function Property(left, right) { + if (Visit(left, right) === TypeExtendsResult.False) + return TypeExtendsResult.False; + if (TypeGuard.TOptional(left) && !TypeGuard.TOptional(right)) + return TypeExtendsResult.False; + return TypeExtendsResult.True; + } + function ObjectRight(left, right) { + if (TypeGuard.TUnknown(left)) + return TypeExtendsResult.False; + if (TypeGuard.TAny(left)) + return TypeExtendsResult.Union; + if (TypeGuard.TNever(left)) + return TypeExtendsResult.True; + if (TypeGuard.TLiteral(left) && IsLiteralString(left) && IsObjectStringLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TLiteral(left) && IsLiteralNumber(left) && IsObjectNumberLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TLiteral(left) && IsLiteralBoolean(left) && IsObjectBooleanLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TSymbol(left) && IsObjectSymbolLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TBigInt(left) && IsObjectBigIntLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TString(left) && IsObjectStringLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TSymbol(left) && IsObjectSymbolLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TNumber(left) && IsObjectNumberLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TInteger(left) && IsObjectNumberLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TBoolean(left) && IsObjectBooleanLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TUint8Array(left) && IsObjectUint8ArrayLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TDate(left) && IsObjectDateLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TConstructor(left) && IsObjectConstructorLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TFunction(left) && IsObjectFunctionLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TRecord(left) && TypeGuard.TString(RecordKey(left))) { + // When expressing a Record with literal key values, the Record is converted into a Object with + // the Hint assigned as `Record`. This is used to invert the extends logic. + return right[exports.Hint] === 'Record' ? TypeExtendsResult.True : TypeExtendsResult.False; + } + if (TypeGuard.TRecord(left) && TypeGuard.TNumber(RecordKey(left))) { + return IsObjectPropertyCount(right, 0) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + return TypeExtendsResult.False; + } + function Object(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + if (!TypeGuard.TObject(right)) + return TypeExtendsResult.False; + for (const key of globalThis.Object.keys(right.properties)) { + if (!(key in left.properties)) + return TypeExtendsResult.False; + if (Property(left.properties[key], right.properties[key]) === TypeExtendsResult.False) { + return TypeExtendsResult.False; + } + } + return TypeExtendsResult.True; + } + // -------------------------------------------------------------------------- + // Promise + // -------------------------------------------------------------------------- + function Promise(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right) && IsObjectPromiseLike(right)) + return TypeExtendsResult.True; + if (!TypeGuard.TPromise(right)) + return TypeExtendsResult.False; + return IntoBooleanResult(Visit(left.item, right.item)); + } + // -------------------------------------------------------------------------- + // Record + // -------------------------------------------------------------------------- + function RecordKey(schema) { + if (exports.PatternNumberExact in schema.patternProperties) + return exports.Type.Number(); + if (exports.PatternStringExact in schema.patternProperties) + return exports.Type.String(); + throw Error('TypeExtends: Cannot get record key'); + } + function RecordValue(schema) { + if (exports.PatternNumberExact in schema.patternProperties) + return schema.patternProperties[exports.PatternNumberExact]; + if (exports.PatternStringExact in schema.patternProperties) + return schema.patternProperties[exports.PatternStringExact]; + throw Error('TypeExtends: Cannot get record value'); + } + function RecordRight(left, right) { + const Key = RecordKey(right); + const Value = RecordValue(right); + if (TypeGuard.TLiteral(left) && IsLiteralString(left) && TypeGuard.TNumber(Key) && IntoBooleanResult(Visit(left, Value)) === TypeExtendsResult.True) + return TypeExtendsResult.True; + if (TypeGuard.TUint8Array(left) && TypeGuard.TNumber(Key)) + return Visit(left, Value); + if (TypeGuard.TString(left) && TypeGuard.TNumber(Key)) + return Visit(left, Value); + if (TypeGuard.TArray(left) && TypeGuard.TNumber(Key)) + return Visit(left, Value); + if (TypeGuard.TObject(left)) { + for (const key of globalThis.Object.keys(left.properties)) { + if (Property(Value, left.properties[key]) === TypeExtendsResult.False) { + return TypeExtendsResult.False; + } + } + return TypeExtendsResult.True; + } + return TypeExtendsResult.False; + } + function Record(left, right) { + const Value = RecordValue(left); + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (!TypeGuard.TRecord(right)) + return TypeExtendsResult.False; + return Visit(Value, RecordValue(right)); + } + // -------------------------------------------------------------------------- + // String + // -------------------------------------------------------------------------- + function StringRight(left, right) { + if (TypeGuard.TLiteral(left) && typeof left.const === 'string') + return TypeExtendsResult.True; + return TypeGuard.TString(left) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function String(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TString(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Symbol + // -------------------------------------------------------------------------- + function Symbol(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TSymbol(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Tuple + // -------------------------------------------------------------------------- + function TupleRight(left, right) { + if (TypeGuard.TUnknown(left)) + return TypeExtendsResult.False; + if (TypeGuard.TAny(left)) + return TypeExtendsResult.Union; + if (TypeGuard.TNever(left)) + return TypeExtendsResult.True; + return TypeExtendsResult.False; + } + function IsArrayOfTuple(left, right) { + return TypeGuard.TArray(right) && left.items !== undefined && left.items.every((schema) => Visit(schema, right.items) === TypeExtendsResult.True); + } + function Tuple(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right) && IsObjectArrayLike(right)) + return TypeExtendsResult.True; + if (TypeGuard.TArray(right) && IsArrayOfTuple(left, right)) + return TypeExtendsResult.True; + if (!TypeGuard.TTuple(right)) + return TypeExtendsResult.False; + if ((left.items === undefined && right.items !== undefined) || (left.items !== undefined && right.items === undefined)) + return TypeExtendsResult.False; + if (left.items === undefined && right.items === undefined) + return TypeExtendsResult.True; + return left.items.every((schema, index) => Visit(schema, right.items[index]) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Uint8Array + // -------------------------------------------------------------------------- + function Uint8Array(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + return TypeGuard.TUint8Array(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Undefined + // -------------------------------------------------------------------------- + function Undefined(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TNever(right)) + return NeverRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + if (TypeGuard.TRecord(right)) + return RecordRight(left, right); + if (TypeGuard.TVoid(right)) + return VoidRight(left, right); + return TypeGuard.TUndefined(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Union + // -------------------------------------------------------------------------- + function UnionRight(left, right) { + return right.anyOf.some((schema) => Visit(left, schema) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Union(left, right) { + return left.anyOf.every((schema) => Visit(schema, right) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Unknown + // -------------------------------------------------------------------------- + function UnknownRight(left, right) { + return TypeExtendsResult.True; + } + function Unknown(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TString(right)) + return StringRight(left, right); + if (TypeGuard.TNumber(right)) + return NumberRight(left, right); + if (TypeGuard.TInteger(right)) + return IntegerRight(left, right); + if (TypeGuard.TBoolean(right)) + return BooleanRight(left, right); + if (TypeGuard.TArray(right)) + return ArrayRight(left, right); + if (TypeGuard.TTuple(right)) + return TupleRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + return TypeGuard.TUnknown(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + // -------------------------------------------------------------------------- + // Void + // -------------------------------------------------------------------------- + function VoidRight(left, right) { + if (TypeGuard.TUndefined(left)) + return TypeExtendsResult.True; + return TypeGuard.TUndefined(left) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Void(left, right) { + if (TypeGuard.TIntersect(right)) + return IntersectRight(left, right); + if (TypeGuard.TUnion(right)) + return UnionRight(left, right); + if (TypeGuard.TUnknown(right)) + return UnknownRight(left, right); + if (TypeGuard.TAny(right)) + return AnyRight(left, right); + if (TypeGuard.TObject(right)) + return ObjectRight(left, right); + return TypeGuard.TVoid(right) ? TypeExtendsResult.True : TypeExtendsResult.False; + } + function Visit(left, right) { + // template union remap + if (TypeGuard.TTemplateLiteral(left)) + return Visit(TemplateLiteralResolver.Resolve(left), right); + if (TypeGuard.TTemplateLiteral(right)) + return Visit(left, TemplateLiteralResolver.Resolve(right)); + // standard extends + if (TypeGuard.TAny(left)) + return Any(left, right); + if (TypeGuard.TArray(left)) + return Array(left, right); + if (TypeGuard.TBigInt(left)) + return BigInt(left, right); + if (TypeGuard.TBoolean(left)) + return Boolean(left, right); + if (TypeGuard.TConstructor(left)) + return Constructor(left, right); + if (TypeGuard.TDate(left)) + return Date(left, right); + if (TypeGuard.TFunction(left)) + return Function(left, right); + if (TypeGuard.TInteger(left)) + return Integer(left, right); + if (TypeGuard.TIntersect(left)) + return Intersect(left, right); + if (TypeGuard.TLiteral(left)) + return Literal(left, right); + if (TypeGuard.TNever(left)) + return Never(left, right); + if (TypeGuard.TNull(left)) + return Null(left, right); + if (TypeGuard.TNumber(left)) + return Number(left, right); + if (TypeGuard.TObject(left)) + return Object(left, right); + if (TypeGuard.TRecord(left)) + return Record(left, right); + if (TypeGuard.TString(left)) + return String(left, right); + if (TypeGuard.TSymbol(left)) + return Symbol(left, right); + if (TypeGuard.TTuple(left)) + return Tuple(left, right); + if (TypeGuard.TPromise(left)) + return Promise(left, right); + if (TypeGuard.TUint8Array(left)) + return Uint8Array(left, right); + if (TypeGuard.TUndefined(left)) + return Undefined(left, right); + if (TypeGuard.TUnion(left)) + return Union(left, right); + if (TypeGuard.TUnknown(left)) + return Unknown(left, right); + if (TypeGuard.TVoid(left)) + return Void(left, right); + throw Error(`TypeExtends: Unknown left type operand '${left[exports.Kind]}'`); + } + function Extends(left, right) { + return Visit(left, right); + } + TypeExtends.Extends = Extends; +})(TypeExtends = exports.TypeExtends || (exports.TypeExtends = {})); +// -------------------------------------------------------------------------- +// TypeClone +// -------------------------------------------------------------------------- +/** Specialized Clone for Types */ +var TypeClone; +(function (TypeClone) { + function IsObject(value) { + return typeof value === 'object' && value !== null; + } + function IsArray(value) { + return globalThis.Array.isArray(value); + } + function Array(value) { + return value.map((value) => Visit(value)); + } + function Object(value) { + const clonedProperties = globalThis.Object.getOwnPropertyNames(value).reduce((acc, key) => { + return { ...acc, [key]: Visit(value[key]) }; + }, {}); + const clonedSymbols = globalThis.Object.getOwnPropertySymbols(value).reduce((acc, key) => { + return { ...acc, [key]: Visit(value[key]) }; + }, {}); + return { ...clonedProperties, ...clonedSymbols }; + } + function Visit(value) { + if (IsArray(value)) + return Array(value); + if (IsObject(value)) + return Object(value); + return value; + } + /** Clones a type. */ + function Clone(schema, options) { + return { ...Visit(schema), ...options }; + } + TypeClone.Clone = Clone; +})(TypeClone = exports.TypeClone || (exports.TypeClone = {})); +// -------------------------------------------------------------------------- +// ObjectMap +// -------------------------------------------------------------------------- +var ObjectMap; +(function (ObjectMap) { + function Intersect(schema, callback) { + // prettier-ignore + return exports.Type.Intersect(schema.allOf.map((inner) => Visit(inner, callback)), { ...schema }); + } + function Union(schema, callback) { + // prettier-ignore + return exports.Type.Union(schema.anyOf.map((inner) => Visit(inner, callback)), { ...schema }); + } + function Object(schema, callback) { + return callback(schema); + } + function Visit(schema, callback) { + // There are cases where users need to map objects with unregistered kinds. Using a TypeGuard here would + // prevent sub schema mapping as unregistered kinds will not pass TSchema checks. This is notable in the + // case of TObject where unregistered property kinds cause the TObject check to fail. As mapping is only + // used for composition, we use explicit checks instead. + if (schema[exports.Kind] === 'Intersect') + return Intersect(schema, callback); + if (schema[exports.Kind] === 'Union') + return Union(schema, callback); + if (schema[exports.Kind] === 'Object') + return Object(schema, callback); + return schema; + } + function Map(schema, callback, options) { + return { ...Visit(TypeClone.Clone(schema, {}), callback), ...options }; + } + ObjectMap.Map = Map; +})(ObjectMap = exports.ObjectMap || (exports.ObjectMap = {})); +// -------------------------------------------------------------------------- +// KeyResolver +// -------------------------------------------------------------------------- +var KeyResolver; +(function (KeyResolver) { + function IsKeyable(schema) { + return TypeGuard.TIntersect(schema) || TypeGuard.TUnion(schema) || (TypeGuard.TObject(schema) && globalThis.Object.getOwnPropertyNames(schema.properties).length > 0); + } + function Intersect(schema) { + return [...schema.allOf.filter((schema) => IsKeyable(schema)).reduce((set, schema) => Visit(schema).map((key) => set.add(key))[0], new Set())]; + } + function Union(schema) { + const sets = schema.anyOf.filter((schema) => IsKeyable(schema)).map((inner) => Visit(inner)); + return [...sets.reduce((set, outer) => outer.map((key) => (sets.every((inner) => inner.includes(key)) ? set.add(key) : set))[0], new Set())]; + } + function Object(schema) { + return globalThis.Object.keys(schema.properties); + } + function Visit(schema) { + if (TypeGuard.TIntersect(schema)) + return Intersect(schema); + if (TypeGuard.TUnion(schema)) + return Union(schema); + if (TypeGuard.TObject(schema)) + return Object(schema); + return []; + } + function Resolve(schema) { + return Visit(schema); + } + KeyResolver.Resolve = Resolve; +})(KeyResolver = exports.KeyResolver || (exports.KeyResolver = {})); +// -------------------------------------------------------------------------- +// TemplateLiteralPattern +// -------------------------------------------------------------------------- +var TemplateLiteralPattern; +(function (TemplateLiteralPattern) { + function Escape(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + function Visit(schema, acc) { + if (TypeGuard.TTemplateLiteral(schema)) { + const pattern = schema.pattern.slice(1, schema.pattern.length - 1); + return pattern; + } + else if (TypeGuard.TUnion(schema)) { + const tokens = schema.anyOf.map((schema) => Visit(schema, acc)).join('|'); + return `(${tokens})`; + } + else if (TypeGuard.TNumber(schema)) { + return `${acc}${exports.PatternNumber}`; + } + else if (TypeGuard.TInteger(schema)) { + return `${acc}${exports.PatternNumber}`; + } + else if (TypeGuard.TBigInt(schema)) { + return `${acc}${exports.PatternNumber}`; + } + else if (TypeGuard.TString(schema)) { + return `${acc}${exports.PatternString}`; + } + else if (TypeGuard.TLiteral(schema)) { + return `${acc}${Escape(schema.const.toString())}`; + } + else if (TypeGuard.TBoolean(schema)) { + return `${acc}${exports.PatternBoolean}`; + } + else if (TypeGuard.TNever(schema)) { + throw Error('TemplateLiteralPattern: TemplateLiteral cannot operate on types of TNever'); + } + else { + throw Error(`TemplateLiteralPattern: Unexpected Kind '${schema[exports.Kind]}'`); + } + } + function Create(kinds) { + return `^${kinds.map((schema) => Visit(schema, '')).join('')}\$`; + } + TemplateLiteralPattern.Create = Create; +})(TemplateLiteralPattern = exports.TemplateLiteralPattern || (exports.TemplateLiteralPattern = {})); +// -------------------------------------------------------------------------------------- +// TemplateLiteralResolver +// -------------------------------------------------------------------------------------- +var TemplateLiteralResolver; +(function (TemplateLiteralResolver) { + function Resolve(template) { + const expression = TemplateLiteralParser.ParseExact(template.pattern); + if (!TemplateLiteralFinite.Check(expression)) + return exports.Type.String(); + const literals = [...TemplateLiteralGenerator.Generate(expression)].map((value) => exports.Type.Literal(value)); + return exports.Type.Union(literals); + } + TemplateLiteralResolver.Resolve = Resolve; +})(TemplateLiteralResolver = exports.TemplateLiteralResolver || (exports.TemplateLiteralResolver = {})); +// -------------------------------------------------------------------------------------- +// TemplateLiteralParser +// -------------------------------------------------------------------------------------- +class TemplateLiteralParserError extends Error { + constructor(message) { + super(message); + } +} +exports.TemplateLiteralParserError = TemplateLiteralParserError; +var TemplateLiteralParser; +(function (TemplateLiteralParser) { + function IsNonEscaped(pattern, index, char) { + return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92; + } + function IsOpenParen(pattern, index) { + return IsNonEscaped(pattern, index, '('); + } + function IsCloseParen(pattern, index) { + return IsNonEscaped(pattern, index, ')'); + } + function IsSeparator(pattern, index) { + return IsNonEscaped(pattern, index, '|'); + } + function IsGroup(pattern) { + if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1))) + return false; + let count = 0; + for (let index = 0; index < pattern.length; index++) { + if (IsOpenParen(pattern, index)) + count += 1; + if (IsCloseParen(pattern, index)) + count -= 1; + if (count === 0 && index !== pattern.length - 1) + return false; + } + return true; + } + function InGroup(pattern) { + return pattern.slice(1, pattern.length - 1); + } + function IsPrecedenceOr(pattern) { + let count = 0; + for (let index = 0; index < pattern.length; index++) { + if (IsOpenParen(pattern, index)) + count += 1; + if (IsCloseParen(pattern, index)) + count -= 1; + if (IsSeparator(pattern, index) && count === 0) + return true; + } + return false; + } + function IsPrecedenceAnd(pattern) { + for (let index = 0; index < pattern.length; index++) { + if (IsOpenParen(pattern, index)) + return true; + } + return false; + } + function Or(pattern) { + let [count, start] = [0, 0]; + const expressions = []; + for (let index = 0; index < pattern.length; index++) { + if (IsOpenParen(pattern, index)) + count += 1; + if (IsCloseParen(pattern, index)) + count -= 1; + if (IsSeparator(pattern, index) && count === 0) { + const range = pattern.slice(start, index); + if (range.length > 0) + expressions.push(Parse(range)); + start = index + 1; + } + } + const range = pattern.slice(start); + if (range.length > 0) + expressions.push(Parse(range)); + if (expressions.length === 0) + return { type: 'const', const: '' }; + if (expressions.length === 1) + return expressions[0]; + return { type: 'or', expr: expressions }; + } + function And(pattern) { + function Group(value, index) { + if (!IsOpenParen(value, index)) + throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`); + let count = 0; + for (let scan = index; scan < value.length; scan++) { + if (IsOpenParen(value, scan)) + count += 1; + if (IsCloseParen(value, scan)) + count -= 1; + if (count === 0) + return [index, scan]; + } + throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`); + } + function Range(pattern, index) { + for (let scan = index; scan < pattern.length; scan++) { + if (IsOpenParen(pattern, scan)) + return [index, scan]; + } + return [index, pattern.length]; + } + const expressions = []; + for (let index = 0; index < pattern.length; index++) { + if (IsOpenParen(pattern, index)) { + const [start, end] = Group(pattern, index); + const range = pattern.slice(start, end + 1); + expressions.push(Parse(range)); + index = end; + } + else { + const [start, end] = Range(pattern, index); + const range = pattern.slice(start, end); + if (range.length > 0) + expressions.push(Parse(range)); + index = end - 1; + } + } + if (expressions.length === 0) + return { type: 'const', const: '' }; + if (expressions.length === 1) + return expressions[0]; + return { type: 'and', expr: expressions }; + } + /** Parses a pattern and returns an expression tree */ + function Parse(pattern) { + if (IsGroup(pattern)) + return Parse(InGroup(pattern)); + if (IsPrecedenceOr(pattern)) + return Or(pattern); + if (IsPrecedenceAnd(pattern)) + return And(pattern); + return { type: 'const', const: pattern }; + } + TemplateLiteralParser.Parse = Parse; + /** Parses a pattern and strips forward and trailing ^ and $ */ + function ParseExact(pattern) { + return Parse(pattern.slice(1, pattern.length - 1)); + } + TemplateLiteralParser.ParseExact = ParseExact; +})(TemplateLiteralParser = exports.TemplateLiteralParser || (exports.TemplateLiteralParser = {})); +// -------------------------------------------------------------------------------------- +// TemplateLiteralFinite +// -------------------------------------------------------------------------------------- +var TemplateLiteralFinite; +(function (TemplateLiteralFinite) { + function IsNumber(expression) { + // prettier-ignore + return (expression.type === 'or' && + expression.expr.length === 2 && + expression.expr[0].type === 'const' && + expression.expr[0].const === '0' && + expression.expr[1].type === 'const' && + expression.expr[1].const === '[1-9][0-9]*'); + } + function IsBoolean(expression) { + // prettier-ignore + return (expression.type === 'or' && + expression.expr.length === 2 && + expression.expr[0].type === 'const' && + expression.expr[0].const === 'true' && + expression.expr[1].type === 'const' && + expression.expr[1].const === 'false'); + } + function IsString(expression) { + return expression.type === 'const' && expression.const === '.*'; + } + function Check(expression) { + if (IsBoolean(expression)) + return true; + if (IsNumber(expression) || IsString(expression)) + return false; + if (expression.type === 'and') + return expression.expr.every((expr) => Check(expr)); + if (expression.type === 'or') + return expression.expr.every((expr) => Check(expr)); + if (expression.type === 'const') + return true; + throw Error(`TemplateLiteralFinite: Unknown expression type`); + } + TemplateLiteralFinite.Check = Check; +})(TemplateLiteralFinite = exports.TemplateLiteralFinite || (exports.TemplateLiteralFinite = {})); +// -------------------------------------------------------------------------------------- +// TemplateLiteralGenerator +// -------------------------------------------------------------------------------------- +var TemplateLiteralGenerator; +(function (TemplateLiteralGenerator) { + function* Reduce(buffer) { + if (buffer.length === 1) + return yield* buffer[0]; + for (const left of buffer[0]) { + for (const right of Reduce(buffer.slice(1))) { + yield `${left}${right}`; + } + } + } + function* And(expression) { + return yield* Reduce(expression.expr.map((expr) => [...Generate(expr)])); + } + function* Or(expression) { + for (const expr of expression.expr) + yield* Generate(expr); + } + function* Const(expression) { + return yield expression.const; + } + function* Generate(expression) { + if (expression.type === 'and') + return yield* And(expression); + if (expression.type === 'or') + return yield* Or(expression); + if (expression.type === 'const') + return yield* Const(expression); + throw Error('TemplateLiteralGenerator: Unknown expression'); + } + TemplateLiteralGenerator.Generate = Generate; +})(TemplateLiteralGenerator = exports.TemplateLiteralGenerator || (exports.TemplateLiteralGenerator = {})); +// -------------------------------------------------------------------------- +// TypeOrdinal: Used for auto $id generation +// -------------------------------------------------------------------------- +let TypeOrdinal = 0; +// -------------------------------------------------------------------------- +// TypeBuilder +// -------------------------------------------------------------------------- +class TypeBuilder { + /** `[Utility]` Creates a schema without `static` and `params` types */ + Create(schema) { + return schema; + } + /** `[Standard]` Omits compositing symbols from this schema */ + Strict(schema) { + return JSON.parse(JSON.stringify(schema)); + } +} +exports.TypeBuilder = TypeBuilder; +// -------------------------------------------------------------------------- +// StandardTypeBuilder +// -------------------------------------------------------------------------- +class StandardTypeBuilder extends TypeBuilder { + // ------------------------------------------------------------------------ + // Modifiers + // ------------------------------------------------------------------------ + /** `[Modifier]` Creates a Optional property */ + Optional(schema) { + return { [exports.Modifier]: 'Optional', ...TypeClone.Clone(schema, {}) }; + } + /** `[Modifier]` Creates a ReadonlyOptional property */ + ReadonlyOptional(schema) { + return { [exports.Modifier]: 'ReadonlyOptional', ...TypeClone.Clone(schema, {}) }; + } + /** `[Modifier]` Creates a Readonly object or property */ + Readonly(schema) { + return { [exports.Modifier]: 'Readonly', ...schema }; + } + // ------------------------------------------------------------------------ + // Types + // ------------------------------------------------------------------------ + /** `[Standard]` Creates an Any type */ + Any(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Any' }); + } + /** `[Standard]` Creates an Array type */ + Array(items, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items: TypeClone.Clone(items, {}) }); + } + /** `[Standard]` Creates a Boolean type */ + Boolean(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' }); + } + /** `[Standard]` Creates a Composite object type. */ + Composite(objects, options) { + const isOptionalAll = (objects, key) => objects.every((object) => !(key in object.properties) || IsOptional(object.properties[key])); + const IsOptional = (schema) => TypeGuard.TOptional(schema) || TypeGuard.TReadonlyOptional(schema); + const [required, optional] = [new Set(), new Set()]; + for (const object of objects) { + for (const key of globalThis.Object.getOwnPropertyNames(object.properties)) { + if (isOptionalAll(objects, key)) + optional.add(key); + } + } + for (const object of objects) { + for (const key of globalThis.Object.getOwnPropertyNames(object.properties)) { + if (!optional.has(key)) + required.add(key); + } + } + const properties = {}; + for (const object of objects) { + for (const [key, schema] of Object.entries(object.properties)) { + const property = TypeClone.Clone(schema, {}); + if (!optional.has(key)) + delete property[exports.Modifier]; + if (key in properties) { + const left = TypeExtends.Extends(properties[key], property) !== TypeExtendsResult.False; + const right = TypeExtends.Extends(property, properties[key]) !== TypeExtendsResult.False; + if (!left && !right) + properties[key] = exports.Type.Never(); + if (!left && right) + properties[key] = property; + } + else { + properties[key] = property; + } + } + } + if (required.size > 0) { + return this.Create({ ...options, [exports.Kind]: 'Object', [exports.Hint]: 'Composite', type: 'object', properties, required: [...required] }); + } + else { + return this.Create({ ...options, [exports.Kind]: 'Object', [exports.Hint]: 'Composite', type: 'object', properties }); + } + } + /** `[Standard]` Creates a Enum type */ + Enum(item, options = {}) { + // prettier-ignore + const values = globalThis.Object.keys(item).filter((key) => isNaN(key)).map((key) => item[key]); + const anyOf = values.map((value) => (typeof value === 'string' ? { [exports.Kind]: 'Literal', type: 'string', const: value } : { [exports.Kind]: 'Literal', type: 'number', const: value })); + return this.Create({ ...options, [exports.Kind]: 'Union', anyOf }); + } + /** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */ + Extends(left, right, trueType, falseType, options = {}) { + switch (TypeExtends.Extends(left, right)) { + case TypeExtendsResult.Union: + return this.Union([TypeClone.Clone(trueType, options), TypeClone.Clone(falseType, options)]); + case TypeExtendsResult.True: + return TypeClone.Clone(trueType, options); + case TypeExtendsResult.False: + return TypeClone.Clone(falseType, options); + } + } + /** `[Standard]` Excludes from the left type any type that is not assignable to the right */ + Exclude(left, right, options = {}) { + if (TypeGuard.TTemplateLiteral(left)) + return this.Exclude(TemplateLiteralResolver.Resolve(left), right, options); + if (TypeGuard.TTemplateLiteral(right)) + return this.Exclude(left, TemplateLiteralResolver.Resolve(right), options); + if (TypeGuard.TUnion(left)) { + const narrowed = left.anyOf.filter((inner) => TypeExtends.Extends(inner, right) === TypeExtendsResult.False); + return (narrowed.length === 1 ? TypeClone.Clone(narrowed[0], options) : this.Union(narrowed, options)); + } + else { + return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? this.Never(options) : TypeClone.Clone(left, options)); + } + } + /** `[Standard]` Extracts from the left type any type that is assignable to the right */ + Extract(left, right, options = {}) { + if (TypeGuard.TTemplateLiteral(left)) + return this.Extract(TemplateLiteralResolver.Resolve(left), right, options); + if (TypeGuard.TTemplateLiteral(right)) + return this.Extract(left, TemplateLiteralResolver.Resolve(right), options); + if (TypeGuard.TUnion(left)) { + const narrowed = left.anyOf.filter((inner) => TypeExtends.Extends(inner, right) !== TypeExtendsResult.False); + return (narrowed.length === 1 ? TypeClone.Clone(narrowed[0], options) : this.Union(narrowed, options)); + } + else { + return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? TypeClone.Clone(left, options) : this.Never(options)); + } + } + /** `[Standard]` Creates an Integer type */ + Integer(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' }); + } + Intersect(allOf, options = {}) { + if (allOf.length === 0) + return exports.Type.Never(); + if (allOf.length === 1) + return TypeClone.Clone(allOf[0], options); + const objects = allOf.every((schema) => TypeGuard.TObject(schema)); + const cloned = allOf.map((schema) => TypeClone.Clone(schema, {})); + const clonedUnevaluatedProperties = TypeGuard.TSchema(options.unevaluatedProperties) ? { unevaluatedProperties: TypeClone.Clone(options.unevaluatedProperties, {}) } : {}; + if (options.unevaluatedProperties === false || TypeGuard.TSchema(options.unevaluatedProperties) || objects) { + return this.Create({ ...options, ...clonedUnevaluatedProperties, [exports.Kind]: 'Intersect', type: 'object', allOf: cloned }); + } + else { + return this.Create({ ...options, ...clonedUnevaluatedProperties, [exports.Kind]: 'Intersect', allOf: cloned }); + } + } + /** `[Standard]` Creates a KeyOf type */ + KeyOf(schema, options = {}) { + if (TypeGuard.TRecord(schema)) { + const pattern = Object.getOwnPropertyNames(schema.patternProperties)[0]; + if (pattern === exports.PatternNumberExact) + return this.Number(options); + if (pattern === exports.PatternStringExact) + return this.String(options); + throw Error('StandardTypeBuilder: Unable to resolve key type from Record key pattern'); + } + else { + const resolved = KeyResolver.Resolve(schema); + if (resolved.length === 0) + return this.Never(options); + const literals = resolved.map((key) => this.Literal(key)); + return this.Union(literals, options); + } + } + /** `[Standard]` Creates a Literal type */ + Literal(value, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value }); + } + /** `[Standard]` Creates a Never type */ + Never(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Never', not: {} }); + } + /** `[Standard]` Creates a Not type. The first argument is the disallowed type, the second is the allowed. */ + Not(not, schema, options) { + return this.Create({ ...options, [exports.Kind]: 'Not', allOf: [{ not: TypeClone.Clone(not, {}) }, TypeClone.Clone(schema, {})] }); + } + /** `[Standard]` Creates a Null type */ + Null(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' }); + } + /** `[Standard]` Creates a Number type */ + Number(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' }); + } + /** `[Standard]` Creates an Object type */ + Object(properties, options = {}) { + const propertyKeys = globalThis.Object.getOwnPropertyNames(properties); + const optionalKeys = propertyKeys.filter((key) => TypeGuard.TOptional(properties[key]) || TypeGuard.TReadonlyOptional(properties[key])); + const requiredKeys = propertyKeys.filter((name) => !optionalKeys.includes(name)); + const clonedAdditionalProperties = TypeGuard.TSchema(options.additionalProperties) ? { additionalProperties: TypeClone.Clone(options.additionalProperties, {}) } : {}; + const clonedProperties = propertyKeys.reduce((acc, key) => ({ ...acc, [key]: TypeClone.Clone(properties[key], {}) }), {}); + if (requiredKeys.length > 0) { + return this.Create({ ...options, ...clonedAdditionalProperties, [exports.Kind]: 'Object', type: 'object', properties: clonedProperties, required: requiredKeys }); + } + else { + return this.Create({ ...options, ...clonedAdditionalProperties, [exports.Kind]: 'Object', type: 'object', properties: clonedProperties }); + } + } + Omit(schema, unresolved, options = {}) { + // prettier-ignore + const keys = TypeGuard.TUnionLiteral(unresolved) ? unresolved.anyOf.map((schema) => schema.const) : + TypeGuard.TLiteral(unresolved) ? [unresolved.const] : + TypeGuard.TNever(unresolved) ? [] : + unresolved; + // prettier-ignore + return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => { + if (schema.required) { + schema.required = schema.required.filter((key) => !keys.includes(key)); + if (schema.required.length === 0) + delete schema.required; + } + for (const key of globalThis.Object.keys(schema.properties)) { + if (keys.includes(key)) + delete schema.properties[key]; + } + return this.Create(schema); + }, options); + } + /** `[Standard]` Creates a mapped type where all properties are Optional */ + Partial(schema, options = {}) { + function Apply(schema) { + // prettier-ignore + switch (schema[exports.Modifier]) { + case 'ReadonlyOptional': + schema[exports.Modifier] = 'ReadonlyOptional'; + break; + case 'Readonly': + schema[exports.Modifier] = 'ReadonlyOptional'; + break; + case 'Optional': + schema[exports.Modifier] = 'Optional'; + break; + default: + schema[exports.Modifier] = 'Optional'; + break; + } + } + // prettier-ignore + return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => { + delete schema.required; + globalThis.Object.keys(schema.properties).forEach(key => Apply(schema.properties[key])); + return schema; + }, options); + } + Pick(schema, unresolved, options = {}) { + // prettier-ignore + const keys = TypeGuard.TUnionLiteral(unresolved) ? unresolved.anyOf.map((schema) => schema.const) : + TypeGuard.TLiteral(unresolved) ? [unresolved.const] : + TypeGuard.TNever(unresolved) ? [] : + unresolved; + // prettier-ignore + return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => { + if (schema.required) { + schema.required = schema.required.filter((key) => keys.includes(key)); + if (schema.required.length === 0) + delete schema.required; + } + for (const key of globalThis.Object.keys(schema.properties)) { + if (!keys.includes(key)) + delete schema.properties[key]; + } + return this.Create(schema); + }, options); + } + /** `[Standard]` Creates a Record type */ + Record(key, schema, options = {}) { + if (TypeGuard.TTemplateLiteral(key)) { + const expression = TemplateLiteralParser.ParseExact(key.pattern); + // prettier-ignore + return TemplateLiteralFinite.Check(expression) + ? (this.Object([...TemplateLiteralGenerator.Generate(expression)].reduce((acc, key) => ({ ...acc, [key]: TypeClone.Clone(schema, {}) }), {}), options)) + : this.Create({ ...options, [exports.Kind]: 'Record', type: 'object', patternProperties: { [key.pattern]: TypeClone.Clone(schema, {}) }, additionalProperties: false }); + } + else if (TypeGuard.TUnionLiteral(key)) { + if (key.anyOf.every((schema) => TypeGuard.TLiteral(schema) && (typeof schema.const === 'string' || typeof schema.const === 'number'))) { + const properties = key.anyOf.reduce((acc, literal) => ({ ...acc, [literal.const]: TypeClone.Clone(schema, {}) }), {}); + return this.Object(properties, { ...options, [exports.Hint]: 'Record' }); + } + else + throw Error('TypeBuilder: Record key can only be derived from union literal of number or string'); + } + else if (TypeGuard.TLiteral(key)) { + if (typeof key.const === 'string' || typeof key.const === 'number') { + return this.Object({ [key.const]: TypeClone.Clone(schema, {}) }, options); + } + else + throw Error('TypeBuilder: Record key can only be derived from literals of number or string'); + } + else if (TypeGuard.TInteger(key) || TypeGuard.TNumber(key)) { + const pattern = exports.PatternNumberExact; + return this.Create({ ...options, [exports.Kind]: 'Record', type: 'object', patternProperties: { [pattern]: TypeClone.Clone(schema, {}) }, additionalProperties: false }); + } + else if (TypeGuard.TString(key)) { + const pattern = key.pattern === undefined ? exports.PatternStringExact : key.pattern; + return this.Create({ ...options, [exports.Kind]: 'Record', type: 'object', patternProperties: { [pattern]: TypeClone.Clone(schema, {}) }, additionalProperties: false }); + } + else { + throw Error(`StandardTypeBuilder: Invalid Record Key`); + } + } + /** `[Standard]` Creates a Recursive type */ + Recursive(callback, options = {}) { + if (options.$id === undefined) + options.$id = `T${TypeOrdinal++}`; + const thisType = callback({ [exports.Kind]: 'This', $ref: `${options.$id}` }); + thisType.$id = options.$id; + return this.Create({ ...options, [exports.Hint]: 'Recursive', ...thisType }); + } + /** `[Standard]` Creates a Ref type. The referenced type must contain a $id */ + Ref(schema, options = {}) { + if (schema.$id === undefined) + throw Error('StandardTypeBuilder.Ref: Target type must specify an $id'); + return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id }); + } + /** `[Standard]` Creates a mapped type where all properties are Required */ + Required(schema, options = {}) { + function Apply(schema) { + // prettier-ignore + switch (schema[exports.Modifier]) { + case 'ReadonlyOptional': + schema[exports.Modifier] = 'Readonly'; + break; + case 'Readonly': + schema[exports.Modifier] = 'Readonly'; + break; + case 'Optional': + delete schema[exports.Modifier]; + break; + default: + delete schema[exports.Modifier]; + break; + } + } + // prettier-ignore + return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => { + schema.required = globalThis.Object.keys(schema.properties); + globalThis.Object.keys(schema.properties).forEach(key => Apply(schema.properties[key])); + return schema; + }, options); + } + /** `[Standard]` Creates a String type */ + String(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' }); + } + /** `[Standard]` Creates a template literal type */ + TemplateLiteral(kinds, options = {}) { + const pattern = TemplateLiteralPattern.Create(kinds); + return this.Create({ ...options, [exports.Kind]: 'TemplateLiteral', type: 'string', pattern }); + } + /** `[Standard]` Creates a Tuple type */ + Tuple(items, options = {}) { + const [additionalItems, minItems, maxItems] = [false, items.length, items.length]; + const clonedItems = items.map((item) => TypeClone.Clone(item, {})); + // prettier-ignore + const schema = (items.length > 0 ? + { ...options, [exports.Kind]: 'Tuple', type: 'array', items: clonedItems, additionalItems, minItems, maxItems } : + { ...options, [exports.Kind]: 'Tuple', type: 'array', minItems, maxItems }); + return this.Create(schema); + } + Union(union, options = {}) { + if (TypeGuard.TTemplateLiteral(union)) { + return TemplateLiteralResolver.Resolve(union); + } + else { + const anyOf = union; + if (anyOf.length === 0) + return this.Never(options); + if (anyOf.length === 1) + return this.Create(TypeClone.Clone(anyOf[0], options)); + const clonedAnyOf = anyOf.map((schema) => TypeClone.Clone(schema, {})); + return this.Create({ ...options, [exports.Kind]: 'Union', anyOf: clonedAnyOf }); + } + } + /** `[Standard]` Creates an Unknown type */ + Unknown(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Unknown' }); + } + /** `[Standard]` Creates a Unsafe type that infers for the generic argument */ + Unsafe(options = {}) { + return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' }); + } +} +exports.StandardTypeBuilder = StandardTypeBuilder; +// -------------------------------------------------------------------------- +// ExtendedTypeBuilder +// -------------------------------------------------------------------------- +class ExtendedTypeBuilder extends StandardTypeBuilder { + /** `[Extended]` Creates a BigInt type */ + BigInt(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'BigInt', type: 'null', typeOf: 'BigInt' }); + } + /** `[Extended]` Extracts the ConstructorParameters from the given Constructor type */ + ConstructorParameters(schema, options = {}) { + return this.Tuple([...schema.parameters], { ...options }); + } + Constructor(parameters, returns, options = {}) { + const clonedReturns = TypeClone.Clone(returns, {}); + if (TypeGuard.TTuple(parameters)) { + const clonedParameters = parameters.items === undefined ? [] : parameters.items.map((parameter) => TypeClone.Clone(parameter, {})); + return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'object', instanceOf: 'Constructor', parameters: clonedParameters, returns: clonedReturns }); + } + else if (globalThis.Array.isArray(parameters)) { + const clonedParameters = parameters.map((parameter) => TypeClone.Clone(parameter, {})); + return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'object', instanceOf: 'Constructor', parameters: clonedParameters, returns: clonedReturns }); + } + else { + throw new Error('ExtendedTypeBuilder.Constructor: Invalid parameters'); + } + } + /** `[Extended]` Creates a Date type */ + Date(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Date', type: 'object', instanceOf: 'Date' }); + } + Function(parameters, returns, options = {}) { + const clonedReturns = TypeClone.Clone(returns, {}); + if (TypeGuard.TTuple(parameters)) { + const clonedParameters = parameters.items === undefined ? [] : parameters.items.map((parameter) => TypeClone.Clone(parameter, {})); + return this.Create({ ...options, [exports.Kind]: 'Function', type: 'object', instanceOf: 'Function', parameters: clonedParameters, returns: clonedReturns }); + } + else if (globalThis.Array.isArray(parameters)) { + const clonedParameters = parameters.map((parameter) => TypeClone.Clone(parameter, {})); + return this.Create({ ...options, [exports.Kind]: 'Function', type: 'object', instanceOf: 'Function', parameters: clonedParameters, returns: clonedReturns }); + } + else { + throw new Error('ExtendedTypeBuilder.Function: Invalid parameters'); + } + } + /** `[Extended]` Extracts the InstanceType from the given Constructor */ + InstanceType(schema, options = {}) { + return TypeClone.Clone(schema.returns, options); + } + /** `[Extended]` Extracts the Parameters from the given Function type */ + Parameters(schema, options = {}) { + return this.Tuple(schema.parameters, { ...options }); + } + /** `[Extended]` Creates a Promise type */ + Promise(item, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'object', instanceOf: 'Promise', item: TypeClone.Clone(item, {}) }); + } + /** `[Extended]` Creates a regular expression type */ + RegEx(regex, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source }); + } + /** `[Extended]` Extracts the ReturnType from the given Function */ + ReturnType(schema, options = {}) { + return TypeClone.Clone(schema.returns, options); + } + /** `[Extended]` Creates a Symbol type */ + Symbol(options) { + return this.Create({ ...options, [exports.Kind]: 'Symbol', type: 'null', typeOf: 'Symbol' }); + } + /** `[Extended]` Creates a Undefined type */ + Undefined(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'null', typeOf: 'Undefined' }); + } + /** `[Extended]` Creates a Uint8Array type */ + Uint8Array(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', instanceOf: 'Uint8Array' }); + } + /** `[Extended]` Creates a Void type */ + Void(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null', typeOf: 'Void' }); + } +} +exports.ExtendedTypeBuilder = ExtendedTypeBuilder; +/** JSON Schema TypeBuilder with Static Resolution for TypeScript */ +exports.StandardType = new StandardTypeBuilder(); +/** JSON Schema TypeBuilder with Static Resolution for TypeScript */ +exports.Type = new ExtendedTypeBuilder(); diff --git a/web/node_modules/@sinclair/typebox/value/cast.d.ts b/web/node_modules/@sinclair/typebox/value/cast.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..992d9e3f854bf6a9bdde95391a6bdd1222dab624 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/cast.d.ts @@ -0,0 +1,30 @@ +import * as Types from '../typebox'; +export declare class ValueCastReferenceTypeError extends Error { + readonly schema: Types.TRef | Types.TThis; + constructor(schema: Types.TRef | Types.TThis); +} +export declare class ValueCastArrayUniqueItemsTypeError extends Error { + readonly schema: Types.TSchema; + readonly value: unknown; + constructor(schema: Types.TSchema, value: unknown); +} +export declare class ValueCastNeverTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCastRecursiveTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCastUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCastDereferenceError extends Error { + readonly schema: Types.TRef | Types.TThis; + constructor(schema: Types.TRef | Types.TThis); +} +export declare namespace ValueCast { + function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any; + function Cast(schema: T, references: Types.TSchema[], value: any): Types.Static; +} diff --git a/web/node_modules/@sinclair/typebox/value/cast.js b/web/node_modules/@sinclair/typebox/value/cast.js new file mode 100644 index 0000000000000000000000000000000000000000..42fe2e1494085667a9911d25be0dd288f23ad975 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/cast.js @@ -0,0 +1,372 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueCast = exports.ValueCastDereferenceError = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0; +const Types = require("../typebox"); +const create_1 = require("./create"); +const check_1 = require("./check"); +const clone_1 = require("./clone"); +// ---------------------------------------------------------------------------------------------- +// Errors +// ---------------------------------------------------------------------------------------------- +class ValueCastReferenceTypeError extends Error { + constructor(schema) { + super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError; +class ValueCastArrayUniqueItemsTypeError extends Error { + constructor(schema, value) { + super('ValueCast: Array cast produced invalid data due to uniqueItems constraint'); + this.schema = schema; + this.value = value; + } +} +exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError; +class ValueCastNeverTypeError extends Error { + constructor(schema) { + super('ValueCast: Never types cannot be cast'); + this.schema = schema; + } +} +exports.ValueCastNeverTypeError = ValueCastNeverTypeError; +class ValueCastRecursiveTypeError extends Error { + constructor(schema) { + super('ValueCast.Recursive: Cannot cast recursive schemas'); + this.schema = schema; + } +} +exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError; +class ValueCastUnknownTypeError extends Error { + constructor(schema) { + super('ValueCast: Unknown type'); + this.schema = schema; + } +} +exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError; +class ValueCastDereferenceError extends Error { + constructor(schema) { + super(`ValueCast: Unable to dereference schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueCastDereferenceError = ValueCastDereferenceError; +// ---------------------------------------------------------------------------------------------- +// The following will score a schema against a value. For objects, the score is the tally of +// points awarded for each property of the value. Property points are (1.0 / propertyCount) +// to prevent large property counts biasing results. Properties that match literal values are +// maximally awarded as literals are typically used as union discriminator fields. +// ---------------------------------------------------------------------------------------------- +var UnionCastCreate; +(function (UnionCastCreate) { + function Score(schema, references, value) { + if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) { + const object = schema; + const keys = Object.keys(value); + const entries = globalThis.Object.entries(object.properties); + const [point, max] = [1 / entries.length, entries.length]; + return entries.reduce((acc, [key, schema]) => { + const literal = schema[Types.Kind] === 'Literal' && schema.const === value[key] ? max : 0; + const checks = check_1.ValueCheck.Check(schema, references, value[key]) ? point : 0; + const exists = keys.includes(key) ? point : 0; + return acc + (literal + checks + exists); + }, 0); + } + else { + return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0; + } + } + function Select(union, references, value) { + let [select, best] = [union.anyOf[0], 0]; + for (const schema of union.anyOf) { + const score = Score(schema, references, value); + if (score > best) { + select = schema; + best = score; + } + } + return select; + } + function Create(union, references, value) { + if (union.default !== undefined) { + return union.default; + } + else { + const schema = Select(union, references, value); + return ValueCast.Cast(schema, references, value); + } + } + UnionCastCreate.Create = Create; +})(UnionCastCreate || (UnionCastCreate = {})); +var ValueCast; +(function (ValueCast) { + // ---------------------------------------------------------------------------------------------- + // Guards + // ---------------------------------------------------------------------------------------------- + function IsObject(value) { + return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value); + } + function IsArray(value) { + return typeof value === 'object' && globalThis.Array.isArray(value); + } + function IsNumber(value) { + return typeof value === 'number' && !isNaN(value); + } + function IsString(value) { + return typeof value === 'string'; + } + // ---------------------------------------------------------------------------------------------- + // Cast + // ---------------------------------------------------------------------------------------------- + function Any(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function Array(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + const created = IsArray(value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + const minimum = IsNumber(schema.minItems) && created.length < schema.minItems ? [...created, ...globalThis.Array.from({ length: schema.minItems - created.length }, () => null)] : created; + const maximum = IsNumber(schema.maxItems) && minimum.length > schema.maxItems ? minimum.slice(0, schema.maxItems) : minimum; + const casted = maximum.map((value) => Visit(schema.items, references, value)); + if (schema.uniqueItems !== true) + return casted; + const unique = [...new Set(casted)]; + if (!check_1.ValueCheck.Check(schema, references, unique)) + throw new ValueCastArrayUniqueItemsTypeError(schema, unique); + return unique; + } + function BigInt(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Boolean(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Constructor(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return create_1.ValueCreate.Create(schema, references); + const required = new Set(schema.returns.required || []); + const result = function () { }; + for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) { + if (!required.has(key) && value.prototype[key] === undefined) + continue; + result.prototype[key] = Visit(property, references, value.prototype[key]); + } + return result; + } + function Date(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function Function(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Integer(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Intersect(schema, references, value) { + const created = create_1.ValueCreate.Create(schema, references); + const mapped = IsObject(created) && IsObject(value) ? { ...created, ...value } : value; + return check_1.ValueCheck.Check(schema, references, mapped) ? mapped : create_1.ValueCreate.Create(schema, references); + } + function Literal(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Never(schema, references, value) { + throw new ValueCastNeverTypeError(schema); + } + function Not(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema.allOf[1], references); + } + function Null(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Number(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Object(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return value; + if (value === null || typeof value !== 'object') + return create_1.ValueCreate.Create(schema, references); + const required = new Set(schema.required || []); + const result = {}; + for (const [key, property] of globalThis.Object.entries(schema.properties)) { + if (!required.has(key) && value[key] === undefined) + continue; + result[key] = Visit(property, references, value[key]); + } + // additional schema properties + if (typeof schema.additionalProperties === 'object') { + const propertyNames = globalThis.Object.getOwnPropertyNames(schema.properties); + for (const propertyName of globalThis.Object.getOwnPropertyNames(value)) { + if (propertyNames.includes(propertyName)) + continue; + result[propertyName] = Visit(schema.additionalProperties, references, value[propertyName]); + } + } + return result; + } + function Promise(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Record(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value) || value instanceof globalThis.Date) + return create_1.ValueCreate.Create(schema, references); + const subschemaPropertyName = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0]; + const subschema = schema.patternProperties[subschemaPropertyName]; + const result = {}; + for (const [propKey, propValue] of globalThis.Object.entries(value)) { + result[propKey] = Visit(subschema, references, propValue); + } + return result; + } + function Ref(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueCastDereferenceError(schema); + const target = references[index]; + return Visit(target, references, value); + } + function String(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Symbol(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function TemplateLiteral(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function This(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueCastDereferenceError(schema); + const target = references[index]; + return Visit(target, references, value); + } + function Tuple(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + if (!globalThis.Array.isArray(value)) + return create_1.ValueCreate.Create(schema, references); + if (schema.items === undefined) + return []; + return schema.items.map((schema, index) => Visit(schema, references, value[index])); + } + function Undefined(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function Union(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : UnionCastCreate.Create(schema, references, value); + } + function Uint8Array(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function Unknown(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function Void(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function UserDefined(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + } + function Visit(schema, references, value) { + const references_ = IsString(schema.$id) ? [...references, schema] : references; + const schema_ = schema; + switch (schema[Types.Kind]) { + case 'Any': + return Any(schema_, references_, value); + case 'Array': + return Array(schema_, references_, value); + case 'BigInt': + return BigInt(schema_, references_, value); + case 'Boolean': + return Boolean(schema_, references_, value); + case 'Constructor': + return Constructor(schema_, references_, value); + case 'Date': + return Date(schema_, references_, value); + case 'Function': + return Function(schema_, references_, value); + case 'Integer': + return Integer(schema_, references_, value); + case 'Intersect': + return Intersect(schema_, references_, value); + case 'Literal': + return Literal(schema_, references_, value); + case 'Never': + return Never(schema_, references_, value); + case 'Not': + return Not(schema_, references_, value); + case 'Null': + return Null(schema_, references_, value); + case 'Number': + return Number(schema_, references_, value); + case 'Object': + return Object(schema_, references_, value); + case 'Promise': + return Promise(schema_, references_, value); + case 'Record': + return Record(schema_, references_, value); + case 'Ref': + return Ref(schema_, references_, value); + case 'String': + return String(schema_, references_, value); + case 'Symbol': + return Symbol(schema_, references_, value); + case 'TemplateLiteral': + return TemplateLiteral(schema_, references_, value); + case 'This': + return This(schema_, references_, value); + case 'Tuple': + return Tuple(schema_, references_, value); + case 'Undefined': + return Undefined(schema_, references_, value); + case 'Union': + return Union(schema_, references_, value); + case 'Uint8Array': + return Uint8Array(schema_, references_, value); + case 'Unknown': + return Unknown(schema_, references_, value); + case 'Void': + return Void(schema_, references_, value); + default: + if (!Types.TypeRegistry.Has(schema_[Types.Kind])) + throw new ValueCastUnknownTypeError(schema_); + return UserDefined(schema_, references_, value); + } + } + ValueCast.Visit = Visit; + function Cast(schema, references, value) { + return Visit(schema, references, clone_1.ValueClone.Clone(value)); + } + ValueCast.Cast = Cast; +})(ValueCast = exports.ValueCast || (exports.ValueCast = {})); diff --git a/web/node_modules/@sinclair/typebox/value/check.d.ts b/web/node_modules/@sinclair/typebox/value/check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee18d9b0d203f46b496f3c585a4e98ad58571594 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/check.d.ts @@ -0,0 +1,12 @@ +import * as Types from '../typebox'; +export declare class ValueCheckUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCheckDereferenceError extends Error { + readonly schema: Types.TRef | Types.TThis; + constructor(schema: Types.TRef | Types.TThis); +} +export declare namespace ValueCheck { + function Check(schema: T, references: Types.TSchema[], value: any): boolean; +} diff --git a/web/node_modules/@sinclair/typebox/value/check.js b/web/node_modules/@sinclair/typebox/value/check.js new file mode 100644 index 0000000000000000000000000000000000000000..833aa6487f01cbb81a0b18924d96c55662f3a3a9 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/check.js @@ -0,0 +1,484 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueCheck = exports.ValueCheckDereferenceError = exports.ValueCheckUnknownTypeError = void 0; +const Types = require("../typebox"); +const index_1 = require("../system/index"); +const hash_1 = require("./hash"); +// ------------------------------------------------------------------------- +// Errors +// ------------------------------------------------------------------------- +class ValueCheckUnknownTypeError extends Error { + constructor(schema) { + super(`ValueCheck: ${schema[Types.Kind] ? `Unknown type '${schema[Types.Kind]}'` : 'Unknown type'}`); + this.schema = schema; + } +} +exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError; +class ValueCheckDereferenceError extends Error { + constructor(schema) { + super(`ValueCheck: Unable to dereference schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueCheckDereferenceError = ValueCheckDereferenceError; +var ValueCheck; +(function (ValueCheck) { + // ---------------------------------------------------------------------- + // Guards + // ---------------------------------------------------------------------- + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsInteger(value) { + return globalThis.Number.isInteger(value); + } + function IsString(value) { + return typeof value === 'string'; + } + function IsDefined(value) { + return value !== undefined; + } + // ---------------------------------------------------------------------- + // Policies + // ---------------------------------------------------------------------- + function IsExactOptionalProperty(value, key) { + return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined; + } + function IsObject(value) { + const result = typeof value === 'object' && value !== null; + return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value); + } + function IsRecordObject(value) { + return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array); + } + function IsNumber(value) { + const result = typeof value === 'number'; + return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value); + } + function IsVoid(value) { + const result = value === undefined; + return index_1.TypeSystem.AllowVoidNull ? result || value === null : result; + } + // ---------------------------------------------------------------------- + // Types + // ---------------------------------------------------------------------- + function Any(schema, references, value) { + return true; + } + function Array(schema, references, value) { + if (!globalThis.Array.isArray(value)) { + return false; + } + if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) { + return false; + } + if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) { + return false; + } + // prettier-ignore + if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) { + const hashed = hash_1.ValueHash.Create(element); + if (set.has(hashed)) { + return false; + } + else { + set.add(hashed); + } + } return true; })())) { + return false; + } + return value.every((value) => Visit(schema.items, references, value)); + } + function BigInt(schema, references, value) { + if (!IsBigInt(value)) { + return false; + } + if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) { + return false; + } + if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) { + return false; + } + if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) { + return false; + } + if (IsDefined(schema.minimum) && !(value >= schema.minimum)) { + return false; + } + if (IsDefined(schema.maximum) && !(value <= schema.maximum)) { + return false; + } + return true; + } + function Boolean(schema, references, value) { + return typeof value === 'boolean'; + } + function Constructor(schema, references, value) { + return Visit(schema.returns, references, value.prototype); + } + function Date(schema, references, value) { + if (!(value instanceof globalThis.Date)) { + return false; + } + if (!IsNumber(value.getTime())) { + return false; + } + if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) { + return false; + } + if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) { + return false; + } + if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) { + return false; + } + if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) { + return false; + } + return true; + } + function Function(schema, references, value) { + return typeof value === 'function'; + } + function Integer(schema, references, value) { + if (!IsInteger(value)) { + return false; + } + if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) { + return false; + } + if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) { + return false; + } + if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) { + return false; + } + if (IsDefined(schema.minimum) && !(value >= schema.minimum)) { + return false; + } + if (IsDefined(schema.maximum) && !(value <= schema.maximum)) { + return false; + } + return true; + } + function Intersect(schema, references, value) { + if (!schema.allOf.every((schema) => Visit(schema, references, value))) { + return false; + } + else if (schema.unevaluatedProperties === false) { + const schemaKeys = Types.KeyResolver.Resolve(schema); + const valueKeys = globalThis.Object.getOwnPropertyNames(value); + return valueKeys.every((key) => schemaKeys.includes(key)); + } + else if (Types.TypeGuard.TSchema(schema.unevaluatedProperties)) { + const schemaKeys = Types.KeyResolver.Resolve(schema); + const valueKeys = globalThis.Object.getOwnPropertyNames(value); + return valueKeys.every((key) => schemaKeys.includes(key) || Visit(schema.unevaluatedProperties, references, value[key])); + } + else { + return true; + } + } + function Literal(schema, references, value) { + return value === schema.const; + } + function Never(schema, references, value) { + return false; + } + function Not(schema, references, value) { + return !Visit(schema.allOf[0].not, references, value) && Visit(schema.allOf[1], references, value); + } + function Null(schema, references, value) { + return value === null; + } + function Number(schema, references, value) { + if (!IsNumber(value)) { + return false; + } + if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) { + return false; + } + if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) { + return false; + } + if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) { + return false; + } + if (IsDefined(schema.minimum) && !(value >= schema.minimum)) { + return false; + } + if (IsDefined(schema.maximum) && !(value <= schema.maximum)) { + return false; + } + return true; + } + function Object(schema, references, value) { + if (!IsObject(value)) { + return false; + } + if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) { + return false; + } + if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) { + return false; + } + const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties); + for (const knownKey of knownKeys) { + const property = schema.properties[knownKey]; + if (schema.required && schema.required.includes(knownKey)) { + if (!Visit(property, references, value[knownKey])) { + return false; + } + if (Types.ExtendsUndefined.Check(property)) { + return knownKey in value; + } + } + else { + if (IsExactOptionalProperty(value, knownKey) && !Visit(property, references, value[knownKey])) { + return false; + } + } + } + if (schema.additionalProperties === false) { + const valueKeys = globalThis.Object.getOwnPropertyNames(value); + // optimization: value is valid if schemaKey length matches the valueKey length + if (schema.required && schema.required.length === knownKeys.length && valueKeys.length === knownKeys.length) { + return true; + } + else { + return valueKeys.every((valueKey) => knownKeys.includes(valueKey)); + } + } + else if (typeof schema.additionalProperties === 'object') { + const valueKeys = globalThis.Object.getOwnPropertyNames(value); + return valueKeys.every((key) => knownKeys.includes(key) || Visit(schema.additionalProperties, references, value[key])); + } + else { + return true; + } + } + function Promise(schema, references, value) { + return typeof value === 'object' && typeof value.then === 'function'; + } + function Record(schema, references, value) { + if (!IsRecordObject(value)) { + return false; + } + if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) { + return false; + } + if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) { + return false; + } + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + const regex = new RegExp(keyPattern); + if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) { + return false; + } + for (const propValue of globalThis.Object.values(value)) { + if (!Visit(valueSchema, references, propValue)) + return false; + } + return true; + } + function Ref(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueCheckDereferenceError(schema); + const target = references[index]; + return Visit(target, references, value); + } + function String(schema, references, value) { + if (!IsString(value)) { + return false; + } + if (IsDefined(schema.minLength)) { + if (!(value.length >= schema.minLength)) + return false; + } + if (IsDefined(schema.maxLength)) { + if (!(value.length <= schema.maxLength)) + return false; + } + if (IsDefined(schema.pattern)) { + const regex = new RegExp(schema.pattern); + if (!regex.test(value)) + return false; + } + if (IsDefined(schema.format)) { + if (!Types.FormatRegistry.Has(schema.format)) + return false; + const func = Types.FormatRegistry.Get(schema.format); + return func(value); + } + return true; + } + function Symbol(schema, references, value) { + if (!(typeof value === 'symbol')) { + return false; + } + return true; + } + function TemplateLiteral(schema, references, value) { + if (!IsString(value)) { + return false; + } + return new RegExp(schema.pattern).test(value); + } + function This(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueCheckDereferenceError(schema); + const target = references[index]; + return Visit(target, references, value); + } + function Tuple(schema, references, value) { + if (!globalThis.Array.isArray(value)) { + return false; + } + if (schema.items === undefined && !(value.length === 0)) { + return false; + } + if (!(value.length === schema.maxItems)) { + return false; + } + if (!schema.items) { + return true; + } + for (let i = 0; i < schema.items.length; i++) { + if (!Visit(schema.items[i], references, value[i])) + return false; + } + return true; + } + function Undefined(schema, references, value) { + return value === undefined; + } + function Union(schema, references, value) { + return schema.anyOf.some((inner) => Visit(inner, references, value)); + } + function Uint8Array(schema, references, value) { + if (!(value instanceof globalThis.Uint8Array)) { + return false; + } + if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) { + return false; + } + if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) { + return false; + } + return true; + } + function Unknown(schema, references, value) { + return true; + } + function Void(schema, references, value) { + return IsVoid(value); + } + function UserDefined(schema, references, value) { + if (!Types.TypeRegistry.Has(schema[Types.Kind])) + return false; + const func = Types.TypeRegistry.Get(schema[Types.Kind]); + return func(schema, value); + } + function Visit(schema, references, value) { + const references_ = IsDefined(schema.$id) ? [...references, schema] : references; + const schema_ = schema; + switch (schema_[Types.Kind]) { + case 'Any': + return Any(schema_, references_, value); + case 'Array': + return Array(schema_, references_, value); + case 'BigInt': + return BigInt(schema_, references_, value); + case 'Boolean': + return Boolean(schema_, references_, value); + case 'Constructor': + return Constructor(schema_, references_, value); + case 'Date': + return Date(schema_, references_, value); + case 'Function': + return Function(schema_, references_, value); + case 'Integer': + return Integer(schema_, references_, value); + case 'Intersect': + return Intersect(schema_, references_, value); + case 'Literal': + return Literal(schema_, references_, value); + case 'Never': + return Never(schema_, references_, value); + case 'Not': + return Not(schema_, references_, value); + case 'Null': + return Null(schema_, references_, value); + case 'Number': + return Number(schema_, references_, value); + case 'Object': + return Object(schema_, references_, value); + case 'Promise': + return Promise(schema_, references_, value); + case 'Record': + return Record(schema_, references_, value); + case 'Ref': + return Ref(schema_, references_, value); + case 'String': + return String(schema_, references_, value); + case 'Symbol': + return Symbol(schema_, references_, value); + case 'TemplateLiteral': + return TemplateLiteral(schema_, references_, value); + case 'This': + return This(schema_, references_, value); + case 'Tuple': + return Tuple(schema_, references_, value); + case 'Undefined': + return Undefined(schema_, references_, value); + case 'Union': + return Union(schema_, references_, value); + case 'Uint8Array': + return Uint8Array(schema_, references_, value); + case 'Unknown': + return Unknown(schema_, references_, value); + case 'Void': + return Void(schema_, references_, value); + default: + if (!Types.TypeRegistry.Has(schema_[Types.Kind])) + throw new ValueCheckUnknownTypeError(schema_); + return UserDefined(schema_, references_, value); + } + } + // ------------------------------------------------------------------------- + // Check + // ------------------------------------------------------------------------- + function Check(schema, references, value) { + return Visit(schema, references, value); + } + ValueCheck.Check = Check; +})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {})); diff --git a/web/node_modules/@sinclair/typebox/value/clone.d.ts b/web/node_modules/@sinclair/typebox/value/clone.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ca0adf13d75cab9e9db943a0a6c88878bb5b661 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/clone.d.ts @@ -0,0 +1,3 @@ +export declare namespace ValueClone { + function Clone(value: T): T; +} diff --git a/web/node_modules/@sinclair/typebox/value/clone.js b/web/node_modules/@sinclair/typebox/value/clone.js new file mode 100644 index 0000000000000000000000000000000000000000..75e2685cd32f9d54c3263759978694d0e5b84880 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/clone.js @@ -0,0 +1,71 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueClone = void 0; +const is_1 = require("./is"); +var ValueClone; +(function (ValueClone) { + function Array(value) { + return value.map((element) => Clone(element)); + } + function Date(value) { + return new globalThis.Date(value.toISOString()); + } + function Object(value) { + const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)]; + return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {}); + } + function TypedArray(value) { + return value.slice(); + } + function Value(value) { + return value; + } + function Clone(value) { + if (is_1.Is.Date(value)) { + return Date(value); + } + else if (is_1.Is.Object(value)) { + return Object(value); + } + else if (is_1.Is.Array(value)) { + return Array(value); + } + else if (is_1.Is.TypedArray(value)) { + return TypedArray(value); + } + else if (is_1.Is.Value(value)) { + return Value(value); + } + else { + throw new Error('ValueClone: Unable to clone value'); + } + } + ValueClone.Clone = Clone; +})(ValueClone = exports.ValueClone || (exports.ValueClone = {})); diff --git a/web/node_modules/@sinclair/typebox/value/convert.d.ts b/web/node_modules/@sinclair/typebox/value/convert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..99c5d5d30b0f8493f068512b41d0c5740f93416b --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/convert.d.ts @@ -0,0 +1,13 @@ +import * as Types from '../typebox'; +export declare class ValueConvertUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueConvertDereferenceError extends Error { + readonly schema: Types.TRef | Types.TThis; + constructor(schema: Types.TRef | Types.TThis); +} +export declare namespace ValueConvert { + function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): unknown; + function Convert(schema: T, references: Types.TSchema[], value: any): unknown; +} diff --git a/web/node_modules/@sinclair/typebox/value/convert.js b/web/node_modules/@sinclair/typebox/value/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..70df03bb0bbf6f2fd3e7cdab44f885ebe88d901c --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/convert.js @@ -0,0 +1,372 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueConvert = exports.ValueConvertDereferenceError = exports.ValueConvertUnknownTypeError = void 0; +const Types = require("../typebox"); +const clone_1 = require("./clone"); +const check_1 = require("./check"); +// ---------------------------------------------------------------------------------------------- +// Errors +// ---------------------------------------------------------------------------------------------- +class ValueConvertUnknownTypeError extends Error { + constructor(schema) { + super('ValueConvert: Unknown type'); + this.schema = schema; + } +} +exports.ValueConvertUnknownTypeError = ValueConvertUnknownTypeError; +class ValueConvertDereferenceError extends Error { + constructor(schema) { + super(`ValueConvert: Unable to dereference schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueConvertDereferenceError = ValueConvertDereferenceError; +var ValueConvert; +(function (ValueConvert) { + // ---------------------------------------------------------------------------------------------- + // Guards + // ---------------------------------------------------------------------------------------------- + function IsObject(value) { + return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value); + } + function IsArray(value) { + return typeof value === 'object' && globalThis.Array.isArray(value); + } + function IsDate(value) { + return typeof value === 'object' && value instanceof globalThis.Date; + } + function IsSymbol(value) { + return typeof value === 'symbol'; + } + function IsString(value) { + return typeof value === 'string'; + } + function IsBoolean(value) { + return typeof value === 'boolean'; + } + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsNumber(value) { + return typeof value === 'number' && !isNaN(value); + } + function IsStringNumeric(value) { + return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value)); + } + function IsValueToString(value) { + return IsBigInt(value) || IsBoolean(value) || IsNumber(value); + } + function IsValueTrue(value) { + return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === globalThis.BigInt('1')) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1')); + } + function IsValueFalse(value) { + return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === globalThis.BigInt('0')) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0')); + } + function IsTimeStringWithTimeZone(value) { + return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value); + } + function IsTimeStringWithoutTimeZone(value) { + return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value); + } + function IsDateTimeStringWithTimeZone(value) { + return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value); + } + function IsDateTimeStringWithoutTimeZone(value) { + return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value); + } + function IsDateString(value) { + return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\d$/i.test(value); + } + // ---------------------------------------------------------------------------------------------- + // Convert + // ---------------------------------------------------------------------------------------------- + function TryConvertLiteralString(value, target) { + const conversion = TryConvertString(value); + return conversion === target ? conversion : value; + } + function TryConvertLiteralNumber(value, target) { + const conversion = TryConvertNumber(value); + return conversion === target ? conversion : value; + } + function TryConvertLiteralBoolean(value, target) { + const conversion = TryConvertBoolean(value); + return conversion === target ? conversion : value; + } + function TryConvertLiteral(schema, value) { + if (typeof schema.const === 'string') { + return TryConvertLiteralString(value, schema.const); + } + else if (typeof schema.const === 'number') { + return TryConvertLiteralNumber(value, schema.const); + } + else if (typeof schema.const === 'boolean') { + return TryConvertLiteralBoolean(value, schema.const); + } + else { + return clone_1.ValueClone.Clone(value); + } + } + function TryConvertBoolean(value) { + return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value; + } + function TryConvertBigInt(value) { + return IsStringNumeric(value) ? globalThis.BigInt(parseInt(value)) : IsNumber(value) ? globalThis.BigInt(value | 0) : IsValueFalse(value) ? 0 : IsValueTrue(value) ? 1 : value; + } + function TryConvertString(value) { + return IsValueToString(value) ? value.toString() : IsSymbol(value) && value.description !== undefined ? value.description.toString() : value; + } + function TryConvertNumber(value) { + return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value; + } + function TryConvertInteger(value) { + return IsStringNumeric(value) ? parseInt(value) : IsNumber(value) ? value | 0 : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value; + } + function TryConvertNull(value) { + return IsString(value) && value.toLowerCase() === 'null' ? null : value; + } + function TryConvertUndefined(value) { + return IsString(value) && value === 'undefined' ? undefined : value; + } + function TryConvertDate(value) { + // note: this function may return an invalid dates for the regex tests + // above. Invalid dates will however be checked during the casting + // function and will return a epoch date if invalid. Consider better + // string parsing for the iso dates in future revisions. + return IsDate(value) + ? value + : IsNumber(value) + ? new globalThis.Date(value) + : IsValueTrue(value) + ? new globalThis.Date(1) + : IsValueFalse(value) + ? new globalThis.Date(0) + : IsStringNumeric(value) + ? new globalThis.Date(parseInt(value)) + : IsTimeStringWithoutTimeZone(value) + ? new globalThis.Date(`1970-01-01T${value}.000Z`) + : IsTimeStringWithTimeZone(value) + ? new globalThis.Date(`1970-01-01T${value}`) + : IsDateTimeStringWithoutTimeZone(value) + ? new globalThis.Date(`${value}.000Z`) + : IsDateTimeStringWithTimeZone(value) + ? new globalThis.Date(value) + : IsDateString(value) + ? new globalThis.Date(`${value}T00:00:00.000Z`) + : value; + } + // ---------------------------------------------------------------------------------------------- + // Cast + // ---------------------------------------------------------------------------------------------- + function Any(schema, references, value) { + return value; + } + function Array(schema, references, value) { + if (IsArray(value)) { + return value.map((value) => Visit(schema.items, references, value)); + } + return value; + } + function BigInt(schema, references, value) { + return TryConvertBigInt(value); + } + function Boolean(schema, references, value) { + return TryConvertBoolean(value); + } + function Constructor(schema, references, value) { + return clone_1.ValueClone.Clone(value); + } + function Date(schema, references, value) { + return TryConvertDate(value); + } + function Function(schema, references, value) { + return value; + } + function Integer(schema, references, value) { + return TryConvertInteger(value); + } + function Intersect(schema, references, value) { + return value; + } + function Literal(schema, references, value) { + return TryConvertLiteral(schema, value); + } + function Never(schema, references, value) { + return value; + } + function Null(schema, references, value) { + return TryConvertNull(value); + } + function Number(schema, references, value) { + return TryConvertNumber(value); + } + function Object(schema, references, value) { + if (IsObject(value)) + return globalThis.Object.keys(schema.properties).reduce((acc, key) => { + return value[key] !== undefined ? { ...acc, [key]: Visit(schema.properties[key], references, value[key]) } : { ...acc }; + }, value); + return value; + } + function Promise(schema, references, value) { + return value; + } + function Record(schema, references, value) { + const propertyKey = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0]; + const property = schema.patternProperties[propertyKey]; + const result = {}; + for (const [propKey, propValue] of globalThis.Object.entries(value)) { + result[propKey] = Visit(property, references, propValue); + } + return result; + } + function Ref(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueConvertDereferenceError(schema); + const target = references[index]; + return Visit(target, references, value); + } + function String(schema, references, value) { + return TryConvertString(value); + } + function Symbol(schema, references, value) { + return value; + } + function TemplateLiteral(schema, references, value) { + return value; + } + function This(schema, references, value) { + const index = references.findIndex((foreign) => foreign.$id === schema.$ref); + if (index === -1) + throw new ValueConvertDereferenceError(schema); + const target = references[index]; + return Visit(target, references, value); + } + function Tuple(schema, references, value) { + if (IsArray(value) && schema.items !== undefined) { + return value.map((value, index) => { + return index < schema.items.length ? Visit(schema.items[index], references, value) : value; + }); + } + return value; + } + function Undefined(schema, references, value) { + return TryConvertUndefined(value); + } + function Union(schema, references, value) { + for (const subschema of schema.anyOf) { + const converted = Visit(subschema, references, value); + if (check_1.ValueCheck.Check(subschema, references, converted)) { + return converted; + } + } + return value; + } + function Uint8Array(schema, references, value) { + return value; + } + function Unknown(schema, references, value) { + return value; + } + function Void(schema, references, value) { + return value; + } + function UserDefined(schema, references, value) { + return value; + } + function Visit(schema, references, value) { + const references_ = IsString(schema.$id) ? [...references, schema] : references; + const schema_ = schema; + switch (schema[Types.Kind]) { + case 'Any': + return Any(schema_, references_, value); + case 'Array': + return Array(schema_, references_, value); + case 'BigInt': + return BigInt(schema_, references_, value); + case 'Boolean': + return Boolean(schema_, references_, value); + case 'Constructor': + return Constructor(schema_, references_, value); + case 'Date': + return Date(schema_, references_, value); + case 'Function': + return Function(schema_, references_, value); + case 'Integer': + return Integer(schema_, references_, value); + case 'Intersect': + return Intersect(schema_, references_, value); + case 'Literal': + return Literal(schema_, references_, value); + case 'Never': + return Never(schema_, references_, value); + case 'Null': + return Null(schema_, references_, value); + case 'Number': + return Number(schema_, references_, value); + case 'Object': + return Object(schema_, references_, value); + case 'Promise': + return Promise(schema_, references_, value); + case 'Record': + return Record(schema_, references_, value); + case 'Ref': + return Ref(schema_, references_, value); + case 'String': + return String(schema_, references_, value); + case 'Symbol': + return Symbol(schema_, references_, value); + case 'TemplateLiteral': + return TemplateLiteral(schema_, references_, value); + case 'This': + return This(schema_, references_, value); + case 'Tuple': + return Tuple(schema_, references_, value); + case 'Undefined': + return Undefined(schema_, references_, value); + case 'Union': + return Union(schema_, references_, value); + case 'Uint8Array': + return Uint8Array(schema_, references_, value); + case 'Unknown': + return Unknown(schema_, references_, value); + case 'Void': + return Void(schema_, references_, value); + default: + if (!Types.TypeRegistry.Has(schema_[Types.Kind])) + throw new ValueConvertUnknownTypeError(schema_); + return UserDefined(schema_, references_, value); + } + } + ValueConvert.Visit = Visit; + function Convert(schema, references, value) { + return Visit(schema, references, clone_1.ValueClone.Clone(value)); + } + ValueConvert.Convert = Convert; +})(ValueConvert = exports.ValueConvert || (exports.ValueConvert = {})); diff --git a/web/node_modules/@sinclair/typebox/value/create.d.ts b/web/node_modules/@sinclair/typebox/value/create.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86e1e5e09d2ce17e03830300a568126533c470f6 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/create.d.ts @@ -0,0 +1,26 @@ +import * as Types from '../typebox'; +export declare class ValueCreateUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCreateNeverTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCreateIntersectTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCreateTempateLiteralTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCreateDereferenceError extends Error { + readonly schema: Types.TRef | Types.TThis; + constructor(schema: Types.TRef | Types.TThis); +} +export declare namespace ValueCreate { + /** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */ + function Visit(schema: Types.TSchema, references: Types.TSchema[]): unknown; + function Create(schema: T, references: Types.TSchema[]): Types.Static; +} diff --git a/web/node_modules/@sinclair/typebox/value/create.js b/web/node_modules/@sinclair/typebox/value/create.js new file mode 100644 index 0000000000000000000000000000000000000000..42374a8b50dba711de374a2c1ede354160667de2 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/create.js @@ -0,0 +1,480 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueCreate = exports.ValueCreateDereferenceError = exports.ValueCreateTempateLiteralTypeError = exports.ValueCreateIntersectTypeError = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0; +const Types = require("../typebox"); +const check_1 = require("./check"); +// -------------------------------------------------------------------------- +// Errors +// -------------------------------------------------------------------------- +class ValueCreateUnknownTypeError extends Error { + constructor(schema) { + super('ValueCreate: Unknown type'); + this.schema = schema; + } +} +exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError; +class ValueCreateNeverTypeError extends Error { + constructor(schema) { + super('ValueCreate: Never types cannot be created'); + this.schema = schema; + } +} +exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError; +class ValueCreateIntersectTypeError extends Error { + constructor(schema) { + super('ValueCreate: Intersect produced invalid value. Consider using a default value.'); + this.schema = schema; + } +} +exports.ValueCreateIntersectTypeError = ValueCreateIntersectTypeError; +class ValueCreateTempateLiteralTypeError extends Error { + constructor(schema) { + super('ValueCreate: Can only create template literal values from patterns that produce finite sequences. Consider using a default value.'); + this.schema = schema; + } +} +exports.ValueCreateTempateLiteralTypeError = ValueCreateTempateLiteralTypeError; +class ValueCreateDereferenceError extends Error { + constructor(schema) { + super(`ValueCreate: Unable to dereference schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueCreateDereferenceError = ValueCreateDereferenceError; +// -------------------------------------------------------------------------- +// ValueCreate +// -------------------------------------------------------------------------- +var ValueCreate; +(function (ValueCreate) { + // -------------------------------------------------------- + // Guards + // -------------------------------------------------------- + function IsString(value) { + return typeof value === 'string'; + } + // -------------------------------------------------------- + // Types + // -------------------------------------------------------- + function Any(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return {}; + } + } + function Array(schema, references) { + if (schema.uniqueItems === true && schema.default === undefined) { + throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value'); + } + else if ('default' in schema) { + return schema.default; + } + else if (schema.minItems !== undefined) { + return globalThis.Array.from({ length: schema.minItems }).map((item) => { + return ValueCreate.Create(schema.items, references); + }); + } + else { + return []; + } + } + function BigInt(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return globalThis.BigInt(0); + } + } + function Boolean(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return false; + } + } + function Constructor(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + const value = ValueCreate.Create(schema.returns, references); + if (typeof value === 'object' && !globalThis.Array.isArray(value)) { + return class { + constructor() { + for (const [key, val] of globalThis.Object.entries(value)) { + const self = this; + self[key] = val; + } + } + }; + } + else { + return class { + }; + } + } + } + function Date(schema, references) { + if ('default' in schema) { + return schema.default; + } + else if (schema.minimumTimestamp !== undefined) { + return new globalThis.Date(schema.minimumTimestamp); + } + else { + return new globalThis.Date(0); + } + } + function Function(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return () => ValueCreate.Create(schema.returns, references); + } + } + function Integer(schema, references) { + if ('default' in schema) { + return schema.default; + } + else if (schema.minimum !== undefined) { + return schema.minimum; + } + else { + return 0; + } + } + function Intersect(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + // Note: The best we can do here is attempt to instance each sub type and apply through object assign. For non-object + // sub types, we just escape the assignment and just return the value. In the latter case, this is typically going to + // be a consequence of an illogical intersection. + const value = schema.allOf.reduce((acc, schema) => { + const next = Visit(schema, references); + return typeof next === 'object' ? { ...acc, ...next } : next; + }, {}); + if (!check_1.ValueCheck.Check(schema, references, value)) + throw new ValueCreateIntersectTypeError(schema); + return value; + } + } + function Literal(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return schema.const; + } + } + function Never(schema, references) { + throw new ValueCreateNeverTypeError(schema); + } + function Not(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return Visit(schema.allOf[1], references); + } + } + function Null(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return null; + } + } + function Number(schema, references) { + if ('default' in schema) { + return schema.default; + } + else if (schema.minimum !== undefined) { + return schema.minimum; + } + else { + return 0; + } + } + function Object(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + const required = new Set(schema.required); + return (schema.default || + globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => { + return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc }; + }, {})); + } + } + function Promise(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references)); + } + } + function Record(schema, references) { + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + if ('default' in schema) { + return schema.default; + } + else if (!(keyPattern === Types.PatternStringExact || keyPattern === Types.PatternNumberExact)) { + const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|'); + return propertyKeys.reduce((acc, key) => { + return { ...acc, [key]: Create(valueSchema, references) }; + }, {}); + } + else { + return {}; + } + } + function Ref(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + const index = references.findIndex((foreign) => foreign.$id === schema.$id); + if (index === -1) + throw new ValueCreateDereferenceError(schema); + const target = references[index]; + return Visit(target, references); + } + } + function String(schema, references) { + if (schema.pattern !== undefined) { + if (!('default' in schema)) { + throw new Error('ValueCreate.String: String types with patterns must specify a default value'); + } + else { + return schema.default; + } + } + else if (schema.format !== undefined) { + if (!('default' in schema)) { + throw new Error('ValueCreate.String: String types with formats must specify a default value'); + } + else { + return schema.default; + } + } + else { + if ('default' in schema) { + return schema.default; + } + else if (schema.minLength !== undefined) { + return globalThis.Array.from({ length: schema.minLength }) + .map(() => '.') + .join(''); + } + else { + return ''; + } + } + } + function Symbol(schema, references) { + if ('default' in schema) { + return schema.default; + } + else if ('value' in schema) { + return globalThis.Symbol.for(schema.value); + } + else { + return globalThis.Symbol(); + } + } + function TemplateLiteral(schema, references) { + if ('default' in schema) { + return schema.default; + } + const expression = Types.TemplateLiteralParser.ParseExact(schema.pattern); + if (!Types.TemplateLiteralFinite.Check(expression)) + throw new ValueCreateTempateLiteralTypeError(schema); + const sequence = Types.TemplateLiteralGenerator.Generate(expression); + return sequence.next().value; + } + function This(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + const index = references.findIndex((foreign) => foreign.$id === schema.$id); + if (index === -1) + throw new ValueCreateDereferenceError(schema); + const target = references[index]; + return Visit(target, references); + } + } + function Tuple(schema, references) { + if ('default' in schema) { + return schema.default; + } + if (schema.items === undefined) { + return []; + } + else { + return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references)); + } + } + function Undefined(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return undefined; + } + } + function Union(schema, references) { + if ('default' in schema) { + return schema.default; + } + else if (schema.anyOf.length === 0) { + throw new Error('ValueCreate.Union: Cannot create Union with zero variants'); + } + else { + return ValueCreate.Create(schema.anyOf[0], references); + } + } + function Uint8Array(schema, references) { + if ('default' in schema) { + return schema.default; + } + else if (schema.minByteLength !== undefined) { + return new globalThis.Uint8Array(schema.minByteLength); + } + else { + return new globalThis.Uint8Array(0); + } + } + function Unknown(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return {}; + } + } + function Void(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + return void 0; + } + } + function UserDefined(schema, references) { + if ('default' in schema) { + return schema.default; + } + else { + throw new Error('ValueCreate.UserDefined: User defined types must specify a default value'); + } + } + /** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */ + function Visit(schema, references) { + const references_ = IsString(schema.$id) ? [...references, schema] : references; + const schema_ = schema; + switch (schema_[Types.Kind]) { + case 'Any': + return Any(schema_, references_); + case 'Array': + return Array(schema_, references_); + case 'BigInt': + return BigInt(schema_, references_); + case 'Boolean': + return Boolean(schema_, references_); + case 'Constructor': + return Constructor(schema_, references_); + case 'Date': + return Date(schema_, references_); + case 'Function': + return Function(schema_, references_); + case 'Integer': + return Integer(schema_, references_); + case 'Intersect': + return Intersect(schema_, references_); + case 'Literal': + return Literal(schema_, references_); + case 'Never': + return Never(schema_, references_); + case 'Not': + return Not(schema_, references_); + case 'Null': + return Null(schema_, references_); + case 'Number': + return Number(schema_, references_); + case 'Object': + return Object(schema_, references_); + case 'Promise': + return Promise(schema_, references_); + case 'Record': + return Record(schema_, references_); + case 'Ref': + return Ref(schema_, references_); + case 'String': + return String(schema_, references_); + case 'Symbol': + return Symbol(schema_, references_); + case 'TemplateLiteral': + return TemplateLiteral(schema_, references_); + case 'This': + return This(schema_, references_); + case 'Tuple': + return Tuple(schema_, references_); + case 'Undefined': + return Undefined(schema_, references_); + case 'Union': + return Union(schema_, references_); + case 'Uint8Array': + return Uint8Array(schema_, references_); + case 'Unknown': + return Unknown(schema_, references_); + case 'Void': + return Void(schema_, references_); + default: + if (!Types.TypeRegistry.Has(schema_[Types.Kind])) + throw new ValueCreateUnknownTypeError(schema_); + return UserDefined(schema_, references_); + } + } + ValueCreate.Visit = Visit; + function Create(schema, references) { + return Visit(schema, references); + } + ValueCreate.Create = Create; +})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {})); diff --git a/web/node_modules/@sinclair/typebox/value/delta.d.ts b/web/node_modules/@sinclair/typebox/value/delta.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3320fac790d96239ba022285fa378629ed7f60a6 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/delta.d.ts @@ -0,0 +1,43 @@ +import { Static } from '../typebox'; +export type Insert = Static; +export declare const Insert: import("../typebox").TObject<{ + type: import("../typebox").TLiteral<"insert">; + path: import("../typebox").TString; + value: import("../typebox").TUnknown; +}>; +export type Update = Static; +export declare const Update: import("../typebox").TObject<{ + type: import("../typebox").TLiteral<"update">; + path: import("../typebox").TString; + value: import("../typebox").TUnknown; +}>; +export type Delete = Static; +export declare const Delete: import("../typebox").TObject<{ + type: import("../typebox").TLiteral<"delete">; + path: import("../typebox").TString; +}>; +export type Edit = Static; +export declare const Edit: import("../typebox").TUnion<[import("../typebox").TObject<{ + type: import("../typebox").TLiteral<"insert">; + path: import("../typebox").TString; + value: import("../typebox").TUnknown; +}>, import("../typebox").TObject<{ + type: import("../typebox").TLiteral<"update">; + path: import("../typebox").TString; + value: import("../typebox").TUnknown; +}>, import("../typebox").TObject<{ + type: import("../typebox").TLiteral<"delete">; + path: import("../typebox").TString; +}>]>; +export declare class ValueDeltaObjectWithSymbolKeyError extends Error { + readonly key: unknown; + constructor(key: unknown); +} +export declare class ValueDeltaUnableToDiffUnknownValue extends Error { + readonly value: unknown; + constructor(value: unknown); +} +export declare namespace ValueDelta { + function Diff(current: unknown, next: unknown): Edit[]; + function Patch(current: unknown, edits: Edit[]): T; +} diff --git a/web/node_modules/@sinclair/typebox/value/delta.js b/web/node_modules/@sinclair/typebox/value/delta.js new file mode 100644 index 0000000000000000000000000000000000000000..89c06a0d889c6cc8e97693a711e6393a80e50aa6 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/delta.js @@ -0,0 +1,204 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueDelta = exports.ValueDeltaUnableToDiffUnknownValue = exports.ValueDeltaObjectWithSymbolKeyError = exports.Edit = exports.Delete = exports.Update = exports.Insert = void 0; +const typebox_1 = require("../typebox"); +const is_1 = require("./is"); +const clone_1 = require("./clone"); +const pointer_1 = require("./pointer"); +exports.Insert = typebox_1.Type.Object({ + type: typebox_1.Type.Literal('insert'), + path: typebox_1.Type.String(), + value: typebox_1.Type.Unknown(), +}); +exports.Update = typebox_1.Type.Object({ + type: typebox_1.Type.Literal('update'), + path: typebox_1.Type.String(), + value: typebox_1.Type.Unknown(), +}); +exports.Delete = typebox_1.Type.Object({ + type: typebox_1.Type.Literal('delete'), + path: typebox_1.Type.String(), +}); +exports.Edit = typebox_1.Type.Union([exports.Insert, exports.Update, exports.Delete]); +// --------------------------------------------------------------------- +// Errors +// --------------------------------------------------------------------- +class ValueDeltaObjectWithSymbolKeyError extends Error { + constructor(key) { + super('ValueDelta: Cannot diff objects with symbol keys'); + this.key = key; + } +} +exports.ValueDeltaObjectWithSymbolKeyError = ValueDeltaObjectWithSymbolKeyError; +class ValueDeltaUnableToDiffUnknownValue extends Error { + constructor(value) { + super('ValueDelta: Unable to create diff edits for unknown value'); + this.value = value; + } +} +exports.ValueDeltaUnableToDiffUnknownValue = ValueDeltaUnableToDiffUnknownValue; +// --------------------------------------------------------------------- +// ValueDelta +// --------------------------------------------------------------------- +var ValueDelta; +(function (ValueDelta) { + // --------------------------------------------------------------------- + // Edits + // --------------------------------------------------------------------- + function Update(path, value) { + return { type: 'update', path, value }; + } + function Insert(path, value) { + return { type: 'insert', path, value }; + } + function Delete(path) { + return { type: 'delete', path }; + } + // --------------------------------------------------------------------- + // Diff + // --------------------------------------------------------------------- + function* Object(path, current, next) { + if (!is_1.Is.Object(next)) + return yield Update(path, next); + const currentKeys = [...globalThis.Object.keys(current), ...globalThis.Object.getOwnPropertySymbols(current)]; + const nextKeys = [...globalThis.Object.keys(next), ...globalThis.Object.getOwnPropertySymbols(next)]; + for (const key of currentKeys) { + if (typeof key === 'symbol') + throw new ValueDeltaObjectWithSymbolKeyError(key); + if (next[key] === undefined && nextKeys.includes(key)) + yield Update(`${path}/${String(key)}`, undefined); + } + for (const key of nextKeys) { + if (current[key] === undefined || next[key] === undefined) + continue; + if (typeof key === 'symbol') + throw new ValueDeltaObjectWithSymbolKeyError(key); + yield* Visit(`${path}/${String(key)}`, current[key], next[key]); + } + for (const key of nextKeys) { + if (typeof key === 'symbol') + throw new ValueDeltaObjectWithSymbolKeyError(key); + if (current[key] === undefined) + yield Insert(`${path}/${String(key)}`, next[key]); + } + for (const key of currentKeys.reverse()) { + if (typeof key === 'symbol') + throw new ValueDeltaObjectWithSymbolKeyError(key); + if (next[key] === undefined && !nextKeys.includes(key)) + yield Delete(`${path}/${String(key)}`); + } + } + function* Array(path, current, next) { + if (!is_1.Is.Array(next)) + return yield Update(path, next); + for (let i = 0; i < Math.min(current.length, next.length); i++) { + yield* Visit(`${path}/${i}`, current[i], next[i]); + } + for (let i = 0; i < next.length; i++) { + if (i < current.length) + continue; + yield Insert(`${path}/${i}`, next[i]); + } + for (let i = current.length - 1; i >= 0; i--) { + if (i < next.length) + continue; + yield Delete(`${path}/${i}`); + } + } + function* TypedArray(path, current, next) { + if (!is_1.Is.TypedArray(next) || current.length !== next.length || globalThis.Object.getPrototypeOf(current).constructor.name !== globalThis.Object.getPrototypeOf(next).constructor.name) + return yield Update(path, next); + for (let i = 0; i < Math.min(current.length, next.length); i++) { + yield* Visit(`${path}/${i}`, current[i], next[i]); + } + } + function* Value(path, current, next) { + if (current === next) + return; + yield Update(path, next); + } + function* Visit(path, current, next) { + if (is_1.Is.Object(current)) { + return yield* Object(path, current, next); + } + else if (is_1.Is.Array(current)) { + return yield* Array(path, current, next); + } + else if (is_1.Is.TypedArray(current)) { + return yield* TypedArray(path, current, next); + } + else if (is_1.Is.Value(current)) { + return yield* Value(path, current, next); + } + else { + throw new ValueDeltaUnableToDiffUnknownValue(current); + } + } + function Diff(current, next) { + return [...Visit('', current, next)]; + } + ValueDelta.Diff = Diff; + // --------------------------------------------------------------------- + // Patch + // --------------------------------------------------------------------- + function IsRootUpdate(edits) { + return edits.length > 0 && edits[0].path === '' && edits[0].type === 'update'; + } + function IsIdentity(edits) { + return edits.length === 0; + } + function Patch(current, edits) { + if (IsRootUpdate(edits)) { + return clone_1.ValueClone.Clone(edits[0].value); + } + if (IsIdentity(edits)) { + return clone_1.ValueClone.Clone(current); + } + const clone = clone_1.ValueClone.Clone(current); + for (const edit of edits) { + switch (edit.type) { + case 'insert': { + pointer_1.ValuePointer.Set(clone, edit.path, edit.value); + break; + } + case 'update': { + pointer_1.ValuePointer.Set(clone, edit.path, edit.value); + break; + } + case 'delete': { + pointer_1.ValuePointer.Delete(clone, edit.path); + break; + } + } + } + return clone; + } + ValueDelta.Patch = Patch; +})(ValueDelta = exports.ValueDelta || (exports.ValueDelta = {})); diff --git a/web/node_modules/@sinclair/typebox/value/equal.d.ts b/web/node_modules/@sinclair/typebox/value/equal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..785c2b8de1540d831ae2ffa94e551db2e9ad2c75 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/equal.d.ts @@ -0,0 +1,3 @@ +export declare namespace ValueEqual { + function Equal(left: T, right: unknown): right is T; +} diff --git a/web/node_modules/@sinclair/typebox/value/equal.js b/web/node_modules/@sinclair/typebox/value/equal.js new file mode 100644 index 0000000000000000000000000000000000000000..ed9773b5618f2abcdb96f3f7c5e91c37f73265b9 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/equal.js @@ -0,0 +1,80 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueEqual = void 0; +const is_1 = require("./is"); +var ValueEqual; +(function (ValueEqual) { + function Object(left, right) { + if (!is_1.Is.Object(right)) + return false; + const leftKeys = [...globalThis.Object.keys(left), ...globalThis.Object.getOwnPropertySymbols(left)]; + const rightKeys = [...globalThis.Object.keys(right), ...globalThis.Object.getOwnPropertySymbols(right)]; + if (leftKeys.length !== rightKeys.length) + return false; + return leftKeys.every((key) => Equal(left[key], right[key])); + } + function Date(left, right) { + return is_1.Is.Date(right) && left.getTime() === right.getTime(); + } + function Array(left, right) { + if (!is_1.Is.Array(right) || left.length !== right.length) + return false; + return left.every((value, index) => Equal(value, right[index])); + } + function TypedArray(left, right) { + if (!is_1.Is.TypedArray(right) || left.length !== right.length || globalThis.Object.getPrototypeOf(left).constructor.name !== globalThis.Object.getPrototypeOf(right).constructor.name) + return false; + return left.every((value, index) => Equal(value, right[index])); + } + function Value(left, right) { + return left === right; + } + function Equal(left, right) { + if (is_1.Is.Object(left)) { + return Object(left, right); + } + else if (is_1.Is.Date(left)) { + return Date(left, right); + } + else if (is_1.Is.TypedArray(left)) { + return TypedArray(left, right); + } + else if (is_1.Is.Array(left)) { + return Array(left, right); + } + else if (is_1.Is.Value(left)) { + return Value(left, right); + } + else { + throw new Error('ValueEquals: Unable to compare value'); + } + } + ValueEqual.Equal = Equal; +})(ValueEqual = exports.ValueEqual || (exports.ValueEqual = {})); diff --git a/web/node_modules/@sinclair/typebox/value/hash.d.ts b/web/node_modules/@sinclair/typebox/value/hash.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c9116b5d0ca327e5f9c6ad6be4b5a5d0c9216c4 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/hash.d.ts @@ -0,0 +1,8 @@ +export declare class ValueHashError extends Error { + readonly value: unknown; + constructor(value: unknown); +} +export declare namespace ValueHash { + /** Creates a FNV1A-64 non cryptographic hash of the given value */ + function Create(value: unknown): bigint; +} diff --git a/web/node_modules/@sinclair/typebox/value/hash.js b/web/node_modules/@sinclair/typebox/value/hash.js new file mode 100644 index 0000000000000000000000000000000000000000..959442084219a25766aaba1a03f4c39189e2abb3 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/hash.js @@ -0,0 +1,208 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/hash + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueHash = exports.ValueHashError = void 0; +class ValueHashError extends Error { + constructor(value) { + super(`Hash: Unable to hash value`); + this.value = value; + } +} +exports.ValueHashError = ValueHashError; +var ValueHash; +(function (ValueHash) { + let ByteMarker; + (function (ByteMarker) { + ByteMarker[ByteMarker["Undefined"] = 0] = "Undefined"; + ByteMarker[ByteMarker["Null"] = 1] = "Null"; + ByteMarker[ByteMarker["Boolean"] = 2] = "Boolean"; + ByteMarker[ByteMarker["Number"] = 3] = "Number"; + ByteMarker[ByteMarker["String"] = 4] = "String"; + ByteMarker[ByteMarker["Object"] = 5] = "Object"; + ByteMarker[ByteMarker["Array"] = 6] = "Array"; + ByteMarker[ByteMarker["Date"] = 7] = "Date"; + ByteMarker[ByteMarker["Uint8Array"] = 8] = "Uint8Array"; + ByteMarker[ByteMarker["Symbol"] = 9] = "Symbol"; + ByteMarker[ByteMarker["BigInt"] = 10] = "BigInt"; + })(ByteMarker || (ByteMarker = {})); + // ---------------------------------------------------- + // State + // ---------------------------------------------------- + let Hash = globalThis.BigInt('14695981039346656037'); + const [Prime, Size] = [globalThis.BigInt('1099511628211'), globalThis.BigInt('2') ** globalThis.BigInt('64')]; + const Bytes = globalThis.Array.from({ length: 256 }).map((_, i) => globalThis.BigInt(i)); + const F64 = new globalThis.Float64Array(1); + const F64In = new globalThis.DataView(F64.buffer); + const F64Out = new globalThis.Uint8Array(F64.buffer); + // ---------------------------------------------------- + // Guards + // ---------------------------------------------------- + function IsDate(value) { + return value instanceof globalThis.Date; + } + function IsUint8Array(value) { + return value instanceof globalThis.Uint8Array; + } + function IsArray(value) { + return globalThis.Array.isArray(value); + } + function IsBoolean(value) { + return typeof value === 'boolean'; + } + function IsNull(value) { + return value === null; + } + function IsNumber(value) { + return typeof value === 'number'; + } + function IsSymbol(value) { + return typeof value === 'symbol'; + } + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsObject(value) { + return typeof value === 'object' && value !== null && !IsArray(value) && !IsDate(value) && !IsUint8Array(value); + } + function IsString(value) { + return typeof value === 'string'; + } + function IsUndefined(value) { + return value === undefined; + } + // ---------------------------------------------------- + // Encoding + // ---------------------------------------------------- + function Array(value) { + FNV1A64(ByteMarker.Array); + for (const item of value) { + Visit(item); + } + } + function Boolean(value) { + FNV1A64(ByteMarker.Boolean); + FNV1A64(value ? 1 : 0); + } + function BigInt(value) { + FNV1A64(ByteMarker.BigInt); + F64In.setBigInt64(0, value); + for (const byte of F64Out) { + FNV1A64(byte); + } + } + function Date(value) { + FNV1A64(ByteMarker.Date); + Visit(value.getTime()); + } + function Null(value) { + FNV1A64(ByteMarker.Null); + } + function Number(value) { + FNV1A64(ByteMarker.Number); + F64In.setFloat64(0, value); + for (const byte of F64Out) { + FNV1A64(byte); + } + } + function Object(value) { + FNV1A64(ByteMarker.Object); + for (const key of globalThis.Object.keys(value).sort()) { + Visit(key); + Visit(value[key]); + } + } + function String(value) { + FNV1A64(ByteMarker.String); + for (let i = 0; i < value.length; i++) { + FNV1A64(value.charCodeAt(i)); + } + } + function Symbol(value) { + FNV1A64(ByteMarker.Symbol); + Visit(value.description); + } + function Uint8Array(value) { + FNV1A64(ByteMarker.Uint8Array); + for (let i = 0; i < value.length; i++) { + FNV1A64(value[i]); + } + } + function Undefined(value) { + return FNV1A64(ByteMarker.Undefined); + } + function Visit(value) { + if (IsArray(value)) { + Array(value); + } + else if (IsBoolean(value)) { + Boolean(value); + } + else if (IsBigInt(value)) { + BigInt(value); + } + else if (IsDate(value)) { + Date(value); + } + else if (IsNull(value)) { + Null(value); + } + else if (IsNumber(value)) { + Number(value); + } + else if (IsObject(value)) { + Object(value); + } + else if (IsString(value)) { + String(value); + } + else if (IsSymbol(value)) { + Symbol(value); + } + else if (IsUint8Array(value)) { + Uint8Array(value); + } + else if (IsUndefined(value)) { + Undefined(value); + } + else { + throw new ValueHashError(value); + } + } + function FNV1A64(byte) { + Hash = Hash ^ Bytes[byte]; + Hash = (Hash * Prime) % Size; + } + /** Creates a FNV1A-64 non cryptographic hash of the given value */ + function Create(value) { + Hash = globalThis.BigInt('14695981039346656037'); + Visit(value); + return Hash; + } + ValueHash.Create = Create; +})(ValueHash = exports.ValueHash || (exports.ValueHash = {})); diff --git a/web/node_modules/@sinclair/typebox/value/index.d.ts b/web/node_modules/@sinclair/typebox/value/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ad0b778b4c32ede29477e6856fd44aaade59065 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/index.d.ts @@ -0,0 +1,6 @@ +export { ValueError, ValueErrorIterator, ValueErrorType } from '../errors/index'; +export { ValueHash } from './hash'; +export { Edit, Insert, Update, Delete } from './delta'; +export { Mutable } from './mutate'; +export * from './pointer'; +export * from './value'; diff --git a/web/node_modules/@sinclair/typebox/value/index.js b/web/node_modules/@sinclair/typebox/value/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1f21de4d31381c1e55c4eebfae8429cb3f4f3077 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/index.js @@ -0,0 +1,56 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +var __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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Delete = exports.Update = exports.Insert = exports.Edit = exports.ValueHash = exports.ValueErrorType = exports.ValueErrorIterator = void 0; +var index_1 = require("../errors/index"); +Object.defineProperty(exports, "ValueErrorIterator", { enumerable: true, get: function () { return index_1.ValueErrorIterator; } }); +Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } }); +var hash_1 = require("./hash"); +Object.defineProperty(exports, "ValueHash", { enumerable: true, get: function () { return hash_1.ValueHash; } }); +var delta_1 = require("./delta"); +Object.defineProperty(exports, "Edit", { enumerable: true, get: function () { return delta_1.Edit; } }); +Object.defineProperty(exports, "Insert", { enumerable: true, get: function () { return delta_1.Insert; } }); +Object.defineProperty(exports, "Update", { enumerable: true, get: function () { return delta_1.Update; } }); +Object.defineProperty(exports, "Delete", { enumerable: true, get: function () { return delta_1.Delete; } }); +__exportStar(require("./pointer"), exports); +__exportStar(require("./value"), exports); diff --git a/web/node_modules/@sinclair/typebox/value/is.d.ts b/web/node_modules/@sinclair/typebox/value/is.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b78ba9c2591aa80b7ab5333236e24c6c53ecccf9 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/is.d.ts @@ -0,0 +1,11 @@ +export type ValueType = null | undefined | Function | symbol | bigint | number | boolean | string; +export type ObjectType = Record; +export type TypedArrayType = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +export type ArrayType = unknown[]; +export declare namespace Is { + function Object(value: unknown): value is ObjectType; + function Date(value: unknown): value is Date; + function Array(value: unknown): value is ArrayType; + function Value(value: unknown): value is ValueType; + function TypedArray(value: unknown): value is TypedArrayType; +} diff --git a/web/node_modules/@sinclair/typebox/value/is.js b/web/node_modules/@sinclair/typebox/value/is.js new file mode 100644 index 0000000000000000000000000000000000000000..fbe1ed43be7019e8a2636c86db5ce7dfb4a76488 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/is.js @@ -0,0 +1,53 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Is = void 0; +var Is; +(function (Is) { + function Object(value) { + return value !== null && typeof value === 'object' && !globalThis.Array.isArray(value) && !ArrayBuffer.isView(value) && !(value instanceof globalThis.Date); + } + Is.Object = Object; + function Date(value) { + return value instanceof globalThis.Date; + } + Is.Date = Date; + function Array(value) { + return globalThis.Array.isArray(value) && !ArrayBuffer.isView(value); + } + Is.Array = Array; + function Value(value) { + return value === null || value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string'; + } + Is.Value = Value; + function TypedArray(value) { + return ArrayBuffer.isView(value); + } + Is.TypedArray = TypedArray; +})(Is = exports.Is || (exports.Is = {})); diff --git a/web/node_modules/@sinclair/typebox/value/mutate.d.ts b/web/node_modules/@sinclair/typebox/value/mutate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e45c07e2bc5aa7a04a360f86eec46ce717f1b8e5 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/mutate.d.ts @@ -0,0 +1,13 @@ +export declare class ValueMutateTypeMismatchError extends Error { + constructor(); +} +export declare class ValueMutateInvalidRootMutationError extends Error { + constructor(); +} +export type Mutable = { + [key: string]: unknown; +} | unknown[]; +export declare namespace ValueMutate { + /** Performs a deep mutable value assignment while retaining internal references. */ + function Mutate(current: Mutable, next: Mutable): void; +} diff --git a/web/node_modules/@sinclair/typebox/value/mutate.js b/web/node_modules/@sinclair/typebox/value/mutate.js new file mode 100644 index 0000000000000000000000000000000000000000..4151596b36305ba2113aa43961683e896c0fcd3a --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/mutate.js @@ -0,0 +1,121 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueMutate = exports.ValueMutateInvalidRootMutationError = exports.ValueMutateTypeMismatchError = void 0; +const is_1 = require("./is"); +const pointer_1 = require("./pointer"); +const clone_1 = require("./clone"); +class ValueMutateTypeMismatchError extends Error { + constructor() { + super('ValueMutate: Cannot assign due type mismatch of assignable values'); + } +} +exports.ValueMutateTypeMismatchError = ValueMutateTypeMismatchError; +class ValueMutateInvalidRootMutationError extends Error { + constructor() { + super('ValueMutate: Only object and array types can be mutated at the root level'); + } +} +exports.ValueMutateInvalidRootMutationError = ValueMutateInvalidRootMutationError; +var ValueMutate; +(function (ValueMutate) { + function Object(root, path, current, next) { + if (!is_1.Is.Object(current)) { + pointer_1.ValuePointer.Set(root, path, clone_1.ValueClone.Clone(next)); + } + else { + const currentKeys = globalThis.Object.keys(current); + const nextKeys = globalThis.Object.keys(next); + for (const currentKey of currentKeys) { + if (!nextKeys.includes(currentKey)) { + delete current[currentKey]; + } + } + for (const nextKey of nextKeys) { + if (!currentKeys.includes(nextKey)) { + current[nextKey] = null; + } + } + for (const nextKey of nextKeys) { + Visit(root, `${path}/${nextKey}`, current[nextKey], next[nextKey]); + } + } + } + function Array(root, path, current, next) { + if (!is_1.Is.Array(current)) { + pointer_1.ValuePointer.Set(root, path, clone_1.ValueClone.Clone(next)); + } + else { + for (let index = 0; index < next.length; index++) { + Visit(root, `${path}/${index}`, current[index], next[index]); + } + current.splice(next.length); + } + } + function TypedArray(root, path, current, next) { + if (is_1.Is.TypedArray(current) && current.length === next.length) { + for (let i = 0; i < current.length; i++) { + current[i] = next[i]; + } + } + else { + pointer_1.ValuePointer.Set(root, path, clone_1.ValueClone.Clone(next)); + } + } + function Value(root, path, current, next) { + if (current === next) + return; + pointer_1.ValuePointer.Set(root, path, next); + } + function Visit(root, path, current, next) { + if (is_1.Is.Array(next)) { + return Array(root, path, current, next); + } + else if (is_1.Is.TypedArray(next)) { + return TypedArray(root, path, current, next); + } + else if (is_1.Is.Object(next)) { + return Object(root, path, current, next); + } + else if (is_1.Is.Value(next)) { + return Value(root, path, current, next); + } + } + /** Performs a deep mutable value assignment while retaining internal references. */ + function Mutate(current, next) { + if (is_1.Is.TypedArray(current) || is_1.Is.Value(current) || is_1.Is.TypedArray(next) || is_1.Is.Value(next)) { + throw new ValueMutateInvalidRootMutationError(); + } + if ((is_1.Is.Object(current) && is_1.Is.Array(next)) || (is_1.Is.Array(current) && is_1.Is.Object(next))) { + throw new ValueMutateTypeMismatchError(); + } + Visit(current, '', current, next); + } + ValueMutate.Mutate = Mutate; +})(ValueMutate = exports.ValueMutate || (exports.ValueMutate = {})); diff --git a/web/node_modules/@sinclair/typebox/value/pointer.d.ts b/web/node_modules/@sinclair/typebox/value/pointer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..abae1e1c4097ab8b6bc5e35c3b9721418779a858 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/pointer.d.ts @@ -0,0 +1,24 @@ +export declare class ValuePointerRootSetError extends Error { + readonly value: unknown; + readonly path: string; + readonly update: unknown; + constructor(value: unknown, path: string, update: unknown); +} +export declare class ValuePointerRootDeleteError extends Error { + readonly value: unknown; + readonly path: string; + constructor(value: unknown, path: string); +} +/** Provides functionality to update values through RFC6901 string pointers */ +export declare namespace ValuePointer { + /** Formats the given pointer into navigable key components */ + function Format(pointer: string): IterableIterator; + /** Sets the value at the given pointer. If the value at the pointer does not exist it is created */ + function Set(value: any, pointer: string, update: unknown): void; + /** Deletes a value at the given pointer */ + function Delete(value: any, pointer: string): void; + /** Returns true if a value exists at the given pointer */ + function Has(value: any, pointer: string): boolean; + /** Gets the value at the given pointer */ + function Get(value: any, pointer: string): any; +} diff --git a/web/node_modules/@sinclair/typebox/value/pointer.js b/web/node_modules/@sinclair/typebox/value/pointer.js new file mode 100644 index 0000000000000000000000000000000000000000..981be6350dd18bcdf98d07e117adb29ca8833761 --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/pointer.js @@ -0,0 +1,142 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0; +class ValuePointerRootSetError extends Error { + constructor(value, path, update) { + super('ValuePointer: Cannot set root value'); + this.value = value; + this.path = path; + this.update = update; + } +} +exports.ValuePointerRootSetError = ValuePointerRootSetError; +class ValuePointerRootDeleteError extends Error { + constructor(value, path) { + super('ValuePointer: Cannot delete root value'); + this.value = value; + this.path = path; + } +} +exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError; +/** Provides functionality to update values through RFC6901 string pointers */ +var ValuePointer; +(function (ValuePointer) { + function Escape(component) { + return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~'); + } + /** Formats the given pointer into navigable key components */ + function* Format(pointer) { + if (pointer === '') + return; + let [start, end] = [0, 0]; + for (let i = 0; i < pointer.length; i++) { + const char = pointer.charAt(i); + if (char === '/') { + if (i === 0) { + start = i + 1; + } + else { + end = i; + yield Escape(pointer.slice(start, end)); + start = i + 1; + } + } + else { + end = i; + } + } + yield Escape(pointer.slice(start)); + } + ValuePointer.Format = Format; + /** Sets the value at the given pointer. If the value at the pointer does not exist it is created */ + function Set(value, pointer, update) { + if (pointer === '') + throw new ValuePointerRootSetError(value, pointer, update); + let [owner, next, key] = [null, value, '']; + for (const component of Format(pointer)) { + if (next[component] === undefined) + next[component] = {}; + owner = next; + next = next[component]; + key = component; + } + owner[key] = update; + } + ValuePointer.Set = Set; + /** Deletes a value at the given pointer */ + function Delete(value, pointer) { + if (pointer === '') + throw new ValuePointerRootDeleteError(value, pointer); + let [owner, next, key] = [null, value, '']; + for (const component of Format(pointer)) { + if (next[component] === undefined || next[component] === null) + return; + owner = next; + next = next[component]; + key = component; + } + if (globalThis.Array.isArray(owner)) { + const index = parseInt(key); + owner.splice(index, 1); + } + else { + delete owner[key]; + } + } + ValuePointer.Delete = Delete; + /** Returns true if a value exists at the given pointer */ + function Has(value, pointer) { + if (pointer === '') + return true; + let [owner, next, key] = [null, value, '']; + for (const component of Format(pointer)) { + if (next[component] === undefined) + return false; + owner = next; + next = next[component]; + key = component; + } + return globalThis.Object.getOwnPropertyNames(owner).includes(key); + } + ValuePointer.Has = Has; + /** Gets the value at the given pointer */ + function Get(value, pointer) { + if (pointer === '') + return value; + let current = value; + for (const component of Format(pointer)) { + if (current[component] === undefined) + return undefined; + current = current[component]; + } + return current; + } + ValuePointer.Get = Get; +})(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {})); diff --git a/web/node_modules/@sinclair/typebox/value/value.d.ts b/web/node_modules/@sinclair/typebox/value/value.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf8d32f5e6f7d3fe336c19b13fa5f7cb1d69329f --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/value.d.ts @@ -0,0 +1,39 @@ +import * as Types from '../typebox'; +import { ValueErrorIterator } from '../errors/index'; +import { Mutable } from './mutate'; +import { Edit } from './delta'; +/** Provides functions to perform structural updates to JavaScript values */ +export declare namespace Value { + /** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number, boolean and date values if a reasonable conversion is possible. */ + function Cast(schema: T, references: [...R], value: unknown): Types.Static; + /** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number, boolean and date values if a reasonable conversion is possible. */ + function Cast(schema: T, value: unknown): Types.Static; + /** Creates a value from the given type */ + function Create(schema: T, references: [...R]): Types.Static; + /** Creates a value from the given type */ + function Create(schema: T): Types.Static; + /** Returns true if the value matches the given type. */ + function Check(schema: T, references: [...R], value: unknown): value is Types.Static; + /** Returns true if the value matches the given type. */ + function Check(schema: T, value: unknown): value is Types.Static; + /** Converts any type mismatched values to their target type if a conversion is possible. */ + function Convert(schema: T, references: [...R], value: unknown): unknown; + /** Converts any type mismatched values to their target type if a conversion is possible. */ + function Convert(schema: T, value: unknown): unknown; + /** Returns a structural clone of the given value */ + function Clone(value: T): T; + /** Returns an iterator for each error in this value. */ + function Errors(schema: T, references: [...R], value: unknown): ValueErrorIterator; + /** Returns an iterator for each error in this value. */ + function Errors(schema: T, value: unknown): ValueErrorIterator; + /** Returns true if left and right values are structurally equal */ + function Equal(left: T, right: unknown): right is T; + /** Returns edits to transform the current value into the next value */ + function Diff(current: unknown, next: unknown): Edit[]; + /** Returns a FNV1A-64 non cryptographic hash of the given value */ + function Hash(value: unknown): bigint; + /** Returns a new value with edits applied to the given value */ + function Patch(current: unknown, edits: Edit[]): T; + /** Performs a deep mutable value assignment while retaining internal references. */ + function Mutate(current: Mutable, next: Mutable): void; +} diff --git a/web/node_modules/@sinclair/typebox/value/value.js b/web/node_modules/@sinclair/typebox/value/value.js new file mode 100644 index 0000000000000000000000000000000000000000..e1ab919f2565708720730063c98fb7ee5d47475d --- /dev/null +++ b/web/node_modules/@sinclair/typebox/value/value.js @@ -0,0 +1,99 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2017-2023 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +---------------------------------------------------------------------------*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Value = void 0; +const index_1 = require("../errors/index"); +const mutate_1 = require("./mutate"); +const hash_1 = require("./hash"); +const equal_1 = require("./equal"); +const cast_1 = require("./cast"); +const clone_1 = require("./clone"); +const convert_1 = require("./convert"); +const create_1 = require("./create"); +const check_1 = require("./check"); +const delta_1 = require("./delta"); +/** Provides functions to perform structural updates to JavaScript values */ +var Value; +(function (Value) { + function Cast(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + return cast_1.ValueCast.Cast(schema, references, value); + } + Value.Cast = Cast; + function Create(...args) { + const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []]; + return create_1.ValueCreate.Create(schema, references); + } + Value.Create = Create; + function Check(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + return check_1.ValueCheck.Check(schema, references, value); + } + Value.Check = Check; + function Convert(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + return convert_1.ValueConvert.Convert(schema, references, value); + } + Value.Convert = Convert; + /** Returns a structural clone of the given value */ + function Clone(value) { + return clone_1.ValueClone.Clone(value); + } + Value.Clone = Clone; + function Errors(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + return index_1.ValueErrors.Errors(schema, references, value); + } + Value.Errors = Errors; + /** Returns true if left and right values are structurally equal */ + function Equal(left, right) { + return equal_1.ValueEqual.Equal(left, right); + } + Value.Equal = Equal; + /** Returns edits to transform the current value into the next value */ + function Diff(current, next) { + return delta_1.ValueDelta.Diff(current, next); + } + Value.Diff = Diff; + /** Returns a FNV1A-64 non cryptographic hash of the given value */ + function Hash(value) { + return hash_1.ValueHash.Create(value); + } + Value.Hash = Hash; + /** Returns a new value with edits applied to the given value */ + function Patch(current, edits) { + return delta_1.ValueDelta.Patch(current, edits); + } + Value.Patch = Patch; + /** Performs a deep mutable value assignment while retaining internal references. */ + function Mutate(current, next) { + mutate_1.ValueMutate.Mutate(current, next); + } + Value.Mutate = Mutate; +})(Value = exports.Value || (exports.Value = {})); diff --git a/web/node_modules/@types/estree/LICENSE b/web/node_modules/@types/estree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/web/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/web/node_modules/@types/estree/README.md b/web/node_modules/@types/estree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c9bc4d5f422105db08b64417e62c82ff756c31aa --- /dev/null +++ b/web/node_modules/@types/estree/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for estree (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/web/node_modules/@types/estree/flow.d.ts b/web/node_modules/@types/estree/flow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d001a92b55a9323e827ee90ef353df47f3c2fa0 --- /dev/null +++ b/web/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,167 @@ +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: InterfaceExtends[]; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: FunctionTypeParam[]; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Identifier[]; + } + + interface TypeParameterInstantiation extends Node { + params: FlowTypeAnnotation[]; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/web/node_modules/@types/estree/index.d.ts b/web/node_modules/@types/estree/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e933e20efd49752be2c92cc5553a7737e804754b --- /dev/null +++ b/web/node_modules/@types/estree/index.d.ts @@ -0,0 +1,683 @@ +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +export interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +export interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +export interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +export type Node = NodeMap[keyof NodeMap]; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +export interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +export interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +export interface BaseStatement extends BaseNode {} + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +export interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +export interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +export interface BaseDeclaration extends BaseStatement {} + +export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +export interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +export type Expression = ExpressionMap[keyof ExpressionMap]; + +export interface BaseExpression extends BaseNode {} + +export type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +export interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +export interface BasePattern extends BaseNode {} + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +export interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +export interface BaseModuleDeclaration extends BaseNode {} + +export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +export interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + source?: Literal | null | undefined; +} + +export interface ExportSpecifier extends BaseModuleSpecifier { + type: "ExportSpecifier"; + exported: Identifier; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | null; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/web/node_modules/@types/estree/package.json b/web/node_modules/@types/estree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2d5a998377ab744c5bfc89c41eedaeb1e12da11e --- /dev/null +++ b/web/node_modules/@types/estree/package.json @@ -0,0 +1,26 @@ +{ + "name": "@types/estree", + "version": "1.0.5", + "description": "TypeScript definitions for estree", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "githubUsername": "RReverser", + "url": "https://github.com/RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "6f0eeaffe488ce594e73f8df619c677d752a279b51edbc744e4aebb20db4b3a7", + "typeScriptVersion": "4.5", + "nonNpm": true +} \ No newline at end of file diff --git a/web/node_modules/@vitest/expect/LICENSE b/web/node_modules/@vitest/expect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ae481fdb8ea5d7ab1dac9e5138d77cd80fbfb8c --- /dev/null +++ b/web/node_modules/@vitest/expect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present Vitest Team + +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/web/node_modules/@vitest/expect/README.md b/web/node_modules/@vitest/expect/README.md new file mode 100644 index 0000000000000000000000000000000000000000..da5d16d8cd42070bae7dd097b441396e8a355c14 --- /dev/null +++ b/web/node_modules/@vitest/expect/README.md @@ -0,0 +1,17 @@ +# @vitest/expect + +Jest's expect matchers as a Chai plugin. + +## Usage + +```js +import * as chai from 'chai' +import { JestAsymmetricMatchers, JestChaiExpect, JestExtend } from '@vitest/expect' + +// allows using expect.extend instead of chai.use to extend plugins +chai.use(JestExtend) +// adds all jest matchers to expect +chai.use(JestChaiExpect) +// adds asymmetric matchers like stringContaining, objectContaining +chai.use(JestAsymmetricMatchers) +``` diff --git a/web/node_modules/@vitest/expect/dist/chai.d.cts b/web/node_modules/@vitest/expect/dist/chai.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..7e231313ed85b703d70ec44778a96e7f3ff4f98e --- /dev/null +++ b/web/node_modules/@vitest/expect/dist/chai.d.cts @@ -0,0 +1,1968 @@ +// Type definitions for chai 4.3 +// Project: http://chaijs.com/ +// Definitions by: Bart van der Schoor +// Andrew Brown +// Olivier Chevet +// Matt Wistrand +// Shaun Luttin +// Satana Charuwichitratana +// Erik Schierboom +// Bogdan Paranytsia +// CXuesong +// Joey Kilpatrick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare namespace Chai { + type Message = string | (() => string); + type ObjectProperty = string | symbol | number; + + interface PathInfo { + parent: object; + name: string; + value?: any; + exists: boolean; + } + + interface ErrorConstructor { + new(...args: any[]): Error; + } + + interface ChaiUtils { + addChainableMethod( + // object to define the method on, e.g. chai.Assertion.prototype + ctx: object, + // method name + name: string, + // method itself; any arguments + method: (...args: any[]) => void, + // called when property is accessed + chainingBehavior?: () => void, + ): void; + overwriteChainableMethod( + ctx: object, + name: string, + method: (...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + addLengthGuard( + fn: Function, + assertionName: string, + isChainable: boolean, + ): void; + addMethod(ctx: object, name: string, method: Function): void; + addProperty(ctx: object, name: string, getter: () => any): void; + overwriteMethod(ctx: object, name: string, method: Function): void; + overwriteProperty(ctx: object, name: string, getter: () => any): void; + compareByInspect(a: object, b: object): -1 | 1; + expectTypes(obj: object, types: string[]): void; + flag(obj: object, key: string, value?: any): any; + getActual(obj: object, args: AssertionArgs): any; + getProperties(obj: object): string[]; + getEnumerableProperties(obj: object): string[]; + getOwnEnumerablePropertySymbols(obj: object): symbol[]; + getOwnEnumerableProperties(obj: object): Array; + getMessage(errorLike: Error | string): string; + getMessage(obj: any, args: AssertionArgs): string; + inspect(obj: any, showHidden?: boolean, depth?: number, colors?: boolean): string; + isProxyEnabled(): boolean; + objDisplay(obj: object): void; + proxify(obj: object, nonChainableMethodName: string): object; + test(obj: object, args: AssertionArgs): boolean; + transferFlags(assertion: Assertion, obj: object, includeAll?: boolean): void; + compatibleInstance(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleConstructor(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleMessage(thrown: Error, errMatcher: string | RegExp): boolean; + getConstructorName(constructorFn: Function): string; + getFuncName(constructorFn: Function): string | null; + + // Reexports from pathval: + hasProperty(obj: object | undefined | null, name: ObjectProperty): boolean; + getPathInfo(obj: object, path: string): PathInfo; + getPathValue(obj: object, path: string): object | undefined; + } + + type ChaiPlugin = (chai: ChaiStatic, utils: ChaiUtils) => void; + + interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: ChaiPlugin): ChaiStatic; + util: ChaiUtils; + assert: AssertStatic; + config: Config; + Assertion: AssertionStatic; + AssertionError: typeof AssertionError; + version: string; + } + + export interface ExpectStatic { + (val: any, message?: string): Assertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface AssertStatic extends Assert { + } + + // chai.Assertion.prototype.assert arguments + type AssertionArgs = [ + // 'expression to be tested' + // This parameter is unused and the docs list its type as + // 'Philosophical', which is mentioned nowhere else in the source. Do + // with that what you will! + any, + Message, // message if value fails + Message, // message if negated value fails + any, // expected value + any?, // actual value + boolean?, // showDiff + ]; + + export interface AssertionPrototype { + assert(...args: AssertionArgs): void; + _obj: any; + } + + export interface AssertionStatic extends AssertionPrototype { + prototype: AssertionPrototype; + + new(target: any, message?: string, ssfi?: Function, lockSsfi?: boolean): Assertion; + + // Deprecated properties: + includeStack: boolean; + showDiff: boolean; + + // Partials of functions on ChaiUtils: + addProperty(name: string, getter: (this: AssertionStatic) => any): void; + addMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + addChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + overwriteProperty(name: string, getter: (this: AssertionStatic) => any): void; + overwriteMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + overwriteChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + } + + export type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; + + export type OperatorComparable = boolean | null | number | string | undefined | Date; + + interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + interface ShouldThrow { + (actual: Function, expected?: string | RegExp, message?: string): void; + (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + ordered: Ordered; + nested: Nested; + own: Own; + any: KeyFilter; + all: KeyFilter; + a: Assertion; + an: Assertion; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + finite: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + property: Property; + ownProperty: Property; + haveOwnProperty: Property; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo: CloseTo; + approximately: CloseTo; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + oneOf: OneOf; + } + + interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + but: Assertion; + does: Assertion; + } + + interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + greaterThanOrEqual: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + lessThanOrEqual: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + within(start: Date, finish: Date, message?: string): Assertion; + } + + interface NumberComparer { + (value: number | Date, message?: string): Assertion; + } + + interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + interface InstanceOf { + (constructor: any, message?: string): Assertion; + } + + interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + + interface Nested { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + members: Members; + } + + interface Own { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + } + + interface Deep extends KeyFilter { + be: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + ordered: Ordered; + nested: Nested; + oneOf: OneOf; + own: Own; + } + + interface Ordered { + members: Members; + } + + interface KeyFilter { + keys: Keys; + members: Members; + } + + interface Equal { + (value: any, message?: string): Assertion; + } + + interface Property { + (name: string | symbol, value: any, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + interface OwnPropertyDescriptor { + (name: string | symbol, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + interface Include { + (value: any, message?: string): Assertion; + keys: Keys; + deep: Deep; + ordered: Ordered; + members: Members; + any: KeyFilter; + all: KeyFilter; + oneOf: OneOf; + } + + interface OneOf { + (list: ReadonlyArray, message?: string): Assertion; + } + + interface Match { + (regexp: RegExp, message?: string): Assertion; + } + + interface Keys { + (...keys: string[]): Assertion; + (keys: ReadonlyArray | Object): Assertion; + } + + interface Throw { + (expected?: string | RegExp, message?: string): Assertion; + (constructor: Error | Function, expected?: string | RegExp, message?: string): Assertion; + } + + interface RespondTo { + (method: string, message?: string): Assertion; + } + + interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + interface Members { + (set: ReadonlyArray, message?: string): Assertion; + } + + interface PropertyChange { + (object: Object, property?: string, message?: string): DeltaAssertion; + } + + interface DeltaAssertion extends Assertion { + by(delta: number, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): asserts expression; + + /** + * Throws a failure. + * + * @param message Message to display on error. + * @remarks Node.js assert module-compatible. + */ + fail(message?: string): never; + + /** + * Throws a failure. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + * @param operator Comparison operator, if not strict equality. + * @remarks Node.js assert module-compatible. + */ + fail(actual: T, expected: T, message?: string, operator?: Operator): never; + + /** + * Asserts that object is truthy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isOk(value: T, message?: string): void; + + /** + * Asserts that object is truthy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + ok(value: T, message?: string): void; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotOk(value: T, message?: string): void; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + notOk(value: T, message?: string): void; + + /** + * Asserts non-strict equality (==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + equal(actual: T, expected: T, message?: string): void; + + /** + * Asserts non-strict inequality (!=) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict equality (===) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + strictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict inequality (!==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is not deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notDeepEqual(actual: T, expected: T, message?: string): void; + + /** + * Alias to deepEqual + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. + * + * @param valueToCheck Actual value. + * @param valueToBeAbove Minimum Potential expected value. + * @param message Message to display on error. + */ + isAbove(valueToCheck: number, valueToBeAbove: number, message?: string): void; + + /** + * Asserts valueToCheck is greater than or equal to (>=) valueToBeAtLeast. + * + * @param valueToCheck Actual value. + * @param valueToBeAtLeast Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtLeast(valueToCheck: number, valueToBeAtLeast: number, message?: string): void; + + /** + * Asserts valueToCheck is strictly less than (<) valueToBeBelow. + * + * @param valueToCheck Actual value. + * @param valueToBeBelow Minimum Potential expected value. + * @param message Message to display on error. + */ + isBelow(valueToCheck: number, valueToBeBelow: number, message?: string): void; + + /** + * Asserts valueToCheck is less than or equal to (<=) valueToBeAtMost. + * + * @param valueToCheck Actual value. + * @param valueToBeAtMost Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtMost(valueToCheck: number, valueToBeAtMost: number, message?: string): void; + + /** + * Asserts that value is true. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isTrue(value: T, message?: string): void; + + /** + * Asserts that value is false. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isFalse(value: T, message?: string): void; + + /** + * Asserts that value is not true. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotTrue(value: T, message?: string): void; + + /** + * Asserts that value is not false. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFalse(value: T, message?: string): void; + + /** + * Asserts that value is null. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNull(value: T, message?: string): void; + + /** + * Asserts that value is not null. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNull(value: T, message?: string): void; + + /** + * Asserts that value is NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNaN(value: T, message?: string): void; + + /** + * Asserts that value is not NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNaN(value: T, message?: string): void; + + /** + * Asserts that the target is neither null nor undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + exists(value: T, message?: string): void; + + /** + * Asserts that the target is either null or undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + notExists(value: T, message?: string): void; + + /** + * Asserts that value is undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isUndefined(value: T, message?: string): void; + + /** + * Asserts that value is not undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isDefined(value: T, message?: string): void; + + /** + * Asserts that value is a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isFunction(value: T, message?: string): void; + + /** + * Asserts that value is not a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFunction(value: T, message?: string): void; + + /** + * Asserts that value is an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + * @remarks The assertion does not match subclassed objects. + */ + isObject(value: T, message?: string): void; + + /** + * Asserts that value is not an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotObject(value: T, message?: string): void; + + /** + * Asserts that value is an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isArray(value: T, message?: string): void; + + /** + * Asserts that value is not an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotArray(value: T, message?: string): void; + + /** + * Asserts that value is a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isString(value: T, message?: string): void; + + /** + * Asserts that value is not a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotString(value: T, message?: string): void; + + /** + * Asserts that value is a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNumber(value: T, message?: string): void; + + /** + * Asserts that value is not a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNumber(value: T, message?: string): void; + + /** + * Asserts that value is a finite number. + * Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * T Type of value + * @param value Actual value + * @param message Message to display on error. + */ + isFinite(value: T, message?: string): void; + + /** + * Asserts that value is a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isBoolean(value: T, message?: string): void; + + /** + * Asserts that value is not a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotBoolean(value: T, message?: string): void; + + /** + * Asserts that value's type is name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + typeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value's type is not name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + notTypeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value is an instance of constructor. + * + * T Type of value. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + instanceOf(value: T, constructor: Function, message?: string): void; + + /** + * Asserts that value is not an instance of constructor. + * + * T Type of value. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + notInstanceOf(value: T, type: Function, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + include(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include( + haystack: ReadonlyArray | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + include(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack does not includes needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + notInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not includes needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude( + haystack: ReadonlyArray | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not includes needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack does not includes needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notInclude(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#include} instead. + */ + deepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + deepInclude( + haystack: ReadonlyArray | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not includes needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + deepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that haystack does not includes needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#notInclude} instead. + */ + notDeepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not includes needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notDeepInclude( + haystack: ReadonlyArray | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not includes needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notDeepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that value matches the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + match(value: string, regexp: RegExp, message?: string): void; + + /** + * Asserts that value does not match the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + notMatch(expected: any, regexp: RegExp, message?: string): void; + + /** + * Asserts that object has a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + property(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object has a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notProperty(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + deepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notDeepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + propertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notPropertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + deepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notDeepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object has a length property with the expected value. + * + * T Type of object. + * @param object Container object. + * @param length Potential expected length of object. + * @param message Message to display on error. + */ + lengthOf(object: T, length: number, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throws(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throws( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + Throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + Throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + doesNotThrow(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + doesNotThrow( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Compares two values using operator. + * + * @param val1 Left value during comparison. + * @param operator Comparison operator. + * @param val2 Right value during comparison. + * @param message Message to display on error. + */ + operator(val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + closeTo(actual: number, expected: number, delta: number, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + approximately(act: number, exp: number, delta: number, message?: string): void; + + /** + * Asserts that set1 and set2 have the same members. Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset. Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in any order. + * Uses a strict equality check (===). Duplicates are ignored. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential not contained set of values. + * @param message Message to display on error. + */ + notIncludeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that non-object, non-array value inList appears in the flat array list. + * + * T Type of list values. + * @param inList Value expected to be in the list. + * @param list List of values. + * @param message Message to display on error. + */ + oneOf(inList: T, list: T[], message?: string): void; + + /** + * Asserts that a function changes the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be modified. + * @param message Message to display on error. + */ + changes(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not change the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be modified. + * @param message Message to display on error. + */ + doesNotChange(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be increased. + * @param message Message to display on error. + */ + increases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not increase an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be increased. + * @param message Message to display on error. + */ + doesNotIncrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function decreases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be decreased. + * @param message Message to display on error. + */ + decreases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not decrease an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be decreased. + * @param message Message to display on error. + */ + doesNotDecrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts if value is not a false value, and throws if it is a true value. + * + * T Type of object. + * @param object Actual value. + * @param message Message to display on error. + * @remarks This is added to allow for chai to be a drop-in replacement for + * Node’s assert class. + */ + ifError(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isExtensible(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + extensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotExtensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notExtensible(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isSealed(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + sealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotSealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notSealed(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isFrozen(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + frozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotFrozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notFrozen(object: T, message?: string): void; + + /** + * Asserts that the target does not contain any values. For arrays and + * strings, it checks the length property. For Map and Set instances, it + * checks the size property. For non-function objects, it gets the count + * of own enumerable string keys. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isEmpty(object: T, message?: string): void; + + /** + * Asserts that the target contains values. For arrays and strings, it checks + * the length property. For Map and Set instances, it checks the size property. + * For non-function objects, it gets the count of own enumerable string keys. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotEmpty(object: T, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that object has a direct or inherited property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + nestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * The property cannot exist on the object nor anywhere in its prototype chain. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + notNestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + nestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object has a property named by property with a value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + deepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notDeepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + } + + export interface Config { + /** + * Default: false + */ + includeStack: boolean; + + /** + * Default: true + */ + showDiff: boolean; + + /** + * Default: 40 + */ + truncateThreshold: number; + + /** + * Default: true + */ + useProxy: boolean; + + /** + * Default: ['then', 'catch', 'inspect', 'toJSON'] + */ + proxyExcludedKeys: string[]; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } +} + +declare const chai: Chai.ChaiStatic; + +declare module "chai" { + export = chai; +} + +// interface Object { +// should: Chai.Assertion; +// } diff --git a/web/node_modules/@vitest/expect/dist/index.d.ts b/web/node_modules/@vitest/expect/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d18b61c4d5308e49cd3a302bc2cedef62b4c73e6 --- /dev/null +++ b/web/node_modules/@vitest/expect/dist/index.d.ts @@ -0,0 +1,253 @@ +import * as _vitest_utils from '@vitest/utils'; +import { stringify, Constructable } from '@vitest/utils'; +export { setupColors } from '@vitest/utils'; +import { diff } from '@vitest/utils/diff'; +export { DiffOptions } from '@vitest/utils/diff'; + +type Formatter = (input: string | number | null | undefined) => string; + +declare function getMatcherUtils(): { + EXPECTED_COLOR: _vitest_utils.ColorMethod; + RECEIVED_COLOR: _vitest_utils.ColorMethod; + INVERTED_COLOR: _vitest_utils.ColorMethod; + BOLD_WEIGHT: _vitest_utils.ColorMethod; + DIM_COLOR: _vitest_utils.ColorMethod; + matcherHint: (matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions) => string; + printReceived: (object: unknown) => string; + printExpected: (value: unknown) => string; +}; +declare function addCustomEqualityTesters(newTesters: Array): void; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +type ChaiPlugin = Chai.ChaiPlugin; +type Tester = (this: TesterContext, a: any, b: any, customTesters: Array) => boolean | undefined; +interface TesterContext { + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; +} + +interface MatcherHintOptions { + comment?: string; + expectedColor?: Formatter; + isDirectExpectCall?: boolean; + isNot?: boolean; + promise?: string; + receivedColor?: Formatter; + secondArgument?: string; + secondArgumentColor?: Formatter; +} +interface MatcherState { + customTesters: Array; + assertionCalls: number; + currentTestName?: string; + dontThrow?: () => void; + error?: Error; + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; + expand?: boolean; + expectedAssertionsNumber?: number | null; + expectedAssertionsNumberErrorGen?: (() => Error) | null; + isExpectingAssertions?: boolean; + isExpectingAssertionsError?: Error | null; + isNot: boolean; + promise: string; + suppressedErrors: Array; + testPath?: string; + utils: ReturnType & { + diff: typeof diff; + stringify: typeof stringify; + iterableEquality: Tester; + subsetEquality: Tester; + }; + soft?: boolean; +} +interface SyncExpectationResult { + pass: boolean; + message: () => string; + actual?: any; + expected?: any; +} +type AsyncExpectationResult = Promise; +type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; +interface RawMatcherFn { + (this: T, received: any, expected: any, options?: any): ExpectationResult; +} +type MatchersObject = Record>; +interface ExpectStatic extends Chai.ExpectStatic, AsymmetricMatchersContaining { + (actual: T, message?: string): Assertion; + unreachable: (message?: string) => never; + soft: (actual: T, message?: string) => Assertion; + extend: (expects: MatchersObject) => void; + addEqualityTesters: (testers: Array) => void; + assertions: (expected: number) => void; + hasAssertions: () => void; + anything: () => any; + any: (constructor: unknown) => any; + getState: () => MatcherState; + setState: (state: Partial) => void; + not: AsymmetricMatchersContaining; +} +interface AsymmetricMatchersContaining { + stringContaining: (expected: string) => any; + objectContaining: (expected: T) => any; + arrayContaining: (expected: Array) => any; + stringMatching: (expected: string | RegExp) => any; + closeTo: (expected: number, precision?: number) => any; +} +interface JestAssertion extends jest.Matchers { + toEqual: (expected: E) => void; + toStrictEqual: (expected: E) => void; + toBe: (expected: E) => void; + toMatch: (expected: string | RegExp) => void; + toMatchObject: (expected: E) => void; + toContain: (item: E) => void; + toContainEqual: (item: E) => void; + toBeTruthy: () => void; + toBeFalsy: () => void; + toBeGreaterThan: (num: number | bigint) => void; + toBeGreaterThanOrEqual: (num: number | bigint) => void; + toBeLessThan: (num: number | bigint) => void; + toBeLessThanOrEqual: (num: number | bigint) => void; + toBeNaN: () => void; + toBeUndefined: () => void; + toBeNull: () => void; + toBeDefined: () => void; + toBeInstanceOf: (expected: E) => void; + toBeCalledTimes: (times: number) => void; + toHaveLength: (length: number) => void; + toHaveProperty: (property: string | (string | number)[], value?: E) => void; + toBeCloseTo: (number: number, numDigits?: number) => void; + toHaveBeenCalledTimes: (times: number) => void; + toHaveBeenCalled: () => void; + toBeCalled: () => void; + toHaveBeenCalledWith: (...args: E) => void; + toBeCalledWith: (...args: E) => void; + toHaveBeenNthCalledWith: (n: number, ...args: E) => void; + nthCalledWith: (nthCall: number, ...args: E) => void; + toHaveBeenLastCalledWith: (...args: E) => void; + lastCalledWith: (...args: E) => void; + toThrow: (expected?: string | Constructable | RegExp | Error) => void; + toThrowError: (expected?: string | Constructable | RegExp | Error) => void; + toReturn: () => void; + toHaveReturned: () => void; + toReturnTimes: (times: number) => void; + toHaveReturnedTimes: (times: number) => void; + toReturnWith: (value: E) => void; + toHaveReturnedWith: (value: E) => void; + toHaveLastReturnedWith: (value: E) => void; + lastReturnedWith: (value: E) => void; + toHaveNthReturnedWith: (nthCall: number, value: E) => void; + nthReturnedWith: (nthCall: number, value: E) => void; +} +type VitestAssertion = { + [K in keyof A]: A[K] extends Chai.Assertion ? Assertion : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion; +} & ((type: string, message?: string) => Assertion); +type Promisify = { + [K in keyof O]: O[K] extends (...args: infer A) => infer R ? O extends R ? Promisify : (...args: A) => Promise : O[K]; +}; +interface Assertion extends VitestAssertion, JestAssertion { + toBeTypeOf: (expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => void; + toHaveBeenCalledOnce: () => void; + toSatisfy: (matcher: (value: E) => boolean, message?: string) => void; + resolves: Promisify>; + rejects: Promisify>; +} +declare global { + namespace jest { + interface Matchers { + } + } +} + +interface AsymmetricMatcherInterface { + asymmetricMatch: (other: unknown) => boolean; + toString: () => string; + getExpectedType?: () => string; + toAsymmetricMatcher?: () => string; +} +declare abstract class AsymmetricMatcher implements AsymmetricMatcherInterface { + protected sample: T; + protected inverse: boolean; + $$typeof: symbol; + constructor(sample: T, inverse?: boolean); + protected getMatcherContext(expect?: Chai.ExpectStatic): State; + abstract asymmetricMatch(other: unknown): boolean; + abstract toString(): string; + getExpectedType?(): string; + toAsymmetricMatcher?(): string; +} +declare class StringContaining extends AsymmetricMatcher { + constructor(sample: string, inverse?: boolean); + asymmetricMatch(other: string): boolean; + toString(): string; + getExpectedType(): string; +} +declare class Anything extends AsymmetricMatcher { + asymmetricMatch(other: unknown): boolean; + toString(): string; + toAsymmetricMatcher(): string; +} +declare class ObjectContaining extends AsymmetricMatcher> { + constructor(sample: Record, inverse?: boolean); + getPrototype(obj: object): any; + hasProperty(obj: object | null, property: string): boolean; + asymmetricMatch(other: any): boolean; + toString(): string; + getExpectedType(): string; +} +declare class ArrayContaining extends AsymmetricMatcher> { + constructor(sample: Array, inverse?: boolean); + asymmetricMatch(other: Array): boolean; + toString(): string; + getExpectedType(): string; +} +declare class Any extends AsymmetricMatcher { + constructor(sample: unknown); + fnNameFor(func: Function): string; + asymmetricMatch(other: unknown): boolean; + toString(): string; + getExpectedType(): string; + toAsymmetricMatcher(): string; +} +declare class StringMatching extends AsymmetricMatcher { + constructor(sample: string | RegExp, inverse?: boolean); + asymmetricMatch(other: string): boolean; + toString(): string; + getExpectedType(): string; +} +declare const JestAsymmetricMatchers: ChaiPlugin; + +declare function equals(a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean): boolean; +declare function isAsymmetric(obj: any): boolean; +declare function hasAsymmetric(obj: any, seen?: Set): boolean; +declare function isA(typeName: string, value: unknown): boolean; +declare function fnNameFor(func: Function): string; +declare function hasProperty(obj: object | null, property: string): boolean; +declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean; +declare function isImmutableUnorderedSet(maybeSet: any): boolean; +declare function iterableEquality(a: any, b: any, customTesters?: Array, aStack?: Array, bStack?: Array): boolean | undefined; +declare function subsetEquality(object: unknown, subset: unknown, customTesters?: Array): boolean | undefined; +declare function typeEquality(a: any, b: any): boolean | undefined; +declare function arrayBufferEquality(a: unknown, b: unknown): boolean | undefined; +declare function sparseArrayEquality(a: unknown, b: unknown, customTesters?: Array): boolean | undefined; +declare function generateToBeMessage(deepEqualityName: string, expected?: string, actual?: string): string; +declare function pluralize(word: string, count: number): string; + +declare const MATCHERS_OBJECT: unique symbol; +declare const JEST_MATCHERS_OBJECT: unique symbol; +declare const GLOBAL_EXPECT: unique symbol; +declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol; + +declare function getState(expect: ExpectStatic): State; +declare function setState(state: Partial, expect: ExpectStatic): void; + +declare const JestChaiExpect: ChaiPlugin; + +declare const JestExtend: ChaiPlugin; + +export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, type Assertion, AsymmetricMatcher, type AsymmetricMatcherInterface, type AsymmetricMatchersContaining, type AsyncExpectationResult, type ChaiPlugin, type ExpectStatic, type ExpectationResult, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, type JestAssertion, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, type MatcherHintOptions, type MatcherState, type MatchersObject, ObjectContaining, type RawMatcherFn, StringContaining, StringMatching, type SyncExpectationResult, type Tester, type TesterContext, addCustomEqualityTesters, arrayBufferEquality, equals, fnNameFor, generateToBeMessage, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality }; diff --git a/web/node_modules/@vitest/expect/dist/index.js b/web/node_modules/@vitest/expect/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..640839e4b9fef0f25d08d055d4350845a8a29791 --- /dev/null +++ b/web/node_modules/@vitest/expect/dist/index.js @@ -0,0 +1,1554 @@ +import { getType, getColors, stringify, isObject, assertTypes } from '@vitest/utils'; +export { setupColors } from '@vitest/utils'; +import { diff } from '@vitest/utils/diff'; +import { isMockFunction } from '@vitest/spy'; +import { processError } from '@vitest/utils/error'; +import { util } from 'chai'; + +const MATCHERS_OBJECT = Symbol.for("matchers-object"); +const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object"); +const GLOBAL_EXPECT = Symbol.for("expect-global"); +const ASYMMETRIC_MATCHERS_OBJECT = Symbol.for("asymmetric-matchers-object"); + +if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) { + const globalState = /* @__PURE__ */ new WeakMap(); + const matchers = /* @__PURE__ */ Object.create(null); + const customEqualityTesters = []; + const assymetricMatchers = /* @__PURE__ */ Object.create(null); + Object.defineProperty(globalThis, MATCHERS_OBJECT, { + get: () => globalState + }); + Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, { + configurable: true, + get: () => ({ + state: globalState.get(globalThis[GLOBAL_EXPECT]), + matchers, + customEqualityTesters + }) + }); + Object.defineProperty(globalThis, ASYMMETRIC_MATCHERS_OBJECT, { + get: () => assymetricMatchers + }); +} +function getState(expect) { + return globalThis[MATCHERS_OBJECT].get(expect); +} +function setState(state, expect) { + const map = globalThis[MATCHERS_OBJECT]; + const current = map.get(expect) || {}; + Object.assign(current, state); + map.set(expect, current); +} + +function getMatcherUtils() { + const c = () => getColors(); + const EXPECTED_COLOR = c().green; + const RECEIVED_COLOR = c().red; + const INVERTED_COLOR = c().inverse; + const BOLD_WEIGHT = c().bold; + const DIM_COLOR = c().dim; + function matcherHint(matcherName, received = "received", expected = "expected", options = {}) { + const { + comment = "", + isDirectExpectCall = false, + // seems redundant with received === '' + isNot = false, + promise = "", + secondArgument = "", + expectedColor = EXPECTED_COLOR, + receivedColor = RECEIVED_COLOR, + secondArgumentColor = EXPECTED_COLOR + } = options; + let hint = ""; + let dimString = "expect"; + if (!isDirectExpectCall && received !== "") { + hint += DIM_COLOR(`${dimString}(`) + receivedColor(received); + dimString = ")"; + } + if (promise !== "") { + hint += DIM_COLOR(`${dimString}.`) + promise; + dimString = ""; + } + if (isNot) { + hint += `${DIM_COLOR(`${dimString}.`)}not`; + dimString = ""; + } + if (matcherName.includes(".")) { + dimString += matcherName; + } else { + hint += DIM_COLOR(`${dimString}.`) + matcherName; + dimString = ""; + } + if (expected === "") { + dimString += "()"; + } else { + hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected); + if (secondArgument) + hint += DIM_COLOR(", ") + secondArgumentColor(secondArgument); + dimString = ")"; + } + if (comment !== "") + dimString += ` // ${comment}`; + if (dimString !== "") + hint += DIM_COLOR(dimString); + return hint; + } + const SPACE_SYMBOL = "\xB7"; + const replaceTrailingSpaces = (text) => text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); + const printReceived = (object) => RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); + const printExpected = (value) => EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); + return { + EXPECTED_COLOR, + RECEIVED_COLOR, + INVERTED_COLOR, + BOLD_WEIGHT, + DIM_COLOR, + matcherHint, + printReceived, + printExpected + }; +} +function addCustomEqualityTesters(newTesters) { + if (!Array.isArray(newTesters)) { + throw new TypeError( + `expect.customEqualityTesters: Must be set to an array of Testers. Was given "${getType( + newTesters + )}"` + ); + } + globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters.push( + ...newTesters + ); +} +function getCustomEqualityTesters() { + return globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters; +} + +function equals(a, b, customTesters, strictCheck) { + customTesters = customTesters || []; + return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey); +} +const functionToString = Function.prototype.toString; +function isAsymmetric(obj) { + return !!obj && typeof obj === "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch); +} +function hasAsymmetric(obj, seen = /* @__PURE__ */ new Set()) { + if (seen.has(obj)) + return false; + seen.add(obj); + if (isAsymmetric(obj)) + return true; + if (Array.isArray(obj)) + return obj.some((i) => hasAsymmetric(i, seen)); + if (obj instanceof Set) + return Array.from(obj).some((i) => hasAsymmetric(i, seen)); + if (isObject(obj)) + return Object.values(obj).some((v) => hasAsymmetric(v, seen)); + return false; +} +function asymmetricMatch(a, b) { + const asymmetricA = isAsymmetric(a); + const asymmetricB = isAsymmetric(b); + if (asymmetricA && asymmetricB) + return void 0; + if (asymmetricA) + return a.asymmetricMatch(b); + if (asymmetricB) + return b.asymmetricMatch(a); +} +function eq(a, b, aStack, bStack, customTesters, hasKey2) { + let result = true; + const asymmetricResult = asymmetricMatch(a, b); + if (asymmetricResult !== void 0) + return asymmetricResult; + const testerContext = { equals }; + for (let i = 0; i < customTesters.length; i++) { + const customTesterResult = customTesters[i].call(testerContext, a, b, customTesters); + if (customTesterResult !== void 0) + return customTesterResult; + } + if (a instanceof Error && b instanceof Error) + return a.message === b.message; + if (typeof URL === "function" && a instanceof URL && b instanceof URL) + return a.href === b.href; + if (Object.is(a, b)) + return true; + if (a === null || b === null) + return a === b; + const className = Object.prototype.toString.call(a); + if (className !== Object.prototype.toString.call(b)) + return false; + switch (className) { + case "[object Boolean]": + case "[object String]": + case "[object Number]": + if (typeof a !== typeof b) { + return false; + } else if (typeof a !== "object" && typeof b !== "object") { + return Object.is(a, b); + } else { + return Object.is(a.valueOf(), b.valueOf()); + } + case "[object Date]": { + const numA = +a; + const numB = +b; + return numA === numB || Number.isNaN(numA) && Number.isNaN(numB); + } + case "[object RegExp]": + return a.source === b.source && a.flags === b.flags; + } + if (typeof a !== "object" || typeof b !== "object") + return false; + if (isDomNode(a) && isDomNode(b)) + return a.isEqualNode(b); + let length = aStack.length; + while (length--) { + if (aStack[length] === a) + return bStack[length] === b; + else if (bStack[length] === b) + return false; + } + aStack.push(a); + bStack.push(b); + if (className === "[object Array]" && a.length !== b.length) + return false; + const aKeys = keys(a, hasKey2); + let key; + let size = aKeys.length; + if (keys(b, hasKey2).length !== size) + return false; + while (size--) { + key = aKeys[size]; + result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2); + if (!result) + return false; + } + aStack.pop(); + bStack.pop(); + return result; +} +function keys(obj, hasKey2) { + const keys2 = []; + for (const key in obj) { + if (hasKey2(obj, key)) + keys2.push(key); + } + return keys2.concat( + Object.getOwnPropertySymbols(obj).filter( + (symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable + ) + ); +} +function hasDefinedKey(obj, key) { + return hasKey(obj, key) && obj[key] !== void 0; +} +function hasKey(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function isA(typeName, value) { + return Object.prototype.toString.apply(value) === `[object ${typeName}]`; +} +function isDomNode(obj) { + return obj !== null && typeof obj === "object" && "nodeType" in obj && typeof obj.nodeType === "number" && "nodeName" in obj && typeof obj.nodeName === "string" && "isEqualNode" in obj && typeof obj.isEqualNode === "function"; +} +function fnNameFor(func) { + if (func.name) + return func.name; + const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/); + return matches ? matches[1] : ""; +} +function getPrototype(obj) { + if (Object.getPrototypeOf) + return Object.getPrototypeOf(obj); + if (obj.constructor.prototype === obj) + return null; + return obj.constructor.prototype; +} +function hasProperty(obj, property) { + if (!obj) + return false; + if (Object.prototype.hasOwnProperty.call(obj, property)) + return true; + return hasProperty(getPrototype(obj), property); +} +const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; +const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; +const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; +function isImmutableUnorderedKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]); +} +function isImmutableUnorderedSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]); +} +const IteratorSymbol = Symbol.iterator; +function hasIterator(object) { + return !!(object != null && object[IteratorSymbol]); +} +function iterableEquality(a, b, customTesters = [], aStack = [], bStack = []) { + if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b)) + return void 0; + if (a.constructor !== b.constructor) + return false; + let length = aStack.length; + while (length--) { + if (aStack[length] === a) + return bStack[length] === b; + } + aStack.push(a); + bStack.push(b); + const filteredCustomTesters = [ + ...customTesters.filter((t) => t !== iterableEquality), + iterableEqualityWithStack + ]; + function iterableEqualityWithStack(a2, b2) { + return iterableEquality( + a2, + b2, + [...filteredCustomTesters], + [...aStack], + [...bStack] + ); + } + if (a.size !== void 0) { + if (a.size !== b.size) { + return false; + } else if (isA("Set", a) || isImmutableUnorderedSet(a)) { + let allFound = true; + for (const aValue of a) { + if (!b.has(aValue)) { + let has = false; + for (const bValue of b) { + const isEqual = equals(aValue, bValue, filteredCustomTesters); + if (isEqual === true) + has = true; + } + if (has === false) { + allFound = false; + break; + } + } + } + aStack.pop(); + bStack.pop(); + return allFound; + } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) { + let allFound = true; + for (const aEntry of a) { + if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), filteredCustomTesters)) { + let has = false; + for (const bEntry of b) { + const matchedKey = equals(aEntry[0], bEntry[0], filteredCustomTesters); + let matchedValue = false; + if (matchedKey === true) + matchedValue = equals(aEntry[1], bEntry[1], filteredCustomTesters); + if (matchedValue === true) + has = true; + } + if (has === false) { + allFound = false; + break; + } + } + } + aStack.pop(); + bStack.pop(); + return allFound; + } + } + const bIterator = b[IteratorSymbol](); + for (const aValue of a) { + const nextB = bIterator.next(); + if (nextB.done || !equals(aValue, nextB.value, filteredCustomTesters)) + return false; + } + if (!bIterator.next().done) + return false; + aStack.pop(); + bStack.pop(); + return true; +} +function hasPropertyInObject(object, key) { + const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype; + if (shouldTerminate) + return false; + return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key); +} +function isObjectWithKeys(a) { + return isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date); +} +function subsetEquality(object, subset, customTesters = []) { + const filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality); + const subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object2, subset2) => { + if (!isObjectWithKeys(subset2)) + return void 0; + return Object.keys(subset2).every((key) => { + if (isObjectWithKeys(subset2[key])) { + if (seenReferences.has(subset2[key])) + return equals(object2[key], subset2[key], filteredCustomTesters); + seenReferences.set(subset2[key], true); + } + const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [ + ...filteredCustomTesters, + subsetEqualityWithContext(seenReferences) + ]); + seenReferences.delete(subset2[key]); + return result; + }); + }; + return subsetEqualityWithContext()(object, subset); +} +function typeEquality(a, b) { + if (a == null || b == null || a.constructor === b.constructor) + return void 0; + return false; +} +function arrayBufferEquality(a, b) { + let dataViewA = a; + let dataViewB = b; + if (!(a instanceof DataView && b instanceof DataView)) { + if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) + return void 0; + try { + dataViewA = new DataView(a); + dataViewB = new DataView(b); + } catch { + return void 0; + } + } + if (dataViewA.byteLength !== dataViewB.byteLength) + return false; + for (let i = 0; i < dataViewA.byteLength; i++) { + if (dataViewA.getUint8(i) !== dataViewB.getUint8(i)) + return false; + } + return true; +} +function sparseArrayEquality(a, b, customTesters = []) { + if (!Array.isArray(a) || !Array.isArray(b)) + return void 0; + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const filteredCustomTesters = customTesters.filter((t) => t !== sparseArrayEquality); + return equals(a, b, filteredCustomTesters, true) && equals(aKeys, bKeys); +} +function generateToBeMessage(deepEqualityName, expected = "#{this}", actual = "#{exp}") { + const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`; + if (["toStrictEqual", "toEqual"].includes(deepEqualityName)) + return `${toBeMessage} + +If it should pass with deep equality, replace "toBe" with "${deepEqualityName}" + +Expected: ${expected} +Received: serializes to the same string +`; + return toBeMessage; +} +function pluralize(word, count) { + return `${count} ${word}${count === 1 ? "" : "s"}`; +} + +class AsymmetricMatcher { + constructor(sample, inverse = false) { + this.sample = sample; + this.inverse = inverse; + } + // should have "jest" to be compatible with its ecosystem + $$typeof = Symbol.for("jest.asymmetricMatcher"); + getMatcherContext(expect) { + return { + ...getState(expect || globalThis[GLOBAL_EXPECT]), + equals, + isNot: this.inverse, + customTesters: getCustomEqualityTesters(), + utils: { + ...getMatcherUtils(), + diff, + stringify, + iterableEquality, + subsetEquality + } + }; + } + // implement custom chai/loupe inspect for better AssertionError.message formatting + // https://github.com/chaijs/loupe/blob/9b8a6deabcd50adc056a64fb705896194710c5c6/src/index.ts#L29 + [Symbol.for("chai/inspect")](options) { + const result = stringify(this, options.depth, { min: true }); + if (result.length <= options.truncate) + return result; + return `${this.toString()}{\u2026}`; + } +} +class StringContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + if (!isA("String", sample)) + throw new Error("Expected is not a string"); + super(sample, inverse); + } + asymmetricMatch(other) { + const result = isA("String", other) && other.includes(this.sample); + return this.inverse ? !result : result; + } + toString() { + return `String${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "string"; + } +} +class Anything extends AsymmetricMatcher { + asymmetricMatch(other) { + return other != null; + } + toString() { + return "Anything"; + } + toAsymmetricMatcher() { + return "Anything"; + } +} +class ObjectContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + super(sample, inverse); + } + getPrototype(obj) { + if (Object.getPrototypeOf) + return Object.getPrototypeOf(obj); + if (obj.constructor.prototype === obj) + return null; + return obj.constructor.prototype; + } + hasProperty(obj, property) { + if (!obj) + return false; + if (Object.prototype.hasOwnProperty.call(obj, property)) + return true; + return this.hasProperty(this.getPrototype(obj), property); + } + asymmetricMatch(other) { + if (typeof this.sample !== "object") { + throw new TypeError( + `You must provide an object to ${this.toString()}, not '${typeof this.sample}'.` + ); + } + let result = true; + const matcherContext = this.getMatcherContext(); + for (const property in this.sample) { + if (!this.hasProperty(other, property) || !equals(this.sample[property], other[property], matcherContext.customTesters)) { + result = false; + break; + } + } + return this.inverse ? !result : result; + } + toString() { + return `Object${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "object"; + } +} +class ArrayContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + super(sample, inverse); + } + asymmetricMatch(other) { + if (!Array.isArray(this.sample)) { + throw new TypeError( + `You must provide an array to ${this.toString()}, not '${typeof this.sample}'.` + ); + } + const matcherContext = this.getMatcherContext(); + const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every( + (item) => other.some((another) => equals(item, another, matcherContext.customTesters)) + ); + return this.inverse ? !result : result; + } + toString() { + return `Array${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "array"; + } +} +class Any extends AsymmetricMatcher { + constructor(sample) { + if (typeof sample === "undefined") { + throw new TypeError( + "any() expects to be passed a constructor function. Please pass one or use anything() to match any object." + ); + } + super(sample); + } + fnNameFor(func) { + if (func.name) + return func.name; + const functionToString = Function.prototype.toString; + const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/); + return matches ? matches[1] : ""; + } + asymmetricMatch(other) { + if (this.sample === String) + return typeof other == "string" || other instanceof String; + if (this.sample === Number) + return typeof other == "number" || other instanceof Number; + if (this.sample === Function) + return typeof other == "function" || other instanceof Function; + if (this.sample === Boolean) + return typeof other == "boolean" || other instanceof Boolean; + if (this.sample === BigInt) + return typeof other == "bigint" || other instanceof BigInt; + if (this.sample === Symbol) + return typeof other == "symbol" || other instanceof Symbol; + if (this.sample === Object) + return typeof other == "object"; + return other instanceof this.sample; + } + toString() { + return "Any"; + } + getExpectedType() { + if (this.sample === String) + return "string"; + if (this.sample === Number) + return "number"; + if (this.sample === Function) + return "function"; + if (this.sample === Object) + return "object"; + if (this.sample === Boolean) + return "boolean"; + return this.fnNameFor(this.sample); + } + toAsymmetricMatcher() { + return `Any<${this.fnNameFor(this.sample)}>`; + } +} +class StringMatching extends AsymmetricMatcher { + constructor(sample, inverse = false) { + if (!isA("String", sample) && !isA("RegExp", sample)) + throw new Error("Expected is not a String or a RegExp"); + super(new RegExp(sample), inverse); + } + asymmetricMatch(other) { + const result = isA("String", other) && this.sample.test(other); + return this.inverse ? !result : result; + } + toString() { + return `String${this.inverse ? "Not" : ""}Matching`; + } + getExpectedType() { + return "string"; + } +} +class CloseTo extends AsymmetricMatcher { + precision; + constructor(sample, precision = 2, inverse = false) { + if (!isA("Number", sample)) + throw new Error("Expected is not a Number"); + if (!isA("Number", precision)) + throw new Error("Precision is not a Number"); + super(sample); + this.inverse = inverse; + this.precision = precision; + } + asymmetricMatch(other) { + if (!isA("Number", other)) + return false; + let result = false; + if (other === Number.POSITIVE_INFINITY && this.sample === Number.POSITIVE_INFINITY) { + result = true; + } else if (other === Number.NEGATIVE_INFINITY && this.sample === Number.NEGATIVE_INFINITY) { + result = true; + } else { + result = Math.abs(this.sample - other) < 10 ** -this.precision / 2; + } + return this.inverse ? !result : result; + } + toString() { + return `Number${this.inverse ? "Not" : ""}CloseTo`; + } + getExpectedType() { + return "number"; + } + toAsymmetricMatcher() { + return [ + this.toString(), + this.sample, + `(${pluralize("digit", this.precision)})` + ].join(" "); + } +} +const JestAsymmetricMatchers = (chai, utils) => { + utils.addMethod( + chai.expect, + "anything", + () => new Anything() + ); + utils.addMethod( + chai.expect, + "any", + (expected) => new Any(expected) + ); + utils.addMethod( + chai.expect, + "stringContaining", + (expected) => new StringContaining(expected) + ); + utils.addMethod( + chai.expect, + "objectContaining", + (expected) => new ObjectContaining(expected) + ); + utils.addMethod( + chai.expect, + "arrayContaining", + (expected) => new ArrayContaining(expected) + ); + utils.addMethod( + chai.expect, + "stringMatching", + (expected) => new StringMatching(expected) + ); + utils.addMethod( + chai.expect, + "closeTo", + (expected, precision) => new CloseTo(expected, precision) + ); + chai.expect.not = { + stringContaining: (expected) => new StringContaining(expected, true), + objectContaining: (expected) => new ObjectContaining(expected, true), + arrayContaining: (expected) => new ArrayContaining(expected, true), + stringMatching: (expected) => new StringMatching(expected, true), + closeTo: (expected, precision) => new CloseTo(expected, precision, true) + }; +}; + +function recordAsyncExpect(test, promise) { + if (test && promise instanceof Promise) { + promise = promise.finally(() => { + const index = test.promises.indexOf(promise); + if (index !== -1) + test.promises.splice(index, 1); + }); + if (!test.promises) + test.promises = []; + test.promises.push(promise); + } + return promise; +} +function wrapSoft(utils, fn) { + return function(...args) { + var _a; + const test = utils.flag(this, "vitest-test"); + const state = (test == null ? void 0 : test.context._local) ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]); + if (!state.soft) + return fn.apply(this, args); + if (!test) + throw new Error("expect.soft() can only be used inside a test"); + try { + return fn.apply(this, args); + } catch (err) { + test.result || (test.result = { state: "fail" }); + test.result.state = "fail"; + (_a = test.result).errors || (_a.errors = []); + test.result.errors.push(processError(err)); + } + }; +} + +const JestChaiExpect = (chai, utils) => { + const { AssertionError } = chai; + const c = () => getColors(); + const customTesters = getCustomEqualityTesters(); + function def(name, fn) { + const addMethod = (n) => { + const softWrapper = wrapSoft(utils, fn); + utils.addMethod(chai.Assertion.prototype, n, softWrapper); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, softWrapper); + }; + if (Array.isArray(name)) + name.forEach((n) => addMethod(n)); + else + addMethod(name); + } + ["throw", "throws", "Throw"].forEach((m) => { + utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => { + return function(...args) { + const promise = utils.flag(this, "promise"); + const object = utils.flag(this, "object"); + const isNot = utils.flag(this, "negate"); + if (promise === "rejects") { + utils.flag(this, "object", () => { + throw object; + }); + } else if (promise === "resolves" && typeof object !== "function") { + if (!isNot) { + const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; + const error = { + showDiff: false + }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } else { + return; + } + } + _super.apply(this, args); + }; + }); + }); + def("withTest", function(test) { + utils.flag(this, "vitest-test", test); + return this; + }); + def("toEqual", function(expected) { + const actual = utils.flag(this, "object"); + const equal = equals( + actual, + expected, + [...customTesters, iterableEquality] + ); + return this.assert( + equal, + "expected #{this} to deeply equal #{exp}", + "expected #{this} to not deeply equal #{exp}", + expected, + actual + ); + }); + def("toStrictEqual", function(expected) { + const obj = utils.flag(this, "object"); + const equal = equals( + obj, + expected, + [ + ...customTesters, + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], + true + ); + return this.assert( + equal, + "expected #{this} to strictly equal #{exp}", + "expected #{this} to not strictly equal #{exp}", + expected, + obj + ); + }); + def("toBe", function(expected) { + const actual = this._obj; + const pass = Object.is(actual, expected); + let deepEqualityName = ""; + if (!pass) { + const toStrictEqualPass = equals( + actual, + expected, + [ + ...customTesters, + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], + true + ); + if (toStrictEqualPass) { + deepEqualityName = "toStrictEqual"; + } else { + const toEqualPass = equals( + actual, + expected, + [...customTesters, iterableEquality] + ); + if (toEqualPass) + deepEqualityName = "toEqual"; + } + } + return this.assert( + pass, + generateToBeMessage(deepEqualityName), + "expected #{this} not to be #{exp} // Object.is equality", + expected, + actual + ); + }); + def("toMatchObject", function(expected) { + const actual = this._obj; + return this.assert( + equals(actual, expected, [...customTesters, iterableEquality, subsetEquality]), + "expected #{this} to match object #{exp}", + "expected #{this} to not match object #{exp}", + expected, + actual + ); + }); + def("toMatch", function(expected) { + if (typeof expected === "string") + return this.include(expected); + else + return this.match(expected); + }); + def("toContain", function(item) { + const actual = this._obj; + if (typeof Node !== "undefined" && actual instanceof Node) { + if (!(item instanceof Node)) + throw new TypeError(`toContain() expected a DOM node as the argument, but got ${typeof item}`); + return this.assert( + actual.contains(item), + "expected #{this} to contain element #{exp}", + "expected #{this} not to contain element #{exp}", + item, + actual + ); + } + if (typeof DOMTokenList !== "undefined" && actual instanceof DOMTokenList) { + assertTypes(item, "class name", ["string"]); + const isNot = utils.flag(this, "negate"); + const expectedClassList = isNot ? actual.value.replace(item, "").trim() : `${actual.value} ${item}`; + return this.assert( + actual.contains(item), + `expected "${actual.value}" to contain "${item}"`, + `expected "${actual.value}" not to contain "${item}"`, + expectedClassList, + actual.value + ); + } + if (actual != null && typeof actual !== "string") + utils.flag(this, "object", Array.from(actual)); + return this.contain(item); + }); + def("toContainEqual", function(expected) { + const obj = utils.flag(this, "object"); + const index = Array.from(obj).findIndex((item) => { + return equals(item, expected, customTesters); + }); + this.assert( + index !== -1, + "expected #{this} to deep equally contain #{exp}", + "expected #{this} to not deep equally contain #{exp}", + expected + ); + }); + def("toBeTruthy", function() { + const obj = utils.flag(this, "object"); + this.assert( + Boolean(obj), + "expected #{this} to be truthy", + "expected #{this} to not be truthy", + obj, + false + ); + }); + def("toBeFalsy", function() { + const obj = utils.flag(this, "object"); + this.assert( + !obj, + "expected #{this} to be falsy", + "expected #{this} to not be falsy", + obj, + false + ); + }); + def("toBeGreaterThan", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual > expected, + `expected ${actual} to be greater than ${expected}`, + `expected ${actual} to be not greater than ${expected}`, + actual, + expected, + false + ); + }); + def("toBeGreaterThanOrEqual", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual >= expected, + `expected ${actual} to be greater than or equal to ${expected}`, + `expected ${actual} to be not greater than or equal to ${expected}`, + actual, + expected, + false + ); + }); + def("toBeLessThan", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual < expected, + `expected ${actual} to be less than ${expected}`, + `expected ${actual} to be not less than ${expected}`, + actual, + expected, + false + ); + }); + def("toBeLessThanOrEqual", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual <= expected, + `expected ${actual} to be less than or equal to ${expected}`, + `expected ${actual} to be not less than or equal to ${expected}`, + actual, + expected, + false + ); + }); + def("toBeNaN", function() { + return this.be.NaN; + }); + def("toBeUndefined", function() { + return this.be.undefined; + }); + def("toBeNull", function() { + return this.be.null; + }); + def("toBeDefined", function() { + const negate = utils.flag(this, "negate"); + utils.flag(this, "negate", false); + if (negate) + return this.be.undefined; + return this.not.be.undefined; + }); + def("toBeTypeOf", function(expected) { + const actual = typeof this._obj; + const equal = expected === actual; + return this.assert( + equal, + "expected #{this} to be type of #{exp}", + "expected #{this} not to be type of #{exp}", + expected, + actual + ); + }); + def("toBeInstanceOf", function(obj) { + return this.instanceOf(obj); + }); + def("toHaveLength", function(length) { + return this.have.length(length); + }); + def("toHaveProperty", function(...args) { + if (Array.isArray(args[0])) + args[0] = args[0].map((key) => String(key).replace(/([.[\]])/g, "\\$1")).join("."); + const actual = this._obj; + const [propertyName, expected] = args; + const getValue = () => { + const hasOwn = Object.prototype.hasOwnProperty.call(actual, propertyName); + if (hasOwn) + return { value: actual[propertyName], exists: true }; + return utils.getPathInfo(actual, propertyName); + }; + const { value, exists } = getValue(); + const pass = exists && (args.length === 1 || equals(expected, value, customTesters)); + const valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`; + return this.assert( + pass, + `expected #{this} to have property "${propertyName}"${valueString}`, + `expected #{this} to not have property "${propertyName}"${valueString}`, + expected, + exists ? value : void 0 + ); + }); + def("toBeCloseTo", function(received, precision = 2) { + const expected = this._obj; + let pass = false; + let expectedDiff = 0; + let receivedDiff = 0; + if (received === Number.POSITIVE_INFINITY && expected === Number.POSITIVE_INFINITY) { + pass = true; + } else if (received === Number.NEGATIVE_INFINITY && expected === Number.NEGATIVE_INFINITY) { + pass = true; + } else { + expectedDiff = 10 ** -precision / 2; + receivedDiff = Math.abs(expected - received); + pass = receivedDiff < expectedDiff; + } + return this.assert( + pass, + `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, + `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, + received, + expected, + false + ); + }); + const assertIsMock = (assertion) => { + if (!isMockFunction(assertion._obj)) + throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`); + }; + const getSpy = (assertion) => { + assertIsMock(assertion); + return assertion._obj; + }; + const ordinalOf = (i) => { + const j = i % 10; + const k = i % 100; + if (j === 1 && k !== 11) + return `${i}st`; + if (j === 2 && k !== 12) + return `${i}nd`; + if (j === 3 && k !== 13) + return `${i}rd`; + return `${i}th`; + }; + const formatCalls = (spy, msg, actualCall) => { + if (spy.mock.calls) { + msg += c().gray(` + +Received: + +${spy.mock.calls.map((callArg, i) => { + let methodCall = c().bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call: + +`); + if (actualCall) + methodCall += diff(actualCall, callArg, { omitAnnotationLines: true }); + else + methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n"); + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + } + msg += c().gray(` + +Number of calls: ${c().bold(spy.mock.calls.length)} +`); + return msg; + }; + const formatReturns = (spy, msg, actualReturn) => { + msg += c().gray(` + +Received: + +${spy.mock.results.map((callReturn, i) => { + let methodCall = c().bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return: + +`); + if (actualReturn) + methodCall += diff(actualReturn, callReturn.value, { omitAnnotationLines: true }); + else + methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n"); + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + msg += c().gray(` + +Number of calls: ${c().bold(spy.mock.calls.length)} +`); + return msg; + }; + def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + return this.assert( + callCount === number, + `expected "${spyName}" to be called #{exp} times, but got ${callCount} times`, + `expected "${spyName}" to not be called #{exp} times`, + number, + callCount, + false + ); + }); + def("toHaveBeenCalledOnce", function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + return this.assert( + callCount === 1, + `expected "${spyName}" to be called once, but got ${callCount} times`, + `expected "${spyName}" to not be called once`, + 1, + callCount, + false + ); + }); + def(["toHaveBeenCalled", "toBeCalled"], function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + const called = callCount > 0; + const isNot = utils.flag(this, "negate"); + let msg = utils.getMessage( + this, + [ + called, + `expected "${spyName}" to be called at least once`, + `expected "${spyName}" to not be called at all, but actually been called ${callCount} times`, + true, + called + ] + ); + if (called && isNot) + msg = formatCalls(spy, msg); + if (called && isNot || !called && !isNot) + throw new AssertionError(msg); + }); + def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = spy.mock.calls.some((callArg) => equals(callArg, args, [...customTesters, iterableEquality])); + const isNot = utils.flag(this, "negate"); + const msg = utils.getMessage( + this, + [ + pass, + `expected "${spyName}" to be called with arguments: #{exp}`, + `expected "${spyName}" to not be called with arguments: #{exp}`, + args + ] + ); + if (pass && isNot || !pass && !isNot) + throw new AssertionError(formatCalls(spy, msg, args)); + }); + def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const nthCall = spy.mock.calls[times - 1]; + this.assert( + equals(nthCall, args, [...customTesters, iterableEquality]), + `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`, + `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, + args, + nthCall + ); + }); + def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const lastCall = spy.mock.calls[spy.mock.calls.length - 1]; + this.assert( + equals(lastCall, args, [...customTesters, iterableEquality]), + `expected last "${spyName}" call to have been called with #{exp}`, + `expected last "${spyName}" call to not have been called with #{exp}`, + args, + lastCall + ); + }); + def(["toThrow", "toThrowError"], function(expected) { + if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp) + return this.throws(expected); + const obj = this._obj; + const promise = utils.flag(this, "promise"); + const isNot = utils.flag(this, "negate"); + let thrown = null; + if (promise === "rejects") { + thrown = obj; + } else if (promise === "resolves" && typeof obj !== "function") { + if (!isNot) { + const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; + const error = { + showDiff: false + }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } else { + return; + } + } else { + let isThrow = false; + try { + obj(); + } catch (err) { + isThrow = true; + thrown = err; + } + if (!isThrow && !isNot) { + const message = utils.flag(this, "message") || "expected function to throw an error, but it didn't"; + const error = { + showDiff: false + }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } + } + if (typeof expected === "function") { + const name = expected.name || expected.prototype.constructor.name; + return this.assert( + thrown && thrown instanceof expected, + `expected error to be instance of ${name}`, + `expected error not to be instance of ${name}`, + expected, + thrown + ); + } + if (expected instanceof Error) { + return this.assert( + thrown && expected.message === thrown.message, + `expected error to have message: ${expected.message}`, + `expected error not to have message: ${expected.message}`, + expected.message, + thrown && thrown.message + ); + } + if (typeof expected === "object" && "asymmetricMatch" in expected && typeof expected.asymmetricMatch === "function") { + const matcher = expected; + return this.assert( + thrown && matcher.asymmetricMatch(thrown), + "expected error to match asymmetric matcher", + "expected error not to match asymmetric matcher", + matcher, + thrown + ); + } + throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`); + }); + def(["toHaveReturned", "toReturn"], function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const calledAndNotThrew = spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type !== "throw"); + this.assert( + calledAndNotThrew, + `expected "${spyName}" to be successfully called at least once`, + `expected "${spyName}" to not be successfully called`, + calledAndNotThrew, + !calledAndNotThrew, + false + ); + }); + def(["toHaveReturnedTimes", "toReturnTimes"], function(times) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const successfulReturns = spy.mock.results.reduce((success, { type }) => type === "throw" ? success : ++success, 0); + this.assert( + successfulReturns === times, + `expected "${spyName}" to be successfully called ${times} times`, + `expected "${spyName}" to not be successfully called ${times} times`, + `expected number of returns: ${times}`, + `received number of returns: ${successfulReturns}`, + false + ); + }); + def(["toHaveReturnedWith", "toReturnWith"], function(value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result)); + const isNot = utils.flag(this, "negate"); + const msg = utils.getMessage( + this, + [ + pass, + `expected "${spyName}" to return with: #{exp} at least once`, + `expected "${spyName}" to not return with: #{exp}`, + value + ] + ); + if (pass && isNot || !pass && !isNot) + throw new AssertionError(formatReturns(spy, msg, value)); + }); + def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const { value: lastResult } = spy.mock.results[spy.mock.results.length - 1]; + const pass = equals(lastResult, value); + this.assert( + pass, + `expected last "${spyName}" call to return #{exp}`, + `expected last "${spyName}" call to not return #{exp}`, + value, + lastResult + ); + }); + def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const isNot = utils.flag(this, "negate"); + const { type: callType, value: callResult } = spy.mock.results[nthCall - 1]; + const ordinalCall = `${ordinalOf(nthCall)} call`; + if (!isNot && callType === "throw") + chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`); + const nthCallReturn = equals(callResult, value); + this.assert( + nthCallReturn, + `expected ${ordinalCall} "${spyName}" call to return #{exp}`, + `expected ${ordinalCall} "${spyName}" call to not return #{exp}`, + value, + callResult + ); + }); + def("toSatisfy", function(matcher, message) { + return this.be.satisfy(matcher, message); + }); + utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() { + const error = new Error("resolves"); + utils.flag(this, "promise", "resolves"); + utils.flag(this, "error", error); + const test = utils.flag(this, "vitest-test"); + const obj = utils.flag(this, "object"); + if (typeof (obj == null ? void 0 : obj.then) !== "function") + throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`); + const proxy = new Proxy(this, { + get: (target, key, receiver) => { + const result = Reflect.get(target, key, receiver); + if (typeof result !== "function") + return result instanceof chai.Assertion ? proxy : result; + return async (...args) => { + const promise = obj.then( + (value) => { + utils.flag(this, "object", value); + return result.call(this, ...args); + }, + (err) => { + const _error = new AssertionError( + `promise rejected "${utils.inspect(err)}" instead of resolving`, + { showDiff: false } + ); + _error.cause = err; + _error.stack = error.stack.replace(error.message, _error.message); + throw _error; + } + ); + return recordAsyncExpect(test, promise); + }; + } + }); + return proxy; + }); + utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() { + const error = new Error("rejects"); + utils.flag(this, "promise", "rejects"); + utils.flag(this, "error", error); + const test = utils.flag(this, "vitest-test"); + const obj = utils.flag(this, "object"); + const wrapper = typeof obj === "function" ? obj() : obj; + if (typeof (wrapper == null ? void 0 : wrapper.then) !== "function") + throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`); + const proxy = new Proxy(this, { + get: (target, key, receiver) => { + const result = Reflect.get(target, key, receiver); + if (typeof result !== "function") + return result instanceof chai.Assertion ? proxy : result; + return async (...args) => { + const promise = wrapper.then( + (value) => { + const _error = new AssertionError( + `promise resolved "${utils.inspect(value)}" instead of rejecting`, + { showDiff: true, expected: new Error("rejected promise"), actual: value } + ); + _error.stack = error.stack.replace(error.message, _error.message); + throw _error; + }, + (err) => { + utils.flag(this, "object", err); + return result.call(this, ...args); + } + ); + return recordAsyncExpect(test, promise); + }; + } + }); + return proxy; + }); +}; + +function getMatcherState(assertion, expect) { + const obj = assertion._obj; + const isNot = util.flag(assertion, "negate"); + const promise = util.flag(assertion, "promise") || ""; + const jestUtils = { + ...getMatcherUtils(), + diff, + stringify, + iterableEquality, + subsetEquality + }; + const matcherState = { + ...getState(expect), + customTesters: getCustomEqualityTesters(), + isNot, + utils: jestUtils, + promise, + equals, + // needed for built-in jest-snapshots, but we don't use it + suppressedErrors: [] + }; + return { + state: matcherState, + isNot, + obj + }; +} +class JestExtendError extends Error { + constructor(message, actual, expected) { + super(message); + this.actual = actual; + this.expected = expected; + } +} +function JestExtendPlugin(expect, matchers) { + return (c, utils) => { + Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => { + function expectWrapper(...args) { + const { state, isNot, obj } = getMatcherState(this, expect); + const result = expectAssertion.call(state, obj, ...args); + if (result && typeof result === "object" && result instanceof Promise) { + return result.then(({ pass: pass2, message: message2, actual: actual2, expected: expected2 }) => { + if (pass2 && isNot || !pass2 && !isNot) + throw new JestExtendError(message2(), actual2, expected2); + }); + } + const { pass, message, actual, expected } = result; + if (pass && isNot || !pass && !isNot) + throw new JestExtendError(message(), actual, expected); + } + const softWrapper = wrapSoft(utils, expectWrapper); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper); + utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper); + class CustomMatcher extends AsymmetricMatcher { + constructor(inverse = false, ...sample) { + super(sample, inverse); + } + asymmetricMatch(other) { + const { pass } = expectAssertion.call( + this.getMatcherContext(expect), + other, + ...this.sample + ); + return this.inverse ? !pass : pass; + } + toString() { + return `${this.inverse ? "not." : ""}${expectAssertionName}`; + } + getExpectedType() { + return "any"; + } + toAsymmetricMatcher() { + return `${this.toString()}<${this.sample.map(String).join(", ")}>`; + } + } + const customMatcher = (...sample) => new CustomMatcher(false, ...sample); + Object.defineProperty(expect, expectAssertionName, { + configurable: true, + enumerable: true, + value: customMatcher, + writable: true + }); + Object.defineProperty(expect.not, expectAssertionName, { + configurable: true, + enumerable: true, + value: (...sample) => new CustomMatcher(true, ...sample), + writable: true + }); + Object.defineProperty(globalThis[ASYMMETRIC_MATCHERS_OBJECT], expectAssertionName, { + configurable: true, + enumerable: true, + value: customMatcher, + writable: true + }); + }); + }; +} +const JestExtend = (chai, utils) => { + utils.addMethod(chai.expect, "extend", (expect, expects) => { + chai.use(JestExtendPlugin(expect, expects)); + }); +}; + +export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, equals, fnNameFor, generateToBeMessage, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality }; diff --git a/web/node_modules/@vitest/expect/index.d.ts b/web/node_modules/@vitest/expect/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b82ac4009099eb50b45e97d7407b4bdfe777fb9 --- /dev/null +++ b/web/node_modules/@vitest/expect/index.d.ts @@ -0,0 +1,3 @@ +import './dist/chai.cjs' + +export * from './dist/index.js' diff --git a/web/node_modules/@vitest/expect/package.json b/web/node_modules/@vitest/expect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..690ce2b38fc9a938da13de57c8efcfc1edaa5178 --- /dev/null +++ b/web/node_modules/@vitest/expect/package.json @@ -0,0 +1,47 @@ +{ + "name": "@vitest/expect", + "type": "module", + "version": "1.3.1", + "description": "Jest's expect matchers as a Chai plugin", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/expect" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "chai": "^4.3.10", + "@vitest/spy": "1.3.1", + "@vitest/utils": "1.3.1" + }, + "devDependencies": { + "@types/chai": "4.3.6", + "picocolors": "^1.0.0", + "rollup-plugin-copy": "^3.5.0", + "@vitest/runner": "1.3.1" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/web/node_modules/@vitest/runner/LICENSE b/web/node_modules/@vitest/runner/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ae481fdb8ea5d7ab1dac9e5138d77cd80fbfb8c --- /dev/null +++ b/web/node_modules/@vitest/runner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present Vitest Team + +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/web/node_modules/@vitest/runner/README.md b/web/node_modules/@vitest/runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2796b6aacd03bef6727c03a2eb3f2635cdb521e7 --- /dev/null +++ b/web/node_modules/@vitest/runner/README.md @@ -0,0 +1,5 @@ +# @vitest/runner + +Vitest mechanism to collect and run tasks. + +[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/advanced/runner) diff --git a/web/node_modules/@vitest/runner/dist/chunk-tasks.js b/web/node_modules/@vitest/runner/dist/chunk-tasks.js new file mode 100644 index 0000000000000000000000000000000000000000..6628bc57a014a4f2e4626dc268344f0e635cd55c --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/chunk-tasks.js @@ -0,0 +1,171 @@ +import { processError } from '@vitest/utils/error'; +import { toArray } from '@vitest/utils'; + +function partitionSuiteChildren(suite) { + let tasksGroup = []; + const tasksGroups = []; + for (const c of suite.tasks) { + if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) { + tasksGroup.push(c); + } else { + tasksGroups.push(tasksGroup); + tasksGroup = [c]; + } + } + if (tasksGroup.length > 0) + tasksGroups.push(tasksGroup); + return tasksGroups; +} + +function interpretTaskModes(suite, namePattern, onlyMode, parentIsOnly, allowOnly) { + const suiteIsOnly = parentIsOnly || suite.mode === "only"; + suite.tasks.forEach((t) => { + const includeTask = suiteIsOnly || t.mode === "only"; + if (onlyMode) { + if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) { + if (t.mode === "only") { + checkAllowOnly(t, allowOnly); + t.mode = "run"; + } + } else if (t.mode === "run" && !includeTask) { + t.mode = "skip"; + } else if (t.mode === "only") { + checkAllowOnly(t, allowOnly); + t.mode = "run"; + } + } + if (t.type === "test") { + if (namePattern && !getTaskFullName(t).match(namePattern)) + t.mode = "skip"; + } else if (t.type === "suite") { + if (t.mode === "skip") + skipAllTasks(t); + else + interpretTaskModes(t, namePattern, onlyMode, includeTask, allowOnly); + } + }); + if (suite.mode === "run") { + if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run")) + suite.mode = "skip"; + } +} +function getTaskFullName(task) { + return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`; +} +function someTasksAreOnly(suite) { + return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); +} +function skipAllTasks(suite) { + suite.tasks.forEach((t) => { + if (t.mode === "run") { + t.mode = "skip"; + if (t.type === "suite") + skipAllTasks(t); + } + }); +} +function checkAllowOnly(task, allowOnly) { + if (allowOnly) + return; + const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error")); + task.result = { + state: "fail", + errors: [error] + }; +} +function generateHash(str) { + let hash = 0; + if (str.length === 0) + return `${hash}`; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; + } + return `${hash}`; +} +function calculateSuiteHash(parent) { + parent.tasks.forEach((t, idx) => { + t.id = `${parent.id}_${idx}`; + if (t.type === "suite") + calculateSuiteHash(t); + }); +} + +function createChainable(keys, fn) { + function create(context) { + const chain2 = function(...args) { + return fn.apply(context, args); + }; + Object.assign(chain2, fn); + chain2.withContext = () => chain2.bind(context); + chain2.setContext = (key, value) => { + context[key] = value; + }; + chain2.mergeContext = (ctx) => { + Object.assign(context, ctx); + }; + for (const key of keys) { + Object.defineProperty(chain2, key, { + get() { + return create({ ...context, [key]: true }); + } + }); + } + return chain2; + } + const chain = create({}); + chain.fn = fn; + return chain; +} + +function isAtomTest(s) { + return s.type === "test" || s.type === "custom"; +} +function getTests(suite) { + const tests = []; + const arraySuites = toArray(suite); + for (const s of arraySuites) { + if (isAtomTest(s)) { + tests.push(s); + } else { + for (const task of s.tasks) { + if (isAtomTest(task)) { + tests.push(task); + } else { + const taskTests = getTests(task); + for (const test of taskTests) + tests.push(test); + } + } + } + } + return tests; +} +function getTasks(tasks = []) { + return toArray(tasks).flatMap((s) => isAtomTest(s) ? [s] : [s, ...getTasks(s.tasks)]); +} +function getSuites(suite) { + return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []); +} +function hasTests(suite) { + return toArray(suite).some((s) => s.tasks.some((c) => isAtomTest(c) || hasTests(c))); +} +function hasFailed(suite) { + return toArray(suite).some((s) => { + var _a; + return ((_a = s.result) == null ? void 0 : _a.state) === "fail" || s.type === "suite" && hasFailed(s.tasks); + }); +} +function getNames(task) { + const names = [task.name]; + let current = task; + while ((current == null ? void 0 : current.suite) || (current == null ? void 0 : current.file)) { + current = current.suite || current.file; + if (current == null ? void 0 : current.name) + names.unshift(current.name); + } + return names; +} + +export { getTests as a, getTasks as b, calculateSuiteHash as c, getSuites as d, hasFailed as e, getNames as f, generateHash as g, hasTests as h, interpretTaskModes as i, createChainable as j, partitionSuiteChildren as p, someTasksAreOnly as s }; diff --git a/web/node_modules/@vitest/runner/dist/index.d.ts b/web/node_modules/@vitest/runner/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6393190a5084404ce37bb886d7079a7fa187eb6 --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/index.d.ts @@ -0,0 +1,33 @@ +import { VitestRunner } from './types.js'; +export { CancelReason, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource } from './types.js'; +import { T as Task, F as File, d as SuiteAPI, e as TestAPI, f as SuiteCollector, g as CustomAPI, h as SuiteHooks, O as OnTestFailedHandler, i as OnTestFinishedHandler, a as Test, C as Custom, S as Suite } from './tasks-_kyNRBhz.js'; +export { D as DoneCallback, E as ExtendedContext, t as Fixture, s as FixtureFn, r as FixtureOptions, u as Fixtures, v as HookCleanupCallback, H as HookListener, I as InferFixturesTypes, R as RunMode, y as RuntimeContext, B as SequenceHooks, G as SequenceSetupFiles, x as SuiteFactory, k as TaskBase, A as TaskContext, w as TaskCustomOptions, m as TaskMeta, l as TaskPopulated, n as TaskResult, o as TaskResultPack, j as TaskState, z as TestContext, p as TestFunction, q as TestOptions, U as Use } from './tasks-_kyNRBhz.js'; +import { Awaitable } from '@vitest/utils'; +export { processError } from '@vitest/utils/error'; +import '@vitest/utils/diff'; + +declare function updateTask(task: Task, runner: VitestRunner): void; +declare function startTests(paths: string[], runner: VitestRunner): Promise; + +declare const suite: SuiteAPI; +declare const test: TestAPI; +declare const describe: SuiteAPI; +declare const it: TestAPI; +declare function getCurrentSuite(): SuiteCollector; +declare function createTaskCollector(fn: (...args: any[]) => any, context?: Record): CustomAPI; + +declare function beforeAll(fn: SuiteHooks['beforeAll'][0], timeout?: number): void; +declare function afterAll(fn: SuiteHooks['afterAll'][0], timeout?: number): void; +declare function beforeEach(fn: SuiteHooks['beforeEach'][0], timeout?: number): void; +declare function afterEach(fn: SuiteHooks['afterEach'][0], timeout?: number): void; +declare const onTestFailed: (fn: OnTestFailedHandler) => void; +declare const onTestFinished: (fn: OnTestFinishedHandler) => void; + +declare function setFn(key: Test | Custom, fn: (() => Awaitable)): void; +declare function getFn(key: Task): (() => Awaitable); +declare function setHooks(key: Suite, hooks: SuiteHooks): void; +declare function getHooks(key: Suite): SuiteHooks; + +declare function getCurrentTest(): T; + +export { Custom, CustomAPI, File, OnTestFailedHandler, OnTestFinishedHandler, Suite, SuiteAPI, SuiteCollector, SuiteHooks, Task, Test, TestAPI, VitestRunner, afterAll, afterEach, beforeAll, beforeEach, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/web/node_modules/@vitest/runner/dist/index.js b/web/node_modules/@vitest/runner/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..df62bea3ebaf9ee4fc265f7e2e7906872b426cc7 --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/index.js @@ -0,0 +1,943 @@ +import limit from 'p-limit'; +import { getSafeTimers, isObject, createDefer, format, objDisplay, objectAttr, toArray, shuffle } from '@vitest/utils'; +import { processError } from '@vitest/utils/error'; +export { processError } from '@vitest/utils/error'; +import { j as createChainable, g as generateHash, c as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, p as partitionSuiteChildren, h as hasTests, e as hasFailed } from './chunk-tasks.js'; +import { relative } from 'pathe'; + +const fnMap = /* @__PURE__ */ new WeakMap(); +const fixtureMap = /* @__PURE__ */ new WeakMap(); +const hooksMap = /* @__PURE__ */ new WeakMap(); +function setFn(key, fn) { + fnMap.set(key, fn); +} +function getFn(key) { + return fnMap.get(key); +} +function setFixture(key, fixture) { + fixtureMap.set(key, fixture); +} +function getFixture(key) { + return fixtureMap.get(key); +} +function setHooks(key, hooks) { + hooksMap.set(key, hooks); +} +function getHooks(key) { + return hooksMap.get(key); +} + +class PendingError extends Error { + constructor(message, task) { + super(message); + this.message = message; + this.taskId = task.id; + } + code = "VITEST_PENDING"; + taskId; +} + +const collectorContext = { + tasks: [], + currentSuite: null +}; +function collectTask(task) { + var _a; + (_a = collectorContext.currentSuite) == null ? void 0 : _a.tasks.push(task); +} +async function runWithSuite(suite, fn) { + const prev = collectorContext.currentSuite; + collectorContext.currentSuite = suite; + await fn(); + collectorContext.currentSuite = prev; +} +function withTimeout(fn, timeout, isHook = false) { + if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) + return fn; + const { setTimeout, clearTimeout } = getSafeTimers(); + return (...args) => { + return Promise.race([fn(...args), new Promise((resolve, reject) => { + var _a; + const timer = setTimeout(() => { + clearTimeout(timer); + reject(new Error(makeTimeoutMsg(isHook, timeout))); + }, timeout); + (_a = timer.unref) == null ? void 0 : _a.call(timer); + })]); + }; +} +function createTestContext(test, runner) { + var _a; + const context = function() { + throw new Error("done() callback is deprecated, use promise instead"); + }; + context.task = test; + context.skip = () => { + test.pending = true; + throw new PendingError("test is skipped; abort execution", test); + }; + context.onTestFailed = (fn) => { + test.onFailed || (test.onFailed = []); + test.onFailed.push(fn); + }; + context.onTestFinished = (fn) => { + test.onFinished || (test.onFinished = []); + test.onFinished.push(fn); + }; + return ((_a = runner.extendTaskContext) == null ? void 0 : _a.call(runner, context)) || context; +} +function makeTimeoutMsg(isHook, timeout) { + return `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms. +If this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`; +} + +function mergeContextFixtures(fixtures, context = {}) { + const fixtureOptionKeys = ["auto"]; + const fixtureArray = Object.entries(fixtures).map(([prop, value]) => { + const fixtureItem = { value }; + if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) { + Object.assign(fixtureItem, value[1]); + fixtureItem.value = value[0]; + } + fixtureItem.prop = prop; + fixtureItem.isFn = typeof fixtureItem.value === "function"; + return fixtureItem; + }); + if (Array.isArray(context.fixtures)) + context.fixtures = context.fixtures.concat(fixtureArray); + else + context.fixtures = fixtureArray; + fixtureArray.forEach((fixture) => { + if (fixture.isFn) { + const usedProps = getUsedProps(fixture.value); + if (usedProps.length) + fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop)); + } + }); + return context; +} +const fixtureValueMaps = /* @__PURE__ */ new Map(); +const cleanupFnArrayMap = /* @__PURE__ */ new Map(); +async function callFixtureCleanup(context) { + const cleanupFnArray = cleanupFnArrayMap.get(context) ?? []; + for (const cleanup of cleanupFnArray.reverse()) + await cleanup(); + cleanupFnArrayMap.delete(context); +} +function withFixtures(fn, testContext) { + return (hookContext) => { + const context = hookContext || testContext; + if (!context) + return fn({}); + const fixtures = getFixture(context); + if (!(fixtures == null ? void 0 : fixtures.length)) + return fn(context); + const usedProps = getUsedProps(fn); + const hasAutoFixture = fixtures.some(({ auto }) => auto); + if (!usedProps.length && !hasAutoFixture) + return fn(context); + if (!fixtureValueMaps.get(context)) + fixtureValueMaps.set(context, /* @__PURE__ */ new Map()); + const fixtureValueMap = fixtureValueMaps.get(context); + if (!cleanupFnArrayMap.has(context)) + cleanupFnArrayMap.set(context, []); + const cleanupFnArray = cleanupFnArrayMap.get(context); + const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop)); + const pendingFixtures = resolveDeps(usedFixtures); + if (!pendingFixtures.length) + return fn(context); + async function resolveFixtures() { + for (const fixture of pendingFixtures) { + if (fixtureValueMap.has(fixture)) + continue; + const resolvedValue = fixture.isFn ? await resolveFixtureFunction(fixture.value, context, cleanupFnArray) : fixture.value; + context[fixture.prop] = resolvedValue; + fixtureValueMap.set(fixture, resolvedValue); + cleanupFnArray.unshift(() => { + fixtureValueMap.delete(fixture); + }); + } + } + return resolveFixtures().then(() => fn(context)); + }; +} +async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) { + const useFnArgPromise = createDefer(); + let isUseFnArgResolved = false; + const fixtureReturn = fixtureFn(context, async (useFnArg) => { + isUseFnArgResolved = true; + useFnArgPromise.resolve(useFnArg); + const useReturnPromise = createDefer(); + cleanupFnArray.push(async () => { + useReturnPromise.resolve(); + await fixtureReturn; + }); + await useReturnPromise; + }).catch((e) => { + if (!isUseFnArgResolved) { + useFnArgPromise.reject(e); + return; + } + throw e; + }); + return useFnArgPromise; +} +function resolveDeps(fixtures, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) { + fixtures.forEach((fixture) => { + if (pendingFixtures.includes(fixture)) + return; + if (!fixture.isFn || !fixture.deps) { + pendingFixtures.push(fixture); + return; + } + if (depSet.has(fixture)) + throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`); + depSet.add(fixture); + resolveDeps(fixture.deps, depSet, pendingFixtures); + pendingFixtures.push(fixture); + depSet.clear(); + }); + return pendingFixtures; +} +function getUsedProps(fn) { + const match = fn.toString().match(/[^(]*\(([^)]*)/); + if (!match) + return []; + const args = splitByComma(match[1]); + if (!args.length) + return []; + const first = args[0]; + if (!(first.startsWith("{") && first.endsWith("}"))) + throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`); + const _first = first.slice(1, -1).replace(/\s/g, ""); + const props = splitByComma(_first).map((prop) => { + return prop.replace(/\:.*|\=.*/g, ""); + }); + const last = props.at(-1); + if (last && last.startsWith("...")) + throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`); + return props; +} +function splitByComma(s) { + const result = []; + const stack = []; + let start = 0; + for (let i = 0; i < s.length; i++) { + if (s[i] === "{" || s[i] === "[") { + stack.push(s[i] === "{" ? "}" : "]"); + } else if (s[i] === stack[stack.length - 1]) { + stack.pop(); + } else if (!stack.length && s[i] === ",") { + const token = s.substring(start, i).trim(); + if (token) + result.push(token); + start = i + 1; + } + } + const lastToken = s.substring(start).trim(); + if (lastToken) + result.push(lastToken); + return result; +} + +let _test; +function setCurrentTest(test) { + _test = test; +} +function getCurrentTest() { + return _test; +} + +const suite = createSuite(); +const test = createTest( + function(name, optionsOrFn, optionsOrTest) { + if (getCurrentTest()) + throw new Error('Calling the test function inside another test function is not allowed. Please put it inside "describe" or "suite" so it can be properly collected.'); + getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest); + } +); +const describe = suite; +const it = test; +let runner; +let defaultSuite; +function getDefaultSuite() { + return defaultSuite; +} +function getRunner() { + return runner; +} +function clearCollectorContext(currentRunner) { + if (!defaultSuite) + defaultSuite = currentRunner.config.sequence.shuffle ? suite.shuffle("") : currentRunner.config.sequence.concurrent ? suite.concurrent("") : suite(""); + runner = currentRunner; + collectorContext.tasks.length = 0; + defaultSuite.clear(); + collectorContext.currentSuite = defaultSuite; +} +function getCurrentSuite() { + return collectorContext.currentSuite || defaultSuite; +} +function createSuiteHooks() { + return { + beforeAll: [], + afterAll: [], + beforeEach: [], + afterEach: [] + }; +} +function parseArguments(optionsOrFn, optionsOrTest) { + let options = {}; + let fn = () => { + }; + if (typeof optionsOrTest === "object") { + if (typeof optionsOrFn === "object") + throw new TypeError("Cannot use two objects as arguments. Please provide options and a function callback in that order."); + options = optionsOrTest; + } else if (typeof optionsOrTest === "number") { + options = { timeout: optionsOrTest }; + } else if (typeof optionsOrFn === "object") { + options = optionsOrFn; + } + if (typeof optionsOrFn === "function") { + if (typeof optionsOrTest === "function") + throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options."); + fn = optionsOrFn; + } else if (typeof optionsOrTest === "function") { + fn = optionsOrTest; + } + return { + options, + handler: fn + }; +} +function createSuiteCollector(name, factory = () => { +}, mode, shuffle, each, suiteOptions) { + const tasks = []; + const factoryQueue = []; + let suite2; + initSuite(); + const task = function(name2 = "", options = {}) { + const task2 = { + id: "", + name: name2, + suite: void 0, + each: options.each, + fails: options.fails, + context: void 0, + type: "custom", + retry: options.retry ?? runner.config.retry, + repeats: options.repeats, + mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run", + meta: options.meta ?? /* @__PURE__ */ Object.create(null) + }; + const handler = options.handler; + if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) + task2.concurrent = true; + if (shuffle) + task2.shuffle = true; + const context = createTestContext(task2, runner); + Object.defineProperty(task2, "context", { + value: context, + enumerable: false + }); + setFixture(context, options.fixtures); + if (handler) { + setFn(task2, withTimeout( + withFixtures(handler, context), + (options == null ? void 0 : options.timeout) ?? runner.config.testTimeout + )); + } + tasks.push(task2); + return task2; + }; + const test2 = createTest(function(name2, optionsOrFn, optionsOrTest) { + let { options, handler } = parseArguments( + optionsOrFn, + optionsOrTest + ); + if (typeof suiteOptions === "object") + options = Object.assign({}, suiteOptions, options); + options.concurrent = this.concurrent || !this.sequential && (options == null ? void 0 : options.concurrent); + options.sequential = this.sequential || !this.concurrent && (options == null ? void 0 : options.sequential); + const test3 = task( + formatName(name2), + { ...this, ...options, handler } + ); + test3.type = "test"; + }); + const collector = { + type: "collector", + name, + mode, + options: suiteOptions, + test: test2, + tasks, + collect, + task, + clear, + on: addHook + }; + function addHook(name2, ...fn) { + getHooks(suite2)[name2].push(...fn); + } + function initSuite() { + if (typeof suiteOptions === "number") + suiteOptions = { timeout: suiteOptions }; + suite2 = { + id: "", + type: "suite", + name, + mode, + each, + shuffle, + tasks: [], + meta: /* @__PURE__ */ Object.create(null), + projectName: "" + }; + setHooks(suite2, createSuiteHooks()); + } + function clear() { + tasks.length = 0; + factoryQueue.length = 0; + initSuite(); + } + async function collect(file) { + factoryQueue.length = 0; + if (factory) + await runWithSuite(collector, () => factory(test2)); + const allChildren = []; + for (const i of [...factoryQueue, ...tasks]) + allChildren.push(i.type === "collector" ? await i.collect(file) : i); + suite2.file = file; + suite2.tasks = allChildren; + allChildren.forEach((task2) => { + task2.suite = suite2; + if (file) + task2.file = file; + }); + return suite2; + } + collectTask(collector); + return collector; +} +function createSuite() { + function suiteFn(name, factoryOrOptions, optionsOrFactory = {}) { + const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run"; + const currentSuite = getCurrentSuite(); + let { options, handler: factory } = parseArguments( + factoryOrOptions, + optionsOrFactory + ); + if (currentSuite == null ? void 0 : currentSuite.options) + options = { ...currentSuite.options, ...options }; + options.concurrent = this.concurrent || !this.sequential && (options == null ? void 0 : options.concurrent); + options.sequential = this.sequential || !this.concurrent && (options == null ? void 0 : options.sequential); + return createSuiteCollector(formatName(name), factory, mode, this.shuffle, this.each, options); + } + suiteFn.each = function(cases, ...args) { + const suite2 = this.withContext(); + this.setContext("each", true); + if (Array.isArray(cases) && args.length) + cases = formatTemplateString(cases, args); + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const arrayOnlyCases = cases.every(Array.isArray); + const { options, handler } = parseArguments( + optionsOrFn, + fnOrOptions + ); + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + arrayOnlyCases ? suite2(formatTitle(_name, items, idx), options, () => handler(...items)) : suite2(formatTitle(_name, items, idx), options, () => handler(i)); + }); + this.setContext("each", void 0); + }; + }; + suiteFn.skipIf = (condition) => condition ? suite.skip : suite; + suiteFn.runIf = (condition) => condition ? suite : suite.skip; + return createChainable( + ["concurrent", "sequential", "shuffle", "skip", "only", "todo"], + suiteFn + ); +} +function createTaskCollector(fn, context) { + const taskFn = fn; + taskFn.each = function(cases, ...args) { + const test2 = this.withContext(); + this.setContext("each", true); + if (Array.isArray(cases) && args.length) + cases = formatTemplateString(cases, args); + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const arrayOnlyCases = cases.every(Array.isArray); + const { options, handler } = parseArguments( + optionsOrFn, + fnOrOptions + ); + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + arrayOnlyCases ? test2(formatTitle(_name, items, idx), options, () => handler(...items)) : test2(formatTitle(_name, items, idx), options, () => handler(i)); + }); + this.setContext("each", void 0); + }; + }; + taskFn.skipIf = function(condition) { + return condition ? this.skip : this; + }; + taskFn.runIf = function(condition) { + return condition ? this : this.skip; + }; + taskFn.extend = function(fixtures) { + const _context = mergeContextFixtures(fixtures, context); + return createTest(function fn2(name, optionsOrFn, optionsOrTest) { + getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest); + }, _context); + }; + const _test = createChainable( + ["concurrent", "sequential", "skip", "only", "todo", "fails"], + taskFn + ); + if (context) + _test.mergeContext(context); + return _test; +} +function createTest(fn, context) { + return createTaskCollector(fn, context); +} +function formatName(name) { + return typeof name === "string" ? name : name instanceof Function ? name.name || "" : String(name); +} +function formatTitle(template, items, idx) { + if (template.includes("%#")) { + template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/__vitest_escaped_%__/g, "%%"); + } + const count = template.split("%").length - 1; + let formatted = format(template, ...items.slice(0, count)); + if (isObject(items[0])) { + formatted = formatted.replace( + /\$([$\w_.]+)/g, + // https://github.com/chaijs/chai/pull/1490 + (_, key) => { + var _a, _b; + return objDisplay(objectAttr(items[0], key), { truncate: (_b = (_a = runner == null ? void 0 : runner.config) == null ? void 0 : _a.chaiConfig) == null ? void 0 : _b.truncateThreshold }); + } + ); + } + return formatted; +} +function formatTemplateString(cases, args) { + const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0]; + const res = []; + for (let i = 0; i < Math.floor(args.length / header.length); i++) { + const oneCase = {}; + for (let j = 0; j < header.length; j++) + oneCase[header[j]] = args[i * header.length + j]; + res.push(oneCase); + } + return res; +} + +async function runSetupFiles(config, runner) { + const files = toArray(config.setupFiles); + if (config.sequence.setupFiles === "parallel") { + await Promise.all( + files.map(async (fsPath) => { + await runner.importFile(fsPath, "setup"); + }) + ); + } else { + for (const fsPath of files) + await runner.importFile(fsPath, "setup"); + } +} + +const now$1 = Date.now; +async function collectTests(paths, runner) { + const files = []; + const config = runner.config; + for (const filepath of paths) { + const path = relative(config.root, filepath); + const file = { + id: generateHash(`${path}${config.name || ""}`), + name: path, + type: "suite", + mode: "run", + filepath, + tasks: [], + meta: /* @__PURE__ */ Object.create(null), + projectName: config.name + }; + clearCollectorContext(runner); + try { + const setupStart = now$1(); + await runSetupFiles(config, runner); + const collectStart = now$1(); + file.setupDuration = collectStart - setupStart; + await runner.importFile(filepath, "collect"); + const defaultTasks = await getDefaultSuite().collect(file); + setHooks(file, getHooks(defaultTasks)); + for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) { + if (c.type === "test") { + file.tasks.push(c); + } else if (c.type === "custom") { + file.tasks.push(c); + } else if (c.type === "suite") { + file.tasks.push(c); + } else if (c.type === "collector") { + const suite = await c.collect(file); + if (suite.name || suite.tasks.length) + file.tasks.push(suite); + } + } + file.collectDuration = now$1() - collectStart; + } catch (e) { + const error = processError(e); + file.result = { + state: "fail", + errors: [error] + }; + } + calculateSuiteHash(file); + const hasOnlyTasks = someTasksAreOnly(file); + interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly); + files.push(file); + } + return files; +} + +const now = Date.now; +function updateSuiteHookState(suite, name, state, runner) { + var _a; + if (!suite.result) + suite.result = { state: "run" }; + if (!((_a = suite.result) == null ? void 0 : _a.hooks)) + suite.result.hooks = {}; + const suiteHooks = suite.result.hooks; + if (suiteHooks) { + suiteHooks[name] = state; + updateTask(suite, runner); + } +} +function getSuiteHooks(suite, name, sequence) { + const hooks = getHooks(suite)[name]; + if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) + return hooks.slice().reverse(); + return hooks; +} +async function callSuiteHook(suite, currentTask, name, runner, args) { + const sequence = runner.config.sequence.hooks; + const callbacks = []; + if (name === "beforeEach" && suite.suite) { + callbacks.push( + ...await callSuiteHook(suite.suite, currentTask, name, runner, args) + ); + } + updateSuiteHookState(currentTask, name, "run", runner); + const hooks = getSuiteHooks(suite, name, sequence); + if (sequence === "parallel") { + callbacks.push(...await Promise.all(hooks.map((fn) => fn(...args)))); + } else { + for (const hook of hooks) + callbacks.push(await hook(...args)); + } + updateSuiteHookState(currentTask, name, "pass", runner); + if (name === "afterEach" && suite.suite) { + callbacks.push( + ...await callSuiteHook(suite.suite, currentTask, name, runner, args) + ); + } + return callbacks; +} +const packs = /* @__PURE__ */ new Map(); +let updateTimer; +let previousUpdate; +function updateTask(task, runner) { + packs.set(task.id, [task.result, task.meta]); + const { clearTimeout, setTimeout } = getSafeTimers(); + clearTimeout(updateTimer); + updateTimer = setTimeout(() => { + previousUpdate = sendTasksUpdate(runner); + }, 10); +} +async function sendTasksUpdate(runner) { + var _a; + const { clearTimeout } = getSafeTimers(); + clearTimeout(updateTimer); + await previousUpdate; + if (packs.size) { + const taskPacks = Array.from(packs).map(([id, task]) => { + return [ + id, + task[0], + task[1] + ]; + }); + const p = (_a = runner.onTaskUpdate) == null ? void 0 : _a.call(runner, taskPacks); + packs.clear(); + return p; + } +} +async function callCleanupHooks(cleanups) { + await Promise.all(cleanups.map(async (fn) => { + if (typeof fn !== "function") + return; + await fn(); + })); +} +async function runTest(test, runner) { + var _a, _b, _c, _d, _e, _f, _g, _h; + await ((_a = runner.onBeforeRunTask) == null ? void 0 : _a.call(runner, test)); + if (test.mode !== "run") + return; + if (((_b = test.result) == null ? void 0 : _b.state) === "fail") { + updateTask(test, runner); + return; + } + const start = now(); + test.result = { + state: "run", + startTime: start, + retryCount: 0 + }; + updateTask(test, runner); + setCurrentTest(test); + const repeats = test.repeats ?? 0; + for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) { + const retry = test.retry ?? 0; + for (let retryCount = 0; retryCount <= retry; retryCount++) { + let beforeEachCleanups = []; + try { + await ((_c = runner.onBeforeTryTask) == null ? void 0 : _c.call(runner, test, { retry: retryCount, repeats: repeatCount })); + test.result.repeatCount = repeatCount; + beforeEachCleanups = await callSuiteHook(test.suite, test, "beforeEach", runner, [test.context, test.suite]); + if (runner.runTask) { + await runner.runTask(test); + } else { + const fn = getFn(test); + if (!fn) + throw new Error("Test function is not found. Did you add it using `setFn`?"); + await fn(); + } + if (test.promises) { + const result = await Promise.allSettled(test.promises); + const errors = result.map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean); + if (errors.length) + throw errors; + } + await ((_d = runner.onAfterTryTask) == null ? void 0 : _d.call(runner, test, { retry: retryCount, repeats: repeatCount })); + if (test.result.state !== "fail") { + if (!test.repeats) + test.result.state = "pass"; + else if (test.repeats && retry === retryCount) + test.result.state = "pass"; + } + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + if (test.pending || ((_e = test.result) == null ? void 0 : _e.state) === "skip") { + test.mode = "skip"; + test.result = { state: "skip" }; + updateTask(test, runner); + setCurrentTest(void 0); + return; + } + try { + await callSuiteHook(test.suite, test, "afterEach", runner, [test.context, test.suite]); + await callCleanupHooks(beforeEachCleanups); + await callFixtureCleanup(test.context); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + if (test.result.state === "pass") + break; + if (retryCount < retry) { + test.result.state = "run"; + test.result.retryCount = (test.result.retryCount ?? 0) + 1; + } + updateTask(test, runner); + } + } + try { + await Promise.all(((_f = test.onFinished) == null ? void 0 : _f.map((fn) => fn(test.result))) || []); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + if (test.result.state === "fail") { + try { + await Promise.all(((_g = test.onFailed) == null ? void 0 : _g.map((fn) => fn(test.result))) || []); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + } + if (test.fails) { + if (test.result.state === "pass") { + const error = processError(new Error("Expect test to fail")); + test.result.state = "fail"; + test.result.errors = [error]; + } else { + test.result.state = "pass"; + test.result.errors = void 0; + } + } + setCurrentTest(void 0); + test.result.duration = now() - start; + await ((_h = runner.onAfterRunTask) == null ? void 0 : _h.call(runner, test)); + updateTask(test, runner); +} +function failTask(result, err, diffOptions) { + if (err instanceof PendingError) { + result.state = "skip"; + return; + } + result.state = "fail"; + const errors = Array.isArray(err) ? err : [err]; + for (const e of errors) { + const error = processError(e, diffOptions); + result.errors ?? (result.errors = []); + result.errors.push(error); + } +} +function markTasksAsSkipped(suite, runner) { + suite.tasks.forEach((t) => { + t.mode = "skip"; + t.result = { ...t.result, state: "skip" }; + updateTask(t, runner); + if (t.type === "suite") + markTasksAsSkipped(t, runner); + }); +} +async function runSuite(suite, runner) { + var _a, _b, _c, _d; + await ((_a = runner.onBeforeRunSuite) == null ? void 0 : _a.call(runner, suite)); + if (((_b = suite.result) == null ? void 0 : _b.state) === "fail") { + markTasksAsSkipped(suite, runner); + updateTask(suite, runner); + return; + } + const start = now(); + suite.result = { + state: "run", + startTime: start + }; + updateTask(suite, runner); + let beforeAllCleanups = []; + if (suite.mode === "skip") { + suite.result.state = "skip"; + } else if (suite.mode === "todo") { + suite.result.state = "todo"; + } else { + try { + beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", runner, [suite]); + if (runner.runSuite) { + await runner.runSuite(suite); + } else { + for (let tasksGroup of partitionSuiteChildren(suite)) { + if (tasksGroup[0].concurrent === true) { + const mutex = limit(runner.config.maxConcurrency); + await Promise.all(tasksGroup.map((c) => mutex(() => runSuiteChild(c, runner)))); + } else { + const { sequence } = runner.config; + if (sequence.shuffle || suite.shuffle) { + const suites = tasksGroup.filter((group) => group.type === "suite"); + const tests = tasksGroup.filter((group) => group.type === "test"); + const groups = shuffle([suites, tests], sequence.seed); + tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed)); + } + for (const c of tasksGroup) + await runSuiteChild(c, runner); + } + } + } + } catch (e) { + failTask(suite.result, e, runner.config.diffOptions); + } + try { + await callSuiteHook(suite, suite, "afterAll", runner, [suite]); + await callCleanupHooks(beforeAllCleanups); + } catch (e) { + failTask(suite.result, e, runner.config.diffOptions); + } + if (suite.mode === "run") { + if (!runner.config.passWithNoTests && !hasTests(suite)) { + suite.result.state = "fail"; + if (!((_c = suite.result.errors) == null ? void 0 : _c.length)) { + const error = processError(new Error(`No test found in suite ${suite.name}`)); + suite.result.errors = [error]; + } + } else if (hasFailed(suite)) { + suite.result.state = "fail"; + } else { + suite.result.state = "pass"; + } + } + updateTask(suite, runner); + suite.result.duration = now() - start; + await ((_d = runner.onAfterRunSuite) == null ? void 0 : _d.call(runner, suite)); + } +} +async function runSuiteChild(c, runner) { + if (c.type === "test" || c.type === "custom") + return runTest(c, runner); + else if (c.type === "suite") + return runSuite(c, runner); +} +async function runFiles(files, runner) { + var _a, _b; + for (const file of files) { + if (!file.tasks.length && !runner.config.passWithNoTests) { + if (!((_b = (_a = file.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.length)) { + const error = processError(new Error(`No test suite found in file ${file.filepath}`)); + file.result = { + state: "fail", + errors: [error] + }; + } + } + await runSuite(file, runner); + } +} +async function startTests(paths, runner) { + var _a, _b, _c, _d; + await ((_a = runner.onBeforeCollect) == null ? void 0 : _a.call(runner, paths)); + const files = await collectTests(paths, runner); + (_b = runner.onCollected) == null ? void 0 : _b.call(runner, files); + await ((_c = runner.onBeforeRunFiles) == null ? void 0 : _c.call(runner, files)); + await runFiles(files, runner); + await ((_d = runner.onAfterRunFiles) == null ? void 0 : _d.call(runner, files)); + await sendTasksUpdate(runner); + return files; +} + +function getDefaultHookTimeout() { + return getRunner().config.hookTimeout; +} +function beforeAll(fn, timeout) { + return getCurrentSuite().on("beforeAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true)); +} +function afterAll(fn, timeout) { + return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true)); +} +function beforeEach(fn, timeout) { + return getCurrentSuite().on("beforeEach", withTimeout(withFixtures(fn), timeout ?? getDefaultHookTimeout(), true)); +} +function afterEach(fn, timeout) { + return getCurrentSuite().on("afterEach", withTimeout(withFixtures(fn), timeout ?? getDefaultHookTimeout(), true)); +} +const onTestFailed = createTestHook("onTestFailed", (test, handler) => { + test.onFailed || (test.onFailed = []); + test.onFailed.push(handler); +}); +const onTestFinished = createTestHook("onTestFinished", (test, handler) => { + test.onFinished || (test.onFinished = []); + test.onFinished.push(handler); +}); +function createTestHook(name, handler) { + return (fn) => { + const current = getCurrentTest(); + if (!current) + throw new Error(`Hook ${name}() can only be called inside a test`); + return handler(current, fn); + }; +} + +export { afterAll, afterEach, beforeAll, beforeEach, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/web/node_modules/@vitest/runner/dist/tasks-_kyNRBhz.d.ts b/web/node_modules/@vitest/runner/dist/tasks-_kyNRBhz.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e65c2329c4264b93c8af41f317e948780d1dbe7 --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/tasks-_kyNRBhz.d.ts @@ -0,0 +1,276 @@ +import { ErrorWithDiff, Awaitable } from '@vitest/utils'; + +type ChainableFunction any, C = {}> = F & { + [x in T]: ChainableFunction; +} & { + fn: (this: Record, ...args: Parameters) => ReturnType; +} & C; +declare function createChainable(keys: T[], fn: (this: Record, ...args: Args) => R): ChainableFunction R>; + +interface FixtureItem extends FixtureOptions { + prop: string; + value: any; + /** + * Indicates whether the fixture is a function + */ + isFn: boolean; + /** + * The dependencies(fixtures) of current fixture function. + */ + deps?: FixtureItem[]; +} + +type RunMode = 'run' | 'skip' | 'only' | 'todo'; +type TaskState = RunMode | 'pass' | 'fail'; +interface TaskBase { + id: string; + name: string; + mode: RunMode; + meta: TaskMeta; + each?: boolean; + concurrent?: boolean; + shuffle?: boolean; + suite?: Suite; + file?: File; + result?: TaskResult; + retry?: number; + repeats?: number; +} +interface TaskPopulated extends TaskBase { + suite: Suite; + pending?: boolean; + result?: TaskResult; + fails?: boolean; + onFailed?: OnTestFailedHandler[]; + onFinished?: OnTestFinishedHandler[]; + /** + * Store promises (from async expects) to wait for them before finishing the test + */ + promises?: Promise[]; +} +interface TaskMeta { +} +interface TaskResult { + state: TaskState; + duration?: number; + startTime?: number; + heap?: number; + errors?: ErrorWithDiff[]; + htmlError?: string; + hooks?: Partial>; + retryCount?: number; + repeatCount?: number; +} +type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta]; +interface Suite extends TaskBase { + type: 'suite'; + tasks: Task[]; + filepath?: string; + projectName: string; +} +interface File extends Suite { + filepath: string; + collectDuration?: number; + setupDuration?: number; +} +interface Test extends TaskPopulated { + type: 'test'; + context: TaskContext & ExtraContext & TestContext; +} +interface Custom extends TaskPopulated { + type: 'custom'; + context: TaskContext & ExtraContext & TestContext; +} +type Task = Test | Suite | Custom | File; +type DoneCallback = (error?: any) => void; +type TestFunction = (context: ExtendedContext & ExtraContext) => Awaitable | void; +type ExtractEachCallbackArgs> = { + 1: [T[0]]; + 2: [T[0], T[1]]; + 3: [T[0], T[1], T[2]]; + 4: [T[0], T[1], T[2], T[3]]; + 5: [T[0], T[1], T[2], T[3], T[4]]; + 6: [T[0], T[1], T[2], T[3], T[4], T[5]]; + 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]]; + 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]]; + 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]]; + 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]]; + fallback: Array ? U : any>; +}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : 'fallback']; +interface EachFunctionReturn { + /** + * @deprecated Use options as the second argument instead + */ + (name: string | Function, fn: (...args: T) => Awaitable, options: TestOptions): void; + (name: string | Function, fn: (...args: T) => Awaitable, options?: number | TestOptions): void; + (name: string | Function, options: TestOptions, fn: (...args: T) => Awaitable): void; +} +interface TestEachFunction { + (cases: ReadonlyArray): EachFunctionReturn; + >(cases: ReadonlyArray): EachFunctionReturn>; + (cases: ReadonlyArray): EachFunctionReturn; + (...args: [TemplateStringsArray, ...any]): EachFunctionReturn; +} +interface TestCollectorCallable { + /** + * @deprecated Use options as the second argument instead + */ + (name: string | Function, fn: TestFunction, options: TestOptions): void; + (name: string | Function, fn?: TestFunction, options?: number | TestOptions): void; + (name: string | Function, options?: TestOptions, fn?: TestFunction): void; +} +type ChainableTestAPI = ChainableFunction<'concurrent' | 'sequential' | 'only' | 'skip' | 'todo' | 'fails', TestCollectorCallable, { + each: TestEachFunction; +}>; +interface TestOptions { + /** + * Test timeout. + */ + timeout?: number; + /** + * Times to retry the test if fails. Useful for making flaky tests more stable. + * When retries is up, the last test error will be thrown. + * + * @default 0 + */ + retry?: number; + /** + * How many times the test will run. + * Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default. + * + * @default 0 + */ + repeats?: number; + /** + * Whether tests run concurrently. + * Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`. + */ + concurrent?: boolean; + /** + * Whether tests run sequentially. + * Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`. + */ + sequential?: boolean; + /** + * Whether the test should be skipped. + */ + skip?: boolean; + /** + * Should this test be the only one running in a suite. + */ + only?: boolean; + /** + * Whether the test should be skipped and marked as a todo. + */ + todo?: boolean; + /** + * Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail. + */ + fails?: boolean; +} +interface ExtendedAPI { + skipIf: (condition: any) => ChainableTestAPI; + runIf: (condition: any) => ChainableTestAPI; +} +type CustomAPI = ChainableTestAPI & ExtendedAPI & { + extend: = {}>(fixtures: Fixtures) => CustomAPI<{ + [K in keyof T | keyof ExtraContext]: K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never; + }>; +}; +type TestAPI = ChainableTestAPI & ExtendedAPI & { + extend: = {}>(fixtures: Fixtures) => TestAPI<{ + [K in keyof T | keyof ExtraContext]: K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never; + }>; +}; +interface FixtureOptions { + /** + * Whether to automatically set up current fixture, even though it's not being used in tests. + */ + auto?: boolean; +} +type Use = (value: T) => Promise; +type FixtureFn = (context: Omit & ExtraContext, use: Use) => Promise; +type Fixture = ((...args: any) => any) extends T[K] ? (T[K] extends any ? FixtureFn>> : never) : T[K] | (T[K] extends any ? FixtureFn>> : never); +type Fixtures, ExtraContext = {}> = { + [K in keyof T]: Fixture> | [Fixture>, FixtureOptions?]; +}; +type InferFixturesTypes = T extends TestAPI ? C : T; +interface SuiteCollectorCallable { + /** + * @deprecated Use options as the second argument instead + */ + (name: string | Function, fn: SuiteFactory, options: TestOptions): SuiteCollector; + (name: string | Function, fn?: SuiteFactory, options?: number | TestOptions): SuiteCollector; + (name: string | Function, options: TestOptions, fn?: SuiteFactory): SuiteCollector; +} +type ChainableSuiteAPI = ChainableFunction<'concurrent' | 'sequential' | 'only' | 'skip' | 'todo' | 'shuffle', SuiteCollectorCallable, { + each: TestEachFunction; +}>; +type SuiteAPI = ChainableSuiteAPI & { + skipIf: (condition: any) => ChainableSuiteAPI; + runIf: (condition: any) => ChainableSuiteAPI; +}; +type HookListener = (...args: T) => Awaitable; +type HookCleanupCallback = (() => Awaitable) | void; +interface SuiteHooks { + beforeAll: HookListener<[Readonly], HookCleanupCallback>[]; + afterAll: HookListener<[Readonly]>[]; + beforeEach: HookListener<[ExtendedContext & ExtraContext, Readonly], HookCleanupCallback>[]; + afterEach: HookListener<[ExtendedContext & ExtraContext, Readonly]>[]; +} +interface TaskCustomOptions extends TestOptions { + concurrent?: boolean; + sequential?: boolean; + skip?: boolean; + only?: boolean; + todo?: boolean; + fails?: boolean; + each?: boolean; + meta?: Record; + fixtures?: FixtureItem[]; + handler?: (context: TaskContext) => Awaitable; +} +interface SuiteCollector { + readonly name: string; + readonly mode: RunMode; + options?: TestOptions; + type: 'collector'; + test: TestAPI; + tasks: (Suite | Custom | Test | SuiteCollector)[]; + task: (name: string, options?: TaskCustomOptions) => Custom; + collect: (file?: File) => Promise; + clear: () => void; + on: >(name: T, ...fn: SuiteHooks[T]) => void; +} +type SuiteFactory = (test: (name: string | Function, fn: TestFunction) => void) => Awaitable; +interface RuntimeContext { + tasks: (SuiteCollector | Test)[]; + currentSuite: SuiteCollector | null; +} +interface TestContext { +} +interface TaskContext { + /** + * Metadata of the current test + */ + task: Readonly; + /** + * Extract hooks on test failed + */ + onTestFailed: (fn: OnTestFailedHandler) => void; + /** + * Extract hooks on test failed + */ + onTestFinished: (fn: OnTestFinishedHandler) => void; + /** + * Mark tests as skipped. All execution after this call will be skipped. + */ + skip: () => void; +} +type ExtendedContext = TaskContext & TestContext; +type OnTestFailedHandler = (result: TaskResult) => Awaitable; +type OnTestFinishedHandler = (result: TaskResult) => Awaitable; +type SequenceHooks = 'stack' | 'list' | 'parallel'; +type SequenceSetupFiles = 'list' | 'parallel'; + +export { type TaskContext as A, type SequenceHooks as B, type Custom as C, type DoneCallback as D, type ExtendedContext as E, type File as F, type SequenceSetupFiles as G, type HookListener as H, type InferFixturesTypes as I, type OnTestFailedHandler as O, type RunMode as R, type Suite as S, type Task as T, type Use as U, type Test as a, type ChainableFunction as b, createChainable as c, type SuiteAPI as d, type TestAPI as e, type SuiteCollector as f, type CustomAPI as g, type SuiteHooks as h, type OnTestFinishedHandler as i, type TaskState as j, type TaskBase as k, type TaskPopulated as l, type TaskMeta as m, type TaskResult as n, type TaskResultPack as o, type TestFunction as p, type TestOptions as q, type FixtureOptions as r, type FixtureFn as s, type Fixture as t, type Fixtures as u, type HookCleanupCallback as v, type TaskCustomOptions as w, type SuiteFactory as x, type RuntimeContext as y, type TestContext as z }; diff --git a/web/node_modules/@vitest/runner/dist/types.d.ts b/web/node_modules/@vitest/runner/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3301b34dc76e58904ac5a790e51c8d157efe388 --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/types.d.ts @@ -0,0 +1,120 @@ +import { B as SequenceHooks, G as SequenceSetupFiles, F as File, T as Task, S as Suite, o as TaskResultPack, a as Test, C as Custom, A as TaskContext, E as ExtendedContext } from './tasks-_kyNRBhz.js'; +export { g as CustomAPI, D as DoneCallback, t as Fixture, s as FixtureFn, r as FixtureOptions, u as Fixtures, v as HookCleanupCallback, H as HookListener, I as InferFixturesTypes, O as OnTestFailedHandler, i as OnTestFinishedHandler, R as RunMode, y as RuntimeContext, d as SuiteAPI, f as SuiteCollector, x as SuiteFactory, h as SuiteHooks, k as TaskBase, w as TaskCustomOptions, m as TaskMeta, l as TaskPopulated, n as TaskResult, j as TaskState, e as TestAPI, z as TestContext, p as TestFunction, q as TestOptions, U as Use } from './tasks-_kyNRBhz.js'; +import { DiffOptions } from '@vitest/utils/diff'; +import '@vitest/utils'; + +interface VitestRunnerConfig { + root: string; + setupFiles: string[] | string; + name: string; + passWithNoTests: boolean; + testNamePattern?: RegExp; + allowOnly?: boolean; + sequence: { + shuffle?: boolean; + concurrent?: boolean; + seed: number; + hooks: SequenceHooks; + setupFiles: SequenceSetupFiles; + }; + chaiConfig?: { + truncateThreshold?: number; + }; + maxConcurrency: number; + testTimeout: number; + hookTimeout: number; + retry: number; + diffOptions?: DiffOptions; +} +type VitestRunnerImportSource = 'collect' | 'setup'; +interface VitestRunnerConstructor { + new (config: VitestRunnerConfig): VitestRunner; +} +type CancelReason = 'keyboard-input' | 'test-failure' | string & Record; +interface VitestRunner { + /** + * First thing that's getting called before actually collecting and running tests. + */ + onBeforeCollect?: (paths: string[]) => unknown; + /** + * Called after collecting tests and before "onBeforeRun". + */ + onCollected?: (files: File[]) => unknown; + /** + * Called when test runner should cancel next test runs. + * Runner should listen for this method and mark tests and suites as skipped in + * "onBeforeRunSuite" and "onBeforeRunTask" when called. + */ + onCancel?: (reason: CancelReason) => unknown; + /** + * Called before running a single test. Doesn't have "result" yet. + */ + onBeforeRunTask?: (test: Task) => unknown; + /** + * Called before actually running the test function. Already has "result" with "state" and "startTime". + */ + onBeforeTryTask?: (test: Task, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * Called after result and state are set. + */ + onAfterRunTask?: (test: Task) => unknown; + /** + * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws. + */ + onAfterTryTask?: (test: Task, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * Called before running a single suite. Doesn't have "result" yet. + */ + onBeforeRunSuite?: (suite: Suite) => unknown; + /** + * Called after running a single suite. Has state and result. + */ + onAfterRunSuite?: (suite: Suite) => unknown; + /** + * If defined, will be called instead of usual Vitest suite partition and handling. + * "before" and "after" hooks will not be ignored. + */ + runSuite?: (suite: Suite) => Promise; + /** + * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function. + * "before" and "after" hooks will not be ignored. + */ + runTask?: (test: Task) => Promise; + /** + * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests. + */ + onTaskUpdate?: (task: TaskResultPack[]) => Promise; + /** + * Called before running all tests in collected paths. + */ + onBeforeRunFiles?: (files: File[]) => unknown; + /** + * Called right after running all tests in collected paths. + */ + onAfterRunFiles?: (files: File[]) => unknown; + /** + * Called when new context for a test is defined. Useful, if you want to add custom properties to the context. + * If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead. + * + * This method is called for both "test" and "custom" handlers. + * + * @see https://vitest.dev/advanced/runner.html#your-task-function + */ + extendTaskContext?: (context: TaskContext) => ExtendedContext; + /** + * Called, when files are imported. Can be called in two situations: when collecting tests and when importing setup files. + */ + importFile: (filepath: string, source: VitestRunnerImportSource) => unknown; + /** + * Publicly available configuration. + */ + config: VitestRunnerConfig; +} + +export { type CancelReason, Custom, ExtendedContext, File, SequenceHooks, SequenceSetupFiles, Suite, Task, TaskContext, TaskResultPack, Test, type VitestRunner, type VitestRunnerConfig, type VitestRunnerConstructor, type VitestRunnerImportSource }; diff --git a/web/node_modules/@vitest/runner/dist/types.js b/web/node_modules/@vitest/runner/dist/types.js new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/types.js @@ -0,0 +1 @@ + diff --git a/web/node_modules/@vitest/runner/dist/utils.d.ts b/web/node_modules/@vitest/runner/dist/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6aca15bdf5c7dd796bd1cfe16f6ba47563b24dd2 --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/utils.d.ts @@ -0,0 +1,25 @@ +import { S as Suite, T as Task, a as Test, C as Custom } from './tasks-_kyNRBhz.js'; +export { b as ChainableFunction, c as createChainable } from './tasks-_kyNRBhz.js'; +import { Arrayable } from '@vitest/utils'; + +/** + * If any tasks been marked as `only`, mark all other tasks as `skip`. + */ +declare function interpretTaskModes(suite: Suite, namePattern?: string | RegExp, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void; +declare function someTasksAreOnly(suite: Suite): boolean; +declare function generateHash(str: string): string; +declare function calculateSuiteHash(parent: Suite): void; + +/** + * Partition in tasks groups by consecutive concurrent + */ +declare function partitionSuiteChildren(suite: Suite): Task[][]; + +declare function getTests(suite: Arrayable): (Test | Custom)[]; +declare function getTasks(tasks?: Arrayable): Task[]; +declare function getSuites(suite: Arrayable): Suite[]; +declare function hasTests(suite: Arrayable): boolean; +declare function hasFailed(suite: Arrayable): boolean; +declare function getNames(task: Task): string[]; + +export { calculateSuiteHash, generateHash, getNames, getSuites, getTasks, getTests, hasFailed, hasTests, interpretTaskModes, partitionSuiteChildren, someTasksAreOnly }; diff --git a/web/node_modules/@vitest/runner/dist/utils.js b/web/node_modules/@vitest/runner/dist/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..c326e818dca6276f45a2044b9d15a83636ebb39e --- /dev/null +++ b/web/node_modules/@vitest/runner/dist/utils.js @@ -0,0 +1,3 @@ +export { c as calculateSuiteHash, j as createChainable, g as generateHash, f as getNames, d as getSuites, b as getTasks, a as getTests, e as hasFailed, h as hasTests, i as interpretTaskModes, p as partitionSuiteChildren, s as someTasksAreOnly } from './chunk-tasks.js'; +import '@vitest/utils/error'; +import '@vitest/utils'; diff --git a/web/node_modules/@vitest/runner/package.json b/web/node_modules/@vitest/runner/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a031b5a15fbffa7abb556a2849f94f9ccf4e88e6 --- /dev/null +++ b/web/node_modules/@vitest/runner/package.json @@ -0,0 +1,49 @@ +{ + "name": "@vitest/runner", + "type": "module", + "version": "1.3.1", + "description": "Vitest test runner", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/runner#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/runner" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": true, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "default": "./dist/utils.js" + }, + "./types": { + "types": "./dist/types.d.ts", + "default": "./dist/types.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "p-limit": "^5.0.0", + "pathe": "^1.1.1", + "@vitest/utils": "1.3.1" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/web/node_modules/@vitest/runner/types.d.ts b/web/node_modules/@vitest/runner/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..26a125423d414fa445c87ab4621e8e3286a7875b --- /dev/null +++ b/web/node_modules/@vitest/runner/types.d.ts @@ -0,0 +1 @@ +export * from './dist/types.js' diff --git a/web/node_modules/@vitest/runner/utils.d.ts b/web/node_modules/@vitest/runner/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3f344e48a8d345df0c9350f51033c85f0e3a3a1 --- /dev/null +++ b/web/node_modules/@vitest/runner/utils.d.ts @@ -0,0 +1 @@ +export * from './dist/utils.js' diff --git a/web/node_modules/@vitest/snapshot/LICENSE b/web/node_modules/@vitest/snapshot/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ae481fdb8ea5d7ab1dac9e5138d77cd80fbfb8c --- /dev/null +++ b/web/node_modules/@vitest/snapshot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present Vitest Team + +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/web/node_modules/@vitest/snapshot/README.md b/web/node_modules/@vitest/snapshot/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c4ecda2260bc37b18e64dbcf1b6ee3771af9280 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/README.md @@ -0,0 +1,79 @@ +# @vitest/snapshot + +Lightweight implementation of Jest's snapshots. + +## Usage + +```js +import { SnapshotClient } from '@vitest/snapshot' +import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment' +import { SnapshotManager } from '@vitest/snapshot/manager' + +const client = new SnapshotClient({ + // you need to provide your own equality check implementation if you use it + // this function is called when `.toMatchSnapshot({ property: 1 })` is called + isEqual: (received, expected) => equals(received, expected, [iterableEquality, subsetEquality]), +}) + +// class that implements snapshot saving and reading +// by default uses fs module, but you can provide your own implementation depending on the environment +const environment = new NodeSnapshotEnvironment() + +// you need to implement this yourselves, +// this depends on your runner +function getCurrentFilepath() { + return '/file.spec.js' +} +function getCurrentTestName() { + return 'test1' +} + +// example for inline snapshots, nothing is required to support regular snapshots, +// just call `assert` with `isInline: false` +function wrapper(received) { + function __INLINE_SNAPSHOT__(inlineSnapshot, message) { + client.assert({ + received, + message, + isInline: true, + inlineSnapshot, + filepath: getCurrentFilepath(), + name: getCurrentTestName(), + }) + } + return { + // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2) + // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor + toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args), + } +} + +const options = { + updateSnapshot: 'new', + snapshotEnvironment: environment, +} + +await client.startCurrentRun(getCurrentFilepath(), getCurrentTestName(), options) + +// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" +client.assert({ + received: 'some text', + isInline: false, +}) + +// uses "pretty-format", so it requires quotes +// also naming is hard-coded when parsing test files +wrapper('text 1').toMatchInlineSnapshot() +wrapper('text 2').toMatchInlineSnapshot('"text 2"') + +const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult + +// you can use manager to manage several clients +const manager = new SnapshotManager(options) +manager.add(result) + +// do something +// and then read the summary + +console.log(manager.summary) +``` diff --git a/web/node_modules/@vitest/snapshot/dist/environment-cMiGIVXz.d.ts b/web/node_modules/@vitest/snapshot/dist/environment-cMiGIVXz.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b2d0125a06a014aac8c798041eeca2e3561be15 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/environment-cMiGIVXz.d.ts @@ -0,0 +1,14 @@ +interface SnapshotEnvironment { + getVersion: () => string; + getHeader: () => string; + resolvePath: (filepath: string) => Promise; + resolveRawPath: (testPath: string, rawPath: string) => Promise; + saveSnapshotFile: (filepath: string, snapshot: string) => Promise; + readSnapshotFile: (filepath: string) => Promise; + removeSnapshotFile: (filepath: string) => Promise; +} +interface SnapshotEnvironmentOptions { + snapshotsDirName?: string; +} + +export type { SnapshotEnvironment as S, SnapshotEnvironmentOptions as a }; diff --git a/web/node_modules/@vitest/snapshot/dist/environment.d.ts b/web/node_modules/@vitest/snapshot/dist/environment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27cc6b545582aa11fb6b96f02855c4e0a26f444b --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/environment.d.ts @@ -0,0 +1,16 @@ +import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment-cMiGIVXz.js'; + +declare class NodeSnapshotEnvironment implements SnapshotEnvironment { + private options; + constructor(options?: SnapshotEnvironmentOptions); + getVersion(): string; + getHeader(): string; + resolveRawPath(testPath: string, rawPath: string): Promise; + resolvePath(filepath: string): Promise; + prepareDirectory(dirPath: string): Promise; + saveSnapshotFile(filepath: string, snapshot: string): Promise; + readSnapshotFile(filepath: string): Promise; + removeSnapshotFile(filepath: string): Promise; +} + +export { NodeSnapshotEnvironment, SnapshotEnvironment }; diff --git a/web/node_modules/@vitest/snapshot/dist/environment.js b/web/node_modules/@vitest/snapshot/dist/environment.js new file mode 100644 index 0000000000000000000000000000000000000000..f6a95f4bcdcbb6a5560cfa7306fcc019f9324fb5 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/environment.js @@ -0,0 +1,44 @@ +import { promises, existsSync } from 'node:fs'; +import { isAbsolute, resolve, dirname, join, basename } from 'pathe'; + +class NodeSnapshotEnvironment { + constructor(options = {}) { + this.options = options; + } + getVersion() { + return "1"; + } + getHeader() { + return `// Snapshot v${this.getVersion()}`; + } + async resolveRawPath(testPath, rawPath) { + return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); + } + async resolvePath(filepath) { + return join( + join( + dirname(filepath), + this.options.snapshotsDirName ?? "__snapshots__" + ), + `${basename(filepath)}.snap` + ); + } + async prepareDirectory(dirPath) { + await promises.mkdir(dirPath, { recursive: true }); + } + async saveSnapshotFile(filepath, snapshot) { + await promises.mkdir(dirname(filepath), { recursive: true }); + await promises.writeFile(filepath, snapshot, "utf-8"); + } + async readSnapshotFile(filepath) { + if (!existsSync(filepath)) + return null; + return promises.readFile(filepath, "utf-8"); + } + async removeSnapshotFile(filepath) { + if (existsSync(filepath)) + await promises.unlink(filepath); + } +} + +export { NodeSnapshotEnvironment }; diff --git a/web/node_modules/@vitest/snapshot/dist/index-S94ASl6q.d.ts b/web/node_modules/@vitest/snapshot/dist/index-S94ASl6q.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7db06811e42cc52743ef9b747e2a26b8ff2cddde --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/index-S94ASl6q.d.ts @@ -0,0 +1,60 @@ +import { Plugin, OptionsReceived } from 'pretty-format'; +import { S as SnapshotEnvironment } from './environment-cMiGIVXz.js'; + +interface RawSnapshotInfo { + file: string; + readonly?: boolean; + content?: string; +} + +type SnapshotData = Record; +type SnapshotUpdateState = 'all' | 'new' | 'none'; +type SnapshotSerializer = Plugin; +interface SnapshotStateOptions { + updateSnapshot: SnapshotUpdateState; + snapshotEnvironment: SnapshotEnvironment; + expand?: boolean; + snapshotFormat?: OptionsReceived; + resolveSnapshotPath?: (path: string, extension: string) => string; +} +interface SnapshotMatchOptions { + testName: string; + received: unknown; + key?: string; + inlineSnapshot?: string; + isInline: boolean; + error?: Error; + rawSnapshot?: RawSnapshotInfo; +} +interface SnapshotResult { + filepath: string; + added: number; + fileDeleted: boolean; + matched: number; + unchecked: number; + uncheckedKeys: Array; + unmatched: number; + updated: number; +} +interface UncheckedSnapshot { + filePath: string; + keys: Array; +} +interface SnapshotSummary { + added: number; + didUpdate: boolean; + failure: boolean; + filesAdded: number; + filesRemoved: number; + filesRemovedList: Array; + filesUnmatched: number; + filesUpdated: number; + matched: number; + total: number; + unchecked: number; + uncheckedKeysByFile: Array; + unmatched: number; + updated: number; +} + +export type { RawSnapshotInfo as R, SnapshotStateOptions as S, UncheckedSnapshot as U, SnapshotMatchOptions as a, SnapshotResult as b, SnapshotData as c, SnapshotUpdateState as d, SnapshotSerializer as e, SnapshotSummary as f }; diff --git a/web/node_modules/@vitest/snapshot/dist/index.d.ts b/web/node_modules/@vitest/snapshot/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba78fd88f1856777442ce2e13ae88ac8d2144a8d --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/index.d.ts @@ -0,0 +1,109 @@ +import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './index-S94ASl6q.js'; +export { c as SnapshotData, e as SnapshotSerializer, f as SnapshotSummary, d as SnapshotUpdateState, U as UncheckedSnapshot } from './index-S94ASl6q.js'; +import { S as SnapshotEnvironment } from './environment-cMiGIVXz.js'; +import { Plugin, Plugins } from 'pretty-format'; + +interface ParsedStack { + method: string; + file: string; + line: number; + column: number; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +interface SnapshotReturnOptions { + actual: string; + count: number; + expected?: string; + key: string; + pass: boolean; +} +interface SaveStatus { + deleted: boolean; + saved: boolean; +} +declare class SnapshotState { + testFilePath: string; + snapshotPath: string; + private _counters; + private _dirty; + private _updateSnapshot; + private _snapshotData; + private _initialData; + private _inlineSnapshots; + private _rawSnapshots; + private _uncheckedKeys; + private _snapshotFormat; + private _environment; + private _fileExists; + added: number; + expand: boolean; + matched: number; + unmatched: number; + updated: number; + private constructor(); + static create(testFilePath: string, options: SnapshotStateOptions): Promise; + get environment(): SnapshotEnvironment; + markSnapshotsAsCheckedForTest(testName: string): void; + protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null; + private _addSnapshot; + clear(): void; + save(): Promise; + getUncheckedCount(): number; + getUncheckedKeys(): Array; + removeUncheckedKeys(): void; + match({ testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, }: SnapshotMatchOptions): SnapshotReturnOptions; + pack(): Promise; +} + +interface AssertOptions { + received: unknown; + filepath?: string; + name?: string; + message?: string; + isInline?: boolean; + properties?: object; + inlineSnapshot?: string; + error?: Error; + errorMessage?: string; + rawSnapshot?: RawSnapshotInfo; +} +interface SnapshotClientOptions { + isEqual?: (received: unknown, expected: unknown) => boolean; +} +declare class SnapshotClient { + private options; + filepath?: string; + name?: string; + snapshotState: SnapshotState | undefined; + snapshotStateMap: Map; + constructor(options?: SnapshotClientOptions); + startCurrentRun(filepath: string, name: string, options: SnapshotStateOptions): Promise; + getSnapshotState(filepath: string): SnapshotState; + clearTest(): void; + skipTestSnapshots(name: string): void; + assert(options: AssertOptions): void; + assertRaw(options: AssertOptions): Promise; + finishCurrentRun(): Promise; + clear(): void; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +declare function addSerializer(plugin: Plugin): void; +declare function getSerializers(): Plugins; + +declare function stripSnapshotIndentation(inlineSnapshot: string): string; + +export { SnapshotClient, SnapshotMatchOptions, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/web/node_modules/@vitest/snapshot/dist/index.js b/web/node_modules/@vitest/snapshot/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b1e61785dd845ab994a751bf2f69079062cbe30 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/index.js @@ -0,0 +1,1548 @@ +import { plugins, format } from 'pretty-format'; +import { resolve as resolve$2 } from 'pathe'; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var naturalCompare$2 = {exports: {}}; + +/* + * @version 1.4.0 + * @date 2015-10-26 + * @stability 3 - Stable + * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite) + * @license MIT License + */ + + +var naturalCompare = function(a, b) { + var i, codeA + , codeB = 1 + , posA = 0 + , posB = 0 + , alphabet = String.alphabet; + + function getCode(str, pos, code) { + if (code) { + for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i; + return +str.slice(pos - 1, i) + } + code = alphabet && alphabet.indexOf(str.charAt(pos)); + return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code + : code < 46 ? 65 // - + : code < 48 ? code - 1 + : code < 58 ? code + 18 // 0-9 + : code < 65 ? code - 11 + : code < 91 ? code + 11 // A-Z + : code < 97 ? code - 37 + : code < 123 ? code + 5 // a-z + : code - 63 + } + + + if ((a+="") != (b+="")) for (;codeB;) { + codeA = getCode(a, posA++); + codeB = getCode(b, posB++); + + if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) { + codeA = getCode(a, posA, posA); + codeB = getCode(b, posB, posA = i); + posB = i; + } + + if (codeA != codeB) return (codeA < codeB) ? -1 : 1 + } + return 0 +}; + +try { + naturalCompare$2.exports = naturalCompare; +} catch (e) { + String.naturalCompare = naturalCompare; +} + +var naturalCompareExports = naturalCompare$2.exports; +var naturalCompare$1 = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports); + +function notNullish(v) { + return v != null; +} +function isPrimitive(value) { + return value === null || typeof value !== "function" && typeof value !== "object"; +} +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} +function getCallLastIndex(code) { + let charIndex = -1; + let inString = null; + let startedBracers = 0; + let endedBracers = 0; + let beforeChar = null; + while (charIndex <= code.length) { + beforeChar = code[charIndex]; + charIndex++; + const char = code[charIndex]; + const isCharString = char === '"' || char === "'" || char === "`"; + if (isCharString && beforeChar !== "\\") { + if (inString === char) + inString = null; + else if (!inString) + inString = char; + } + if (!inString) { + if (char === "(") + startedBracers++; + if (char === ")") + endedBracers++; + } + if (startedBracers && endedBracers && startedBracers === endedBracers) + return charIndex; + } + return null; +} + +let getPromiseValue = () => 'Promise{…}'; +try { + const { getPromiseDetails, kPending, kRejected } = process.binding('util'); + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = (value, options) => { + const [state, innerValue] = getPromiseDetails(value); + if (state === kPending) { + return 'Promise{}' + } + return `Promise${state === kRejected ? '!' : ''}{${options.inspect(innerValue, options)}}` + }; + } +} catch (notNode) { + /* ignore */ +} + +/* ! + * loupe + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +let nodeInspect = false; +try { + // eslint-disable-next-line global-require + const nodeUtil = require('util'); + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; +} catch (noNodeInspect) { + nodeInspect = false; +} + +const lineSplitRE = /\r?\n/; +function positionToOffset(source, lineNumber, columnNumber) { + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let start = 0; + if (lineNumber > lines.length) + return source.length; + for (let i = 0; i < lineNumber - 1; i++) + start += lines[i].length + nl; + return start + columnNumber; +} +function offsetToLineNumber(source, offset) { + if (offset > source.length) { + throw new Error( + `offset is longer than source length! offset ${offset} > length ${source.length}` + ); + } + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let counted = 0; + let line = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + nl; + if (counted + lineLength >= offset) + break; + counted += lineLength; + } + return line + 1; +} + +// Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell +// License: MIT. +var LineTerminatorSequence; +LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; +RegExp(LineTerminatorSequence.source); + +// src/index.ts +var reservedWords = { + keyword: [ + "break", + "case", + "catch", + "continue", + "debugger", + "default", + "do", + "else", + "finally", + "for", + "function", + "if", + "return", + "switch", + "throw", + "try", + "var", + "const", + "while", + "with", + "new", + "this", + "super", + "class", + "extends", + "export", + "import", + "null", + "true", + "false", + "in", + "instanceof", + "typeof", + "void", + "delete" + ], + strict: [ + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield" + ] +}; new Set(reservedWords.keyword); new Set(reservedWords.strict); + +const serialize$1 = (val, config, indentation, depth, refs, printer) => { + const name = val.getMockName(); + const nameString = name === "vi.fn()" ? "" : ` ${name}`; + let callsString = ""; + if (val.mock.calls.length !== 0) { + const indentationNext = indentation + config.indent; + callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`; + } + return `[MockFunction${nameString}]${callsString}`; +}; +const test = (val) => val && !!val._isMockFunction; +const plugin = { serialize: serialize$1, test }; + +const { + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent, + AsymmetricMatcher +} = plugins; +let PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher, + plugin +]; +function addSerializer(plugin) { + PLUGINS = [plugin].concat(PLUGINS); +} +function getSerializers() { + return PLUGINS; +} + +function testNameToKey(testName, count) { + return `${testName} ${count}`; +} +function keyToTestName(key) { + if (!/ \d+$/.test(key)) + throw new Error("Snapshot keys must end with a number."); + return key.replace(/ \d+$/, ""); +} +function getSnapshotData(content, options) { + const update = options.updateSnapshot; + const data = /* @__PURE__ */ Object.create(null); + let snapshotContents = ""; + let dirty = false; + if (content != null) { + try { + snapshotContents = content; + const populate = new Function("exports", snapshotContents); + populate(data); + } catch { + } + } + const isInvalid = snapshotContents; + if ((update === "all" || update === "new") && isInvalid) + dirty = true; + return { data, dirty }; +} +function addExtraLineBreaks(string) { + return string.includes("\n") ? ` +${string} +` : string; +} +function removeExtraLineBreaks(string) { + return string.length > 2 && string.startsWith("\n") && string.endsWith("\n") ? string.slice(1, -1) : string; +} +const escapeRegex = true; +const printFunctionName = false; +function serialize(val, indent = 2, formatOverrides = {}) { + return normalizeNewlines( + format(val, { + escapeRegex, + indent, + plugins: getSerializers(), + printFunctionName, + ...formatOverrides + }) + ); +} +function escapeBacktickString(str) { + return str.replace(/`|\\|\${/g, "\\$&"); +} +function printBacktickString(str) { + return `\`${escapeBacktickString(str)}\``; +} +function normalizeNewlines(string) { + return string.replace(/\r\n|\r/g, "\n"); +} +async function saveSnapshotFile(environment, snapshotData, snapshotPath) { + const snapshots = Object.keys(snapshotData).sort(naturalCompare$1).map( + (key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};` + ); + const content = `${environment.getHeader()} + +${snapshots.join("\n\n")} +`; + const oldContent = await environment.readSnapshotFile(snapshotPath); + const skipWriting = oldContent != null && oldContent === content; + if (skipWriting) + return; + await environment.saveSnapshotFile( + snapshotPath, + content + ); +} +function prepareExpected(expected) { + function findStartIndent() { + var _a, _b; + const matchObject = /^( +)}\s+$/m.exec(expected || ""); + const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length; + if (objectIndent) + return objectIndent; + const matchText = /^\n( +)"/.exec(expected || ""); + return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0; + } + const startIndent = findStartIndent(); + let expectedTrimmed = expected == null ? void 0 : expected.trim(); + if (startIndent) { + expectedTrimmed = expectedTrimmed == null ? void 0 : expectedTrimmed.replace(new RegExp(`^${" ".repeat(startIndent)}`, "gm"), "").replace(/ +}$/, "}"); + } + return expectedTrimmed; +} +function deepMergeArray(target = [], source = []) { + const mergedOutput = Array.from(target); + source.forEach((sourceElement, index) => { + const targetElement = mergedOutput[index]; + if (Array.isArray(target[index])) { + mergedOutput[index] = deepMergeArray(target[index], sourceElement); + } else if (isObject(targetElement)) { + mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement); + } else { + mergedOutput[index] = sourceElement; + } + }); + return mergedOutput; +} +function deepMergeSnapshot(target, source) { + if (isObject(target) && isObject(source)) { + const mergedOutput = { ...target }; + Object.keys(source).forEach((key) => { + if (isObject(source[key]) && !source[key].$$typeof) { + if (!(key in target)) + Object.assign(mergedOutput, { [key]: source[key] }); + else + mergedOutput[key] = deepMergeSnapshot(target[key], source[key]); + } else if (Array.isArray(source[key])) { + mergedOutput[key] = deepMergeArray(target[key], source[key]); + } else { + Object.assign(mergedOutput, { [key]: source[key] }); + } + }); + return mergedOutput; + } else if (Array.isArray(target) && Array.isArray(source)) { + return deepMergeArray(target, source); + } + return target; +} + +const comma = ','.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; +} +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator$1); +} +function sortComparator$1(a, b) { + return a[0] - b[0]; +} + +// 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; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +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: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.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('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.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 <= UrlType.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$1(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.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 UrlType.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 UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.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 UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +function resolve(input, base) { + // The base 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 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$1(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +function maybeSort(mappings, owned) { + 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, 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]; +} + +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]); + * ``` + */ +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, + }; +} +/** + * 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. + */ +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) { + // 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)); +} + +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)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * 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. + */ +let originalPositionFor; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : 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; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + originalPositionFor = (map, { line, column, bias }) => { + 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, 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 OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} + +const CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code])?$/; +const stackIgnorePatterns = [ + "node:internal", + /\/packages\/\w+\/dist\//, + /\/@vitest\/\w+\/dist\//, + "/vitest/dist/", + "/vitest/src/", + "/vite-node/dist/", + "/vite-node/src/", + "/node_modules/chai/", + "/node_modules/tinypool/", + "/node_modules/tinyspy/", + "/deps/chai.js", + /__vitest_browser__/ +]; +function extractLocation(urlLike) { + if (!urlLike.includes(":")) + return [urlLike]; + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) + return [urlLike]; + let url = parts[1]; + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + url = urlObj.pathname; + } + if (url.startsWith("/@fs/")) { + url = url.slice(typeof process !== "undefined" && process.platform === "win32" ? 5 : 4); + } + return [url, parts[2] || void 0, parts[3] || void 0]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) + return null; + if (line.includes(" > eval")) + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + if (!line.includes("@") && !line.includes(":")) + return null; + const functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/; + const matches = line.match(functionNameRegex); + const functionName = matches && matches[1] ? matches[1] : void 0; + const [url, lineNumber, columnNumber] = extractLocation(line.replace(functionNameRegex, "")); + if (!url || !lineNumber || !columnNumber) + return null; + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) + return null; + if (line.includes("(eval ")) + line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); + let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); + const location = sanitizedLine.match(/ (\(.+\)$)/); + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? void 0 : url; + if (!file || !lineNumber || !columnNumber) + return null; + if (method.startsWith("async ")) + method = method.slice(6); + if (file.startsWith("file://")) + file = file.slice(7); + file = resolve$2(file); + if (method) + method = method.replace(/__vite_ssr_import_\d+__\./g, ""); + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseStacktrace(stack, options = {}) { + const { ignoreStackEntries = stackIgnorePatterns } = options; + let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); + if (ignoreStackEntries.length) + stacks = stacks.filter((stack2) => !ignoreStackEntries.some((p) => stack2.file.match(p))); + return stacks.map((stack2) => { + var _a; + const map = (_a = options.getSourceMap) == null ? void 0 : _a.call(options, stack2.file); + if (!map || typeof map !== "object" || !map.version) + return stack2; + const traceMap = new TraceMap(map); + const { line, column } = originalPositionFor(traceMap, stack2); + if (line != null && column != null) + return { ...stack2, line, column }; + return stack2; + }); +} +function parseFFOrSafariStackTrace(stack) { + return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); +} +function parseV8Stacktrace(stack) { + return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); +} +function parseErrorStacktrace(e, options = {}) { + if (!e || isPrimitive(e)) + return []; + if (e.stacks) + return e.stacks; + const stackStr = e.stack || e.stackStr || ""; + let stackFrames = parseStacktrace(stackStr, options); + if (options.frameFilter) + stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); + e.stacks = stackFrames; + return stackFrames; +} + +async function saveInlineSnapshots(environment, snapshots) { + const MagicString = (await import('magic-string')).default; + const files = new Set(snapshots.map((i) => i.file)); + await Promise.all(Array.from(files).map(async (file) => { + const snaps = snapshots.filter((i) => i.file === file); + const code = await environment.readSnapshotFile(file); + const s = new MagicString(code); + for (const snap of snaps) { + const index = positionToOffset(code, snap.line, snap.column); + replaceInlineSnap(code, s, index, snap.snapshot); + } + const transformed = s.toString(); + if (transformed !== code) + await environment.saveSnapshotFile(file, transformed); + })); +} +const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*({)/m; +function replaceObjectSnap(code, s, index, newSnap) { + let _code = code.slice(index); + const startMatch = startObjectRegex.exec(_code); + if (!startMatch) + return false; + _code = _code.slice(startMatch.index); + let callEnd = getCallLastIndex(_code); + if (callEnd === null) + return false; + callEnd += index + startMatch.index; + const shapeStart = index + startMatch.index + startMatch[0].length; + const shapeEnd = getObjectShapeEndIndex(code, shapeStart); + const snap = `, ${prepareSnapString(newSnap, code, index)}`; + if (shapeEnd === callEnd) { + s.appendLeft(callEnd, snap); + } else { + s.overwrite(shapeEnd, callEnd, snap); + } + return true; +} +function getObjectShapeEndIndex(code, index) { + let startBraces = 1; + let endBraces = 0; + while (startBraces !== endBraces && index < code.length) { + const s = code[index++]; + if (s === "{") + startBraces++; + else if (s === "}") + endBraces++; + } + return index; +} +function prepareSnapString(snap, source, index) { + const lineNumber = offsetToLineNumber(source, index); + const line = source.split(lineSplitRE)[lineNumber - 1]; + const indent = line.match(/^\s*/)[0] || ""; + const indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `; + const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g); + const isOneline = lines.length <= 1; + const quote = "`"; + if (isOneline) + return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")}${quote}`; + return `${quote} +${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")} +${indent}${quote}`; +} +const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*[\w_$]*(['"`\)])/m; +function replaceInlineSnap(code, s, index, newSnap) { + const codeStartingAtIndex = code.slice(index); + const startMatch = startRegex.exec(codeStartingAtIndex); + const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(codeStartingAtIndex); + if (!startMatch || startMatch.index !== (firstKeywordMatch == null ? void 0 : firstKeywordMatch.index)) + return replaceObjectSnap(code, s, index, newSnap); + const quote = startMatch[1]; + const startIndex = index + startMatch.index + startMatch[0].length; + const snapString = prepareSnapString(newSnap, code, index); + if (quote === ")") { + s.appendRight(startIndex - 1, snapString); + return true; + } + const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`); + const endMatch = quoteEndRE.exec(code.slice(startIndex)); + if (!endMatch) + return false; + const endIndex = startIndex + endMatch.index + endMatch[0].length; + s.overwrite(startIndex - 1, endIndex, snapString); + return true; +} +const INDENTATION_REGEX = /^([^\S\n]*)\S/m; +function stripSnapshotIndentation(inlineSnapshot) { + const match = inlineSnapshot.match(INDENTATION_REGEX); + if (!match || !match[1]) { + return inlineSnapshot; + } + const indentation = match[1]; + const lines = inlineSnapshot.split(/\n/g); + if (lines.length <= 2) { + return inlineSnapshot; + } + if (lines[0].trim() !== "" || lines[lines.length - 1].trim() !== "") { + return inlineSnapshot; + } + for (let i = 1; i < lines.length - 1; i++) { + if (lines[i] !== "") { + if (lines[i].indexOf(indentation) !== 0) { + return inlineSnapshot; + } + lines[i] = lines[i].substring(indentation.length); + } + } + lines[lines.length - 1] = ""; + inlineSnapshot = lines.join("\n"); + return inlineSnapshot; +} + +async function saveRawSnapshots(environment, snapshots) { + await Promise.all(snapshots.map(async (snap) => { + if (!snap.readonly) + await environment.saveSnapshotFile(snap.file, snap.snapshot); + })); +} + +class SnapshotState { + constructor(testFilePath, snapshotPath, snapshotContent, options) { + this.testFilePath = testFilePath; + this.snapshotPath = snapshotPath; + const { data, dirty } = getSnapshotData( + snapshotContent, + options + ); + this._fileExists = snapshotContent != null; + this._initialData = data; + this._snapshotData = data; + this._dirty = dirty; + this._inlineSnapshots = []; + this._rawSnapshots = []; + this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); + this._counters = /* @__PURE__ */ new Map(); + this.expand = options.expand || false; + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this._updateSnapshot = options.updateSnapshot; + this.updated = 0; + this._snapshotFormat = { + printBasicPrototype: false, + escapeString: false, + ...options.snapshotFormat + }; + this._environment = options.snapshotEnvironment; + } + _counters; + _dirty; + _updateSnapshot; + _snapshotData; + _initialData; + _inlineSnapshots; + _rawSnapshots; + _uncheckedKeys; + _snapshotFormat; + _environment; + _fileExists; + added; + expand; + matched; + unmatched; + updated; + static async create(testFilePath, options) { + const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath); + const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath); + return new SnapshotState(testFilePath, snapshotPath, content, options); + } + get environment() { + return this._environment; + } + markSnapshotsAsCheckedForTest(testName) { + this._uncheckedKeys.forEach((uncheckedKey) => { + if (keyToTestName(uncheckedKey) === testName) + this._uncheckedKeys.delete(uncheckedKey); + }); + } + _inferInlineSnapshotStack(stacks) { + const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); + if (promiseIndex !== -1) + return stacks[promiseIndex + 3]; + const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__")); + return stackIndex !== -1 ? stacks[stackIndex + 2] : null; + } + _addSnapshot(key, receivedSerialized, options) { + this._dirty = true; + if (options.isInline) { + const stacks = parseErrorStacktrace(options.error || new Error("snapshot"), { ignoreStackEntries: [] }); + const stack = this._inferInlineSnapshotStack(stacks); + if (!stack) { + throw new Error( + `@vitest/snapshot: Couldn't infer stack frame for inline snapshot. +${JSON.stringify(stacks)}` + ); + } + stack.column--; + this._inlineSnapshots.push({ + snapshot: receivedSerialized, + ...stack + }); + } else if (options.rawSnapshot) { + this._rawSnapshots.push({ + ...options.rawSnapshot, + snapshot: receivedSerialized + }); + } else { + this._snapshotData[key] = receivedSerialized; + } + } + clear() { + this._snapshotData = this._initialData; + this._counters = /* @__PURE__ */ new Map(); + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this.updated = 0; + this._dirty = false; + } + async save() { + const hasExternalSnapshots = Object.keys(this._snapshotData).length; + const hasInlineSnapshots = this._inlineSnapshots.length; + const hasRawSnapshots = this._rawSnapshots.length; + const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots && !hasRawSnapshots; + const status = { + deleted: false, + saved: false + }; + if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { + if (hasExternalSnapshots) { + await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath); + this._fileExists = true; + } + if (hasInlineSnapshots) + await saveInlineSnapshots(this._environment, this._inlineSnapshots); + if (hasRawSnapshots) + await saveRawSnapshots(this._environment, this._rawSnapshots); + status.saved = true; + } else if (!hasExternalSnapshots && this._fileExists) { + if (this._updateSnapshot === "all") { + await this._environment.removeSnapshotFile(this.snapshotPath); + this._fileExists = false; + } + status.deleted = true; + } + return status; + } + getUncheckedCount() { + return this._uncheckedKeys.size || 0; + } + getUncheckedKeys() { + return Array.from(this._uncheckedKeys); + } + removeUncheckedKeys() { + if (this._updateSnapshot === "all" && this._uncheckedKeys.size) { + this._dirty = true; + this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]); + this._uncheckedKeys.clear(); + } + } + match({ + testName, + received, + key, + inlineSnapshot, + isInline, + error, + rawSnapshot + }) { + this._counters.set(testName, (this._counters.get(testName) || 0) + 1); + const count = Number(this._counters.get(testName)); + if (!key) + key = testNameToKey(testName, count); + if (!(isInline && this._snapshotData[key] !== void 0)) + this._uncheckedKeys.delete(key); + let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, void 0, this._snapshotFormat); + if (!rawSnapshot) + receivedSerialized = addExtraLineBreaks(receivedSerialized); + if (rawSnapshot) { + if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) + rawSnapshot.content = normalizeNewlines(rawSnapshot.content); + } + const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key]; + const expectedTrimmed = prepareExpected(expected); + const pass = expectedTrimmed === prepareExpected(receivedSerialized); + const hasSnapshot = expected !== void 0; + const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null; + if (pass && !isInline && !rawSnapshot) { + this._snapshotData[key] = receivedSerialized; + } + if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) { + if (this._updateSnapshot === "all") { + if (!pass) { + if (hasSnapshot) + this.updated++; + else + this.added++; + this._addSnapshot(key, receivedSerialized, { error, isInline, rawSnapshot }); + } else { + this.matched++; + } + } else { + this._addSnapshot(key, receivedSerialized, { error, isInline, rawSnapshot }); + this.added++; + } + return { + actual: "", + count, + expected: "", + key, + pass: true + }; + } else { + if (!pass) { + this.unmatched++; + return { + actual: removeExtraLineBreaks(receivedSerialized), + count, + expected: expectedTrimmed !== void 0 ? removeExtraLineBreaks(expectedTrimmed) : void 0, + key, + pass: false + }; + } else { + this.matched++; + return { + actual: "", + count, + expected: "", + key, + pass: true + }; + } + } + } + async pack() { + const snapshot = { + filepath: this.testFilePath, + added: 0, + fileDeleted: false, + matched: 0, + unchecked: 0, + uncheckedKeys: [], + unmatched: 0, + updated: 0 + }; + const uncheckedCount = this.getUncheckedCount(); + const uncheckedKeys = this.getUncheckedKeys(); + if (uncheckedCount) + this.removeUncheckedKeys(); + const status = await this.save(); + snapshot.fileDeleted = status.deleted; + snapshot.added = this.added; + snapshot.matched = this.matched; + snapshot.unmatched = this.unmatched; + snapshot.updated = this.updated; + snapshot.unchecked = !status.deleted ? uncheckedCount : 0; + snapshot.uncheckedKeys = Array.from(uncheckedKeys); + return snapshot; + } +} + +function createMismatchError(message, expand, actual, expected) { + const error = new Error(message); + Object.defineProperty(error, "actual", { + value: actual, + enumerable: true, + configurable: true, + writable: true + }); + Object.defineProperty(error, "expected", { + value: expected, + enumerable: true, + configurable: true, + writable: true + }); + Object.defineProperty(error, "diffOptions", { value: { expand } }); + return error; +} +class SnapshotClient { + constructor(options = {}) { + this.options = options; + } + filepath; + name; + snapshotState; + snapshotStateMap = /* @__PURE__ */ new Map(); + async startCurrentRun(filepath, name, options) { + var _a; + this.filepath = filepath; + this.name = name; + if (((_a = this.snapshotState) == null ? void 0 : _a.testFilePath) !== filepath) { + await this.finishCurrentRun(); + if (!this.getSnapshotState(filepath)) { + this.snapshotStateMap.set( + filepath, + await SnapshotState.create( + filepath, + options + ) + ); + } + this.snapshotState = this.getSnapshotState(filepath); + } + } + getSnapshotState(filepath) { + return this.snapshotStateMap.get(filepath); + } + clearTest() { + this.filepath = void 0; + this.name = void 0; + } + skipTestSnapshots(name) { + var _a; + (_a = this.snapshotState) == null ? void 0 : _a.markSnapshotsAsCheckedForTest(name); + } + assert(options) { + var _a, _b, _c, _d; + const { + filepath = this.filepath, + name = this.name, + message, + isInline = false, + properties, + inlineSnapshot, + error, + errorMessage, + rawSnapshot + } = options; + let { received } = options; + if (!filepath) + throw new Error("Snapshot cannot be used outside of test"); + if (typeof properties === "object") { + if (typeof received !== "object" || !received) + throw new Error("Received value must be an object when the matcher has properties"); + try { + const pass2 = ((_b = (_a = this.options).isEqual) == null ? void 0 : _b.call(_a, received, properties)) ?? false; + if (!pass2) + throw createMismatchError("Snapshot properties mismatched", (_c = this.snapshotState) == null ? void 0 : _c.expand, received, properties); + else + received = deepMergeSnapshot(received, properties); + } catch (err) { + err.message = errorMessage || "Snapshot mismatched"; + throw err; + } + } + const testName = [ + name, + ...message ? [message] : [] + ].join(" > "); + const snapshotState = this.getSnapshotState(filepath); + const { actual, expected, key, pass } = snapshotState.match({ + testName, + received, + isInline, + error, + inlineSnapshot, + rawSnapshot + }); + if (!pass) + throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, (_d = this.snapshotState) == null ? void 0 : _d.expand, actual == null ? void 0 : actual.trim(), expected == null ? void 0 : expected.trim()); + } + async assertRaw(options) { + if (!options.rawSnapshot) + throw new Error("Raw snapshot is required"); + const { + filepath = this.filepath, + rawSnapshot + } = options; + if (rawSnapshot.content == null) { + if (!filepath) + throw new Error("Snapshot cannot be used outside of test"); + const snapshotState = this.getSnapshotState(filepath); + options.filepath || (options.filepath = filepath); + rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file); + rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) || void 0; + } + return this.assert(options); + } + async finishCurrentRun() { + if (!this.snapshotState) + return null; + const result = await this.snapshotState.pack(); + this.snapshotState = void 0; + return result; + } + clear() { + this.snapshotStateMap.clear(); + } +} + +export { SnapshotClient, SnapshotState, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/web/node_modules/@vitest/snapshot/dist/manager.d.ts b/web/node_modules/@vitest/snapshot/dist/manager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8695e5def05bd0e8eb5b49fb8a5a5706e4dc728e --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/manager.d.ts @@ -0,0 +1,18 @@ +import { S as SnapshotStateOptions, f as SnapshotSummary, b as SnapshotResult } from './index-S94ASl6q.js'; +import 'pretty-format'; +import './environment-cMiGIVXz.js'; + +declare class SnapshotManager { + options: Omit; + summary: SnapshotSummary; + extension: string; + constructor(options: Omit); + clear(): void; + add(result: SnapshotResult): void; + resolvePath(testPath: string): string; + resolveRawPath(testPath: string, rawPath: string): string; +} +declare function emptySummary(options: Omit): SnapshotSummary; +declare function addSnapshotResult(summary: SnapshotSummary, result: SnapshotResult): void; + +export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/web/node_modules/@vitest/snapshot/dist/manager.js b/web/node_modules/@vitest/snapshot/dist/manager.js new file mode 100644 index 0000000000000000000000000000000000000000..21cc7ef45eb40cf878f8dd1dfc2aa30e627bbcda --- /dev/null +++ b/web/node_modules/@vitest/snapshot/dist/manager.js @@ -0,0 +1,75 @@ +import { join, dirname, basename, isAbsolute, resolve } from 'pathe'; + +class SnapshotManager { + constructor(options) { + this.options = options; + this.clear(); + } + summary = void 0; + extension = ".snap"; + clear() { + this.summary = emptySummary(this.options); + } + add(result) { + addSnapshotResult(this.summary, result); + } + resolvePath(testPath) { + const resolver = this.options.resolveSnapshotPath || (() => { + return join( + join( + dirname(testPath), + "__snapshots__" + ), + `${basename(testPath)}${this.extension}` + ); + }); + const path = resolver(testPath, this.extension); + return path; + } + resolveRawPath(testPath, rawPath) { + return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); + } +} +function emptySummary(options) { + const summary = { + added: 0, + failure: false, + filesAdded: 0, + filesRemoved: 0, + filesRemovedList: [], + filesUnmatched: 0, + filesUpdated: 0, + matched: 0, + total: 0, + unchecked: 0, + uncheckedKeysByFile: [], + unmatched: 0, + updated: 0, + didUpdate: options.updateSnapshot === "all" + }; + return summary; +} +function addSnapshotResult(summary, result) { + if (result.added) + summary.filesAdded++; + if (result.fileDeleted) + summary.filesRemoved++; + if (result.unmatched) + summary.filesUnmatched++; + if (result.updated) + summary.filesUpdated++; + summary.added += result.added; + summary.matched += result.matched; + summary.unchecked += result.unchecked; + if (result.uncheckedKeys && result.uncheckedKeys.length > 0) { + summary.uncheckedKeysByFile.push({ + filePath: result.filepath, + keys: result.uncheckedKeys + }); + } + summary.unmatched += result.unmatched; + summary.updated += result.updated; + summary.total += result.added + result.matched + result.unmatched + result.updated; +} + +export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/web/node_modules/@vitest/snapshot/environment.d.ts b/web/node_modules/@vitest/snapshot/environment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..855f0d10a8c55b2a80dc264d1b3b3677b3ee9094 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/environment.d.ts @@ -0,0 +1 @@ +export * from './dist/environment.js' diff --git a/web/node_modules/@vitest/snapshot/manager.d.ts b/web/node_modules/@vitest/snapshot/manager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3e80774b831684b8bfb08e7239407a84dceb955 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/manager.d.ts @@ -0,0 +1 @@ +export * from './dist/manager.js' diff --git a/web/node_modules/@vitest/snapshot/package.json b/web/node_modules/@vitest/snapshot/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5aaf0839c1ba85aab42e82ee1ce57e368c948874 --- /dev/null +++ b/web/node_modules/@vitest/snapshot/package.json @@ -0,0 +1,54 @@ +{ + "name": "@vitest/snapshot", + "type": "module", + "version": "1.3.1", + "description": "Vitest snapshot manager", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/snapshot#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/snapshot" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./environment": { + "types": "./dist/environment.d.ts", + "default": "./dist/environment.js" + }, + "./manager": { + "types": "./dist/manager.d.ts", + "default": "./dist/manager.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "magic-string": "^0.30.5", + "pathe": "^1.1.1", + "pretty-format": "^29.7.0" + }, + "devDependencies": { + "@types/natural-compare": "^1.4.3", + "natural-compare": "^1.4.0", + "@vitest/utils": "1.3.1" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/web/node_modules/@vitest/spy/LICENSE b/web/node_modules/@vitest/spy/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ae481fdb8ea5d7ab1dac9e5138d77cd80fbfb8c --- /dev/null +++ b/web/node_modules/@vitest/spy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present Vitest Team + +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/web/node_modules/@vitest/spy/README.md b/web/node_modules/@vitest/spy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5d23c876f4d74b84614797a858ebc29c81c81b9f --- /dev/null +++ b/web/node_modules/@vitest/spy/README.md @@ -0,0 +1,3 @@ +# @vitest/spy + +Lightweight Jest compatible spy implementation. diff --git a/web/node_modules/@vitest/spy/dist/index.d.ts b/web/node_modules/@vitest/spy/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e93f8f6e08e8c3a98a1e9e587e04959bd51fb49 --- /dev/null +++ b/web/node_modules/@vitest/spy/dist/index.d.ts @@ -0,0 +1,285 @@ +interface MockResultReturn { + type: 'return'; + /** + * The value that was returned from the function. If function returned a Promise, then this will be a resolved value. + */ + value: T; +} +interface MockResultIncomplete { + type: 'incomplete'; + value: undefined; +} +interface MockResultThrow { + type: 'throw'; + /** + * An error that was thrown during function execution. + */ + value: any; +} +type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; +interface MockContext { + /** + * This is an array containing all arguments for each call. One item of the array is the arguments of that call. + * + * @example + * const fn = vi.fn() + * + * fn('arg1', 'arg2') + * fn('arg3') + * + * fn.mock.calls === [ + * ['arg1', 'arg2'], // first call + * ['arg3'], // second call + * ] + */ + calls: TArgs[]; + /** + * This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value. + */ + instances: TReturns[]; + /** + * The order of mock's execution. This returns an array of numbers which are shared between all defined mocks. + * + * @example + * const fn1 = vi.fn() + * const fn2 = vi.fn() + * + * fn1() + * fn2() + * fn1() + * + * fn1.mock.invocationCallOrder === [1, 3] + * fn2.mock.invocationCallOrder === [2] + */ + invocationCallOrder: number[]; + /** + * This is an array containing all values that were `returned` from the function. + * + * The `value` property contains the returned value or thrown error. If the function returned a promise, the `value` will be the _resolved_ value, not the actual `Promise`, unless it was never resolved. + * + * @example + * const fn = vi.fn() + * .mockReturnValueOnce('result') + * .mockImplementationOnce(() => { throw new Error('thrown error') }) + * + * const result = fn() + * + * try { + * fn() + * } + * catch {} + * + * fn.mock.results === [ + * { + * type: 'return', + * value: 'result', + * }, + * { + * type: 'throw', + * value: Error, + * }, + * ] + */ + results: MockResult[]; + /** + * This contains the arguments of the last call. If spy wasn't called, will return `undefined`. + */ + lastCall: TArgs | undefined; +} +type Procedure = (...args: any[]) => any; +type Methods = keyof { + [K in keyof T as T[K] extends Procedure ? K : never]: T[K]; +}; +type Properties = { + [K in keyof T]: T[K] extends Procedure ? never : K; +}[keyof T] & (string | symbol); +type Classes = { + [K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never; +}[keyof T] & (string | symbol); +/** + * @deprecated Use MockInstance instead + */ +interface SpyInstance extends MockInstance { +} +interface MockInstance { + /** + * Use it to return the name given to mock with method `.mockName(name)`. + */ + getMockName: () => string; + /** + * Sets internal mock name. Useful to see the name of the mock if an assertion fails. + */ + mockName: (n: string) => this; + /** + * Current context of the mock. It stores information about all invocation calls, instances, and results. + */ + mock: MockContext; + /** + * Clears all information about every call. After calling it, all properties on `.mock` will return an empty state. This method does not reset implementations. + * + * It is useful if you need to clean up mock between different assertions. + */ + mockClear: () => this; + /** + * Does what `mockClear` does and makes inner implementation an empty function (returning `undefined` when invoked). This also resets all "once" implementations. + * + * This is useful when you want to completely reset a mock to the default state. + */ + mockReset: () => this; + /** + * Does what `mockReset` does and restores inner implementation to the original function. + * + * Note that restoring mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. Restoring a `vi.fn(impl)` will restore implementation to `impl`. + */ + mockRestore: () => void; + /** + * Returns current mock implementation if there is one. + * + * If mock was created with `vi.fn`, it will consider passed down method as a mock implementation. + * + * If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided. + */ + getMockImplementation: () => ((...args: TArgs) => TReturns) | undefined; + /** + * Accepts a function that will be used as an implementation of the mock. + * @example + * const increment = vi.fn().mockImplementation(count => count + 1); + * expect(increment(3)).toBe(4); + */ + mockImplementation: (fn: ((...args: TArgs) => TReturns)) => this; + /** + * Accepts a function that will be used as a mock implementation during the next call. Can be chained so that multiple function calls produce different results. + * @example + * const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1); + * expect(fn(3)).toBe(4); + * expect(fn(3)).toBe(3); + */ + mockImplementationOnce: (fn: ((...args: TArgs) => TReturns)) => this; + /** + * Overrides the original mock implementation temporarily while the callback is being executed. + * @example + * const myMockFn = vi.fn(() => 'original') + * + * myMockFn.withImplementation(() => 'temp', () => { + * myMockFn() // 'temp' + * }) + * + * myMockFn() // 'original' + */ + withImplementation: (fn: ((...args: TArgs) => TReturns), cb: () => T) => T extends Promise ? Promise : this; + /** + * Use this if you need to return `this` context from the method without invoking actual implementation. + */ + mockReturnThis: () => this; + /** + * Accepts a value that will be returned whenever the mock function is called. + */ + mockReturnValue: (obj: TReturns) => this; + /** + * Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value. + * + * When there are no more `mockReturnValueOnce` values to use, mock will fallback to the previously defined implementation if there is one. + * @example + * const myMockFn = vi + * .fn() + * .mockReturnValue('default') + * .mockReturnValueOnce('first call') + * .mockReturnValueOnce('second call') + * + * // 'first call', 'second call', 'default' + * console.log(myMockFn(), myMockFn(), myMockFn()) + */ + mockReturnValueOnce: (obj: TReturns) => this; + /** + * Accepts a value that will be resolved when async function is called. + * @example + * const asyncMock = vi.fn().mockResolvedValue(42) + * asyncMock() // Promise<42> + */ + mockResolvedValue: (obj: Awaited) => this; + /** + * Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve specified value. + * @example + * const myMockFn = vi + * .fn() + * .mockResolvedValue('default') + * .mockResolvedValueOnce('first call') + * .mockResolvedValueOnce('second call') + * + * // Promise<'first call'>, Promise<'second call'>, Promise<'default'> + * console.log(myMockFn(), myMockFn(), myMockFn()) + */ + mockResolvedValueOnce: (obj: Awaited) => this; + /** + * Accepts an error that will be rejected when async function is called. + * @example + * const asyncMock = vi.fn().mockRejectedValue(new Error('Async error')) + * await asyncMock() // throws 'Async error' + */ + mockRejectedValue: (obj: any) => this; + /** + * Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject specified value. + * @example + * const asyncMock = vi + * .fn() + * .mockResolvedValueOnce('first call') + * .mockRejectedValueOnce(new Error('Async error')) + * + * await asyncMock() // first call + * await asyncMock() // throws "Async error" + */ + mockRejectedValueOnce: (obj: any) => this; +} +interface Mock extends MockInstance { + new (...args: TArgs): TReturns; + (...args: TArgs): TReturns; +} +interface PartialMock extends MockInstance> ? Promise>> : Partial> { + new (...args: TArgs): TReturns; + (...args: TArgs): TReturns; +} +type MaybeMockedConstructor = T extends new (...args: Array) => infer R ? Mock, R> : T; +type MockedFunction = Mock, ReturnType> & { + [K in keyof T]: T[K]; +}; +type PartiallyMockedFunction = PartialMock, ReturnType> & { + [K in keyof T]: T[K]; +}; +type MockedFunctionDeep = Mock, ReturnType> & MockedObjectDeep; +type PartiallyMockedFunctionDeep = PartialMock, ReturnType> & MockedObjectDeep; +type MockedObject = MaybeMockedConstructor & { + [K in Methods]: T[K] extends Procedure ? MockedFunction : T[K]; +} & { + [K in Properties]: T[K]; +}; +type MockedObjectDeep = MaybeMockedConstructor & { + [K in Methods]: T[K] extends Procedure ? MockedFunctionDeep : T[K]; +} & { + [K in Properties]: MaybeMockedDeep; +}; +type MaybeMockedDeep = T extends Procedure ? MockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybePartiallyMockedDeep = T extends Procedure ? PartiallyMockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybeMocked = T extends Procedure ? MockedFunction : T extends object ? MockedObject : T; +type MaybePartiallyMocked = T extends Procedure ? PartiallyMockedFunction : T extends object ? MockedObject : T; +interface Constructable { + new (...args: any[]): any; +} +type MockedClass = MockInstance any ? P : never, InstanceType> & { + prototype: T extends { + prototype: any; + } ? Mocked : never; +} & T; +type Mocked = { + [P in keyof T]: T[P] extends (...args: infer Args) => infer Returns ? MockInstance : T[P] extends Constructable ? MockedClass : T[P]; +} & T; +declare const mocks: Set>; +declare function isMockFunction(fn: any): fn is MockInstance; +declare function spyOn>>(obj: T, methodName: S, accessType: 'get'): MockInstance<[], T[S]>; +declare function spyOn>>(obj: T, methodName: G, accessType: 'set'): MockInstance<[T[G]], void>; +declare function spyOn> | Methods>)>(obj: T, methodName: M): Required[M] extends ({ + new (...args: infer A): infer R; +}) | ((...args: infer A) => infer R) ? MockInstance : never; +declare function fn(): Mock; +declare function fn(implementation: (...args: TArgs) => R): Mock; + +export { type MaybeMocked, type MaybeMockedConstructor, type MaybeMockedDeep, type MaybePartiallyMocked, type MaybePartiallyMockedDeep, type Mock, type MockContext, type MockInstance, type Mocked, type MockedClass, type MockedFunction, type MockedFunctionDeep, type MockedObject, type MockedObjectDeep, type PartialMock, type PartiallyMockedFunction, type PartiallyMockedFunctionDeep, type SpyInstance, fn, isMockFunction, mocks, spyOn }; diff --git a/web/node_modules/@vitest/spy/dist/index.js b/web/node_modules/@vitest/spy/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9dc6378e95becacc6673c79dcf6b41502368a9e9 --- /dev/null +++ b/web/node_modules/@vitest/spy/dist/index.js @@ -0,0 +1,130 @@ +import * as tinyspy from 'tinyspy'; + +const mocks = /* @__PURE__ */ new Set(); +function isMockFunction(fn2) { + return typeof fn2 === "function" && "_isMockFunction" in fn2 && fn2._isMockFunction; +} +function spyOn(obj, method, accessType) { + const dictionary = { + get: "getter", + set: "setter" + }; + const objMethod = accessType ? { [dictionary[accessType]]: method } : method; + const stub = tinyspy.internalSpyOn(obj, objMethod); + return enhanceSpy(stub); +} +let callOrder = 0; +function enhanceSpy(spy) { + const stub = spy; + let implementation; + let instances = []; + let invocations = []; + const state = tinyspy.getInternalState(spy); + const mockContext = { + get calls() { + return state.calls; + }, + get instances() { + return instances; + }, + get invocationCallOrder() { + return invocations; + }, + get results() { + return state.results.map(([callType, value]) => { + const type = callType === "error" ? "throw" : "return"; + return { type, value }; + }); + }, + get lastCall() { + return state.calls[state.calls.length - 1]; + } + }; + let onceImplementations = []; + let implementationChangedTemporarily = false; + function mockCall(...args) { + instances.push(this); + invocations.push(++callOrder); + const impl = implementationChangedTemporarily ? implementation : onceImplementations.shift() || implementation || state.getOriginal() || (() => { + }); + return impl.apply(this, args); + } + let name = stub.name; + stub.getMockName = () => name || "vi.fn()"; + stub.mockName = (n) => { + name = n; + return stub; + }; + stub.mockClear = () => { + state.reset(); + instances = []; + invocations = []; + return stub; + }; + stub.mockReset = () => { + stub.mockClear(); + implementation = () => void 0; + onceImplementations = []; + return stub; + }; + stub.mockRestore = () => { + stub.mockReset(); + state.restore(); + implementation = void 0; + return stub; + }; + stub.getMockImplementation = () => implementation; + stub.mockImplementation = (fn2) => { + implementation = fn2; + state.willCall(mockCall); + return stub; + }; + stub.mockImplementationOnce = (fn2) => { + onceImplementations.push(fn2); + return stub; + }; + function withImplementation(fn2, cb) { + const originalImplementation = implementation; + implementation = fn2; + state.willCall(mockCall); + implementationChangedTemporarily = true; + const reset = () => { + implementation = originalImplementation; + implementationChangedTemporarily = false; + }; + const result = cb(); + if (result instanceof Promise) { + return result.then(() => { + reset(); + return stub; + }); + } + reset(); + return stub; + } + stub.withImplementation = withImplementation; + stub.mockReturnThis = () => stub.mockImplementation(function() { + return this; + }); + stub.mockReturnValue = (val) => stub.mockImplementation(() => val); + stub.mockReturnValueOnce = (val) => stub.mockImplementationOnce(() => val); + stub.mockResolvedValue = (val) => stub.mockImplementation(() => Promise.resolve(val)); + stub.mockResolvedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.resolve(val)); + stub.mockRejectedValue = (val) => stub.mockImplementation(() => Promise.reject(val)); + stub.mockRejectedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.reject(val)); + Object.defineProperty(stub, "mock", { + get: () => mockContext + }); + state.willCall(mockCall); + mocks.add(stub); + return stub; +} +function fn(implementation) { + const enhancedSpy = enhanceSpy(tinyspy.internalSpyOn({ spy: implementation || (() => { + }) }, "spy")); + if (implementation) + enhancedSpy.mockImplementation(implementation); + return enhancedSpy; +} + +export { fn, isMockFunction, mocks, spyOn }; diff --git a/web/node_modules/@vitest/spy/package.json b/web/node_modules/@vitest/spy/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5f008ffe21f5a9e5d31d3a348f061951f55de871 --- /dev/null +++ b/web/node_modules/@vitest/spy/package.json @@ -0,0 +1,38 @@ +{ + "name": "@vitest/spy", + "type": "module", + "version": "1.3.1", + "description": "Lightweight Jest compatible spy implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/spy#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/spy" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "dependencies": { + "tinyspy": "^2.2.0" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/web/node_modules/@vitest/utils/LICENSE b/web/node_modules/@vitest/utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ae481fdb8ea5d7ab1dac9e5138d77cd80fbfb8c --- /dev/null +++ b/web/node_modules/@vitest/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present Vitest Team + +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/web/node_modules/@vitest/utils/diff.d.ts b/web/node_modules/@vitest/utils/diff.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a66b86595c065228ede7e5adad789331f3efce0 --- /dev/null +++ b/web/node_modules/@vitest/utils/diff.d.ts @@ -0,0 +1 @@ +export * from './dist/diff.js' diff --git a/web/node_modules/@vitest/utils/dist/ast.d.ts b/web/node_modules/@vitest/utils/dist/ast.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..80e095a56349f8d033afccdcbb1ae33c77decb1e --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/ast.d.ts @@ -0,0 +1,723 @@ +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +type Node$1 = NodeMap[keyof NodeMap]; + +interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +interface BaseStatement extends BaseNode {} + +interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +interface BaseDeclaration extends BaseStatement {} + +interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const"; +} + +interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +type Expression = ExpressionMap[keyof ExpressionMap]; + +interface BaseExpression extends BaseNode {} + +type ChainElement = SimpleCallExpression | MemberExpression; + +interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression; + right: Expression; +} + +interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +type CallExpression = SimpleCallExpression | NewExpression; + +interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +interface BasePattern extends BaseNode {} + +interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +type LogicalOperator = "||" | "&&" | "??"; + +type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +type UpdateOperator = "++" | "--"; + +interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +interface Super extends BaseNode { + type: "Super"; +} + +interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +type Class = ClassDeclaration | ClassExpression; +interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +interface BaseModuleDeclaration extends BaseNode {} + +type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + source: Literal; +} + +interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier; +} + +interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; +} + +interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + source?: Literal | null | undefined; +} + +interface ExportSpecifier extends BaseModuleSpecifier { + type: "ExportSpecifier"; + exported: Identifier; +} + +interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | null; + source: Literal; +} + +interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} + +type Positioned = T & { + start: number; + end: number; +}; +type Node = Positioned; +interface IdentifierInfo { + /** + * If the identifier is used in a property shorthand + * { foo } -> { foo: __import_x__.foo } + */ + hasBindingShortcut: boolean; + /** + * The identifier is used in a class declaration + */ + classDeclaration: boolean; + /** + * The identifier is a name for a class expression + */ + classExpression: boolean; +} +interface Visitors { + onIdentifier?: (node: Positioned, info: IdentifierInfo, parentStack: Node[]) => void; + onImportMeta?: (node: Node) => void; + onDynamicImport?: (node: Positioned) => void; + onCallExpression?: (node: Positioned) => void; +} +declare function setIsNodeInPattern(node: Property): WeakSet; +declare function isNodeInPattern(node: Node$1): node is Property; +/** + * Same logic from \@vue/compiler-core & \@vue/compiler-sfc + * Except this is using acorn AST + */ +declare function esmWalker(root: Node, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }: Visitors): void; +declare function isStaticProperty(node: Node$1): node is Property; +declare function isStaticPropertyKey(node: Node$1, parent: Node$1): boolean; +declare function isFunctionNode(node: Node$1): node is Function; +declare function isInDestructuringAssignment(parent: Node$1, parentStack: Node$1[]): boolean; + +export { type ArrayExpression, type ArrayPattern, type ArrowFunctionExpression, type AssignmentExpression, type AssignmentOperator, type AssignmentPattern, type AssignmentProperty, type AwaitExpression, type BaseCallExpression, type BaseClass, type BaseDeclaration, type BaseExpression, type BaseForXStatement, type BaseFunction, type BaseModuleDeclaration, type BaseModuleSpecifier, type BaseNode, type BaseNodeWithoutComments, type BasePattern, type BaseStatement, type BigIntLiteral, type BinaryExpression, type BinaryOperator, type BlockStatement, type BreakStatement, type CallExpression, type CatchClause, type ChainElement, type ChainExpression, type Class, type ClassBody, type ClassDeclaration, type ClassExpression, type Comment, type ConditionalExpression, type ContinueStatement, type DebuggerStatement, type Declaration, type Directive, type DoWhileStatement, type EmptyStatement, type ExportAllDeclaration, type ExportDefaultDeclaration, type ExportNamedDeclaration, type ExportSpecifier, type Expression, type ExpressionMap, type ExpressionStatement, type ForInStatement, type ForOfStatement, type ForStatement, type Function, type FunctionDeclaration, type FunctionExpression, type Identifier, type IfStatement, type ImportDeclaration, type ImportDefaultSpecifier, type ImportExpression, type ImportNamespaceSpecifier, type ImportSpecifier, type LabeledStatement, type Literal, type LogicalExpression, type LogicalOperator, type MaybeNamedClassDeclaration, type MaybeNamedFunctionDeclaration, type MemberExpression, type MetaProperty, type MethodDefinition, type ModuleDeclaration, type ModuleSpecifier, type NewExpression, type Node, type NodeMap, type ObjectExpression, type ObjectPattern, type Pattern, type Position, type Positioned, type PrivateIdentifier, type Program, type Property, type PropertyDefinition, type RegExpLiteral, type RestElement, type ReturnStatement, type SequenceExpression, type SimpleCallExpression, type SimpleLiteral, type SourceLocation, type SpreadElement, type Statement, type StaticBlock, type Super, type SwitchCase, type SwitchStatement, type TaggedTemplateExpression, type TemplateElement, type TemplateLiteral, type ThisExpression, type ThrowStatement, type TryStatement, type UnaryExpression, type UnaryOperator, type UpdateExpression, type UpdateOperator, type VariableDeclaration, type VariableDeclarator, type WhileStatement, type WithStatement, type YieldExpression, esmWalker, isFunctionNode, isInDestructuringAssignment, isNodeInPattern, isStaticProperty, isStaticPropertyKey, setIsNodeInPattern }; diff --git a/web/node_modules/@vitest/utils/dist/ast.js b/web/node_modules/@vitest/utils/dist/ast.js new file mode 100644 index 0000000000000000000000000000000000000000..ad9f32f4cab07719945267a40647ea7ca1b850a5 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/ast.js @@ -0,0 +1,180 @@ +import { walk } from 'estree-walker'; + +const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet(); +function setIsNodeInPattern(node) { + return isNodeInPatternWeakSet.add(node); +} +function isNodeInPattern(node) { + return isNodeInPatternWeakSet.has(node); +} +function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) { + const parentStack = []; + const varKindStack = []; + const scopeMap = /* @__PURE__ */ new WeakMap(); + const identifiers = []; + const setScope = (node, name) => { + let scopeIds = scopeMap.get(node); + if (scopeIds && scopeIds.has(name)) + return; + if (!scopeIds) { + scopeIds = /* @__PURE__ */ new Set(); + scopeMap.set(node, scopeIds); + } + scopeIds.add(name); + }; + function isInScope(name, parents) { + return parents.some((node) => { + var _a; + return node && ((_a = scopeMap.get(node)) == null ? void 0 : _a.has(name)); + }); + } + function handlePattern(p, parentScope) { + if (p.type === "Identifier") { + setScope(parentScope, p.name); + } else if (p.type === "RestElement") { + handlePattern(p.argument, parentScope); + } else if (p.type === "ObjectPattern") { + p.properties.forEach((property) => { + if (property.type === "RestElement") + setScope(parentScope, property.argument.name); + else + handlePattern(property.value, parentScope); + }); + } else if (p.type === "ArrayPattern") { + p.elements.forEach((element) => { + if (element) + handlePattern(element, parentScope); + }); + } else if (p.type === "AssignmentPattern") { + handlePattern(p.left, parentScope); + } else { + setScope(parentScope, p.name); + } + } + walk(root, { + enter(node, parent) { + if (node.type === "ImportDeclaration") + return this.skip(); + if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) + parentStack.unshift(parent); + if (node.type === "VariableDeclaration") + varKindStack.unshift(node.kind); + if (node.type === "CallExpression") + onCallExpression == null ? void 0 : onCallExpression(node); + if (node.type === "MetaProperty" && node.meta.name === "import") + onImportMeta == null ? void 0 : onImportMeta(node); + else if (node.type === "ImportExpression") + onDynamicImport == null ? void 0 : onDynamicImport(node); + if (node.type === "Identifier") { + if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) { + identifiers.push([node, parentStack.slice(0)]); + } + } else if (isFunctionNode(node)) { + if (node.type === "FunctionDeclaration") { + const parentScope = findParentScope(parentStack); + if (parentScope) + setScope(parentScope, node.id.name); + } + node.params.forEach((p) => { + if (p.type === "ObjectPattern" || p.type === "ArrayPattern") { + handlePattern(p, node); + return; + } + walk(p.type === "AssignmentPattern" ? p.left : p, { + enter(child, parent2) { + if ((parent2 == null ? void 0 : parent2.type) === "AssignmentPattern" && (parent2 == null ? void 0 : parent2.right) === child) + return this.skip(); + if (child.type !== "Identifier") + return; + if (isStaticPropertyKey(child, parent2)) + return; + if ((parent2 == null ? void 0 : parent2.type) === "TemplateLiteral" && (parent2 == null ? void 0 : parent2.expressions.includes(child)) || (parent2 == null ? void 0 : parent2.type) === "CallExpression" && (parent2 == null ? void 0 : parent2.callee) === child) + return; + setScope(node, child.name); + } + }); + }); + } else if (node.type === "Property" && parent.type === "ObjectPattern") { + setIsNodeInPattern(node); + } else if (node.type === "VariableDeclarator") { + const parentFunction = findParentScope( + parentStack, + varKindStack[0] === "var" + ); + if (parentFunction) + handlePattern(node.id, parentFunction); + } else if (node.type === "CatchClause" && node.param) { + handlePattern(node.param, node); + } + }, + leave(node, parent) { + if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) + parentStack.shift(); + if (node.type === "VariableDeclaration") + varKindStack.shift(); + } + }); + identifiers.forEach(([node, stack]) => { + if (!isInScope(node.name, stack)) { + const parent = stack[0]; + const grandparent = stack[1]; + const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)); + const classDeclaration = parent.type === "PropertyDefinition" && (grandparent == null ? void 0 : grandparent.type) === "ClassBody" || parent.type === "ClassDeclaration" && node === parent.superClass; + const classExpression = parent.type === "ClassExpression" && node === parent.id; + onIdentifier == null ? void 0 : onIdentifier(node, { + hasBindingShortcut, + classDeclaration, + classExpression + }, stack); + } + }); +} +function isRefIdentifier(id, parent, parentStack) { + if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) + return false; + if (isFunctionNode(parent)) { + if (parent.id === id) + return false; + if (parent.params.includes(id)) + return false; + } + if (parent.type === "MethodDefinition" && !parent.computed) + return false; + if (isStaticPropertyKey(id, parent)) + return false; + if (isNodeInPattern(parent) && parent.value === id) + return false; + if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) + return false; + if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) + return false; + if (parent.type === "ExportSpecifier") + return false; + if (id.name === "arguments") + return false; + return true; +} +function isStaticProperty(node) { + return node && node.type === "Property" && !node.computed; +} +function isStaticPropertyKey(node, parent) { + return isStaticProperty(parent) && parent.key === node; +} +const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/; +function isFunctionNode(node) { + return functionNodeTypeRE.test(node.type); +} +const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/; +function isBlock(node) { + return blockNodeTypeRE.test(node.type); +} +function findParentScope(parentStack, isVar = false) { + return parentStack.find(isVar ? isFunctionNode : isBlock); +} +function isInDestructuringAssignment(parent, parentStack) { + if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) + return parentStack.some((i) => i.type === "AssignmentExpression"); + return false; +} + +export { esmWalker, isFunctionNode, isInDestructuringAssignment, isNodeInPattern, isStaticProperty, isStaticPropertyKey, setIsNodeInPattern }; diff --git a/web/node_modules/@vitest/utils/dist/chunk-colors.js b/web/node_modules/@vitest/utils/dist/chunk-colors.js new file mode 100644 index 0000000000000000000000000000000000000000..080aa1ddcd56419ec5d693d01033127cb2be58b2 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/chunk-colors.js @@ -0,0 +1,77 @@ +const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS"); +const SAFE_COLORS_SYMBOL = Symbol("vitest:SAFE_COLORS"); + +const colorsMap = { + bold: ["\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"], + dim: ["\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"], + italic: ["\x1B[3m", "\x1B[23m"], + underline: ["\x1B[4m", "\x1B[24m"], + inverse: ["\x1B[7m", "\x1B[27m"], + hidden: ["\x1B[8m", "\x1B[28m"], + strikethrough: ["\x1B[9m", "\x1B[29m"], + black: ["\x1B[30m", "\x1B[39m"], + red: ["\x1B[31m", "\x1B[39m"], + green: ["\x1B[32m", "\x1B[39m"], + yellow: ["\x1B[33m", "\x1B[39m"], + blue: ["\x1B[34m", "\x1B[39m"], + magenta: ["\x1B[35m", "\x1B[39m"], + cyan: ["\x1B[36m", "\x1B[39m"], + white: ["\x1B[37m", "\x1B[39m"], + gray: ["\x1B[90m", "\x1B[39m"], + bgBlack: ["\x1B[40m", "\x1B[49m"], + bgRed: ["\x1B[41m", "\x1B[49m"], + bgGreen: ["\x1B[42m", "\x1B[49m"], + bgYellow: ["\x1B[43m", "\x1B[49m"], + bgBlue: ["\x1B[44m", "\x1B[49m"], + bgMagenta: ["\x1B[45m", "\x1B[49m"], + bgCyan: ["\x1B[46m", "\x1B[49m"], + bgWhite: ["\x1B[47m", "\x1B[49m"] +}; +const colorsEntries = Object.entries(colorsMap); +function string(str) { + return String(str); +} +string.open = ""; +string.close = ""; +const defaultColors = /* @__PURE__ */ colorsEntries.reduce((acc, [key]) => { + acc[key] = string; + return acc; +}, { isColorSupported: false }); +function getDefaultColors() { + return { ...defaultColors }; +} +function getColors() { + return globalThis[SAFE_COLORS_SYMBOL] || defaultColors; +} +function createColors(isTTY = false) { + const enabled = typeof process !== "undefined" && !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && !("GITHUB_ACTIONS" in process.env) && ("FORCE_COLOR" in process.env || process.argv.includes("--color") || process.platform === "win32" || isTTY && process.env.TERM !== "dumb" || "CI" in process.env); + const replaceClose = (string2, close, replace, index) => { + const start = string2.substring(0, index) + replace; + const end = string2.substring(index + close.length); + const nextIndex = end.indexOf(close); + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end; + }; + const formatter = (open, close, replace = open) => { + const fn = (input) => { + const string2 = String(input); + const index = string2.indexOf(close, open.length); + return ~index ? open + replaceClose(string2, close, replace, index) + close : open + string2 + close; + }; + fn.open = open; + fn.close = close; + return fn; + }; + const colorsObject = { + isColorSupported: enabled, + reset: enabled ? (s) => `\x1B[0m${s}\x1B[0m` : string + }; + for (const [name, formatterArgs] of colorsEntries) { + colorsObject[name] = enabled ? formatter(...formatterArgs) : string; + } + return colorsObject; +} +function setupColors(colors) { + globalThis[SAFE_COLORS_SYMBOL] = colors; +} + +export { SAFE_TIMERS_SYMBOL as S, SAFE_COLORS_SYMBOL as a, getDefaultColors as b, createColors as c, getColors as g, setupColors as s }; diff --git a/web/node_modules/@vitest/utils/dist/chunk-display.js b/web/node_modules/@vitest/utils/dist/chunk-display.js new file mode 100644 index 0000000000000000000000000000000000000000..a590415eb5165590aecab132a0c7900613376b1d --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/chunk-display.js @@ -0,0 +1,144 @@ +import { format as format$1, plugins } from 'pretty-format'; +import * as loupe from 'loupe'; + +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) { + const MAX_LENGTH = maxLength ?? 1e4; + let result; + try { + result = format$1(object, { + maxDepth, + escapeString: false, + // min: true, + plugins: PLUGINS, + ...options + }); + } catch { + result = format$1(object, { + callToJSON: false, + maxDepth, + escapeString: false, + // min: true, + plugins: PLUGINS, + ...options + }); + } + return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(maxDepth / 2)) : result; +} + +const formatRegExp = /%[sdjifoOcj%]/g; +function format(...args) { + if (typeof args[0] !== "string") { + const objects = []; + for (let i2 = 0; i2 < args.length; i2++) + objects.push(inspect(args[i2], { depth: 0, colors: false, compact: 3 })); + return objects.join(" "); + } + const len = args.length; + let i = 1; + const template = args[0]; + let str = String(template).replace(formatRegExp, (x) => { + if (x === "%%") + return "%"; + if (i >= len) + return x; + switch (x) { + case "%s": { + const value = args[i++]; + if (typeof value === "bigint") + return `${value.toString()}n`; + if (typeof value === "number" && value === 0 && 1 / value < 0) + return "-0"; + if (typeof value === "object" && value !== null) + return inspect(value, { depth: 0, colors: false, compact: 3 }); + return String(value); + } + case "%d": { + const value = args[i++]; + if (typeof value === "bigint") + return `${value.toString()}n`; + return Number(value).toString(); + } + case "%i": { + const value = args[i++]; + if (typeof value === "bigint") + return `${value.toString()}n`; + return Number.parseInt(String(value)).toString(); + } + case "%f": + return Number.parseFloat(String(args[i++])).toString(); + case "%o": + return inspect(args[i++], { showHidden: true, showProxy: true }); + case "%O": + return inspect(args[i++]); + case "%c": { + i++; + return ""; + } + case "%j": + try { + return JSON.stringify(args[i++]); + } catch (err) { + const m = err.message; + if ( + // chromium + m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object") + ) + return "[Circular]"; + throw err; + } + default: + return x; + } + }); + for (let x = args[i]; i < len; x = args[++i]) { + if (x === null || typeof x !== "object") + str += ` ${x}`; + else + str += ` ${inspect(x)}`; + } + return str; +} +function inspect(obj, options = {}) { + if (options.truncate === 0) + options.truncate = Number.POSITIVE_INFINITY; + return loupe.inspect(obj, options); +} +function objDisplay(obj, options = {}) { + if (typeof options.truncate === "undefined") + options.truncate = 40; + const str = inspect(obj, options); + const type = Object.prototype.toString.call(obj); + if (options.truncate && str.length >= options.truncate) { + if (type === "[object Function]") { + const fn = obj; + return !fn.name || fn.name === "" ? "[Function]" : `[Function: ${fn.name}]`; + } else if (type === "[object Array]") { + return `[ Array(${obj.length}) ]`; + } else if (type === "[object Object]") { + const keys = Object.keys(obj); + const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", "); + return `{ Object (${kstr}) }`; + } else { + return str; + } + } + return str; +} + +export { format as f, inspect as i, objDisplay as o, stringify as s }; diff --git a/web/node_modules/@vitest/utils/dist/diff.d.ts b/web/node_modules/@vitest/utils/dist/diff.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7a7d339455cc3fb794b5f9ae6bac4f2caee3806 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/diff.d.ts @@ -0,0 +1,93 @@ +import { D as DiffOptions } from './types-widbdqe5.js'; +export { a as DiffOptionsColor } from './types-widbdqe5.js'; +import 'pretty-format'; + +/** + * Diff Match and Patch + * Copyright 2018 The diff-match-patch Authors. + * https://github.com/google/diff-match-patch + * + * 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. + */ +/** + * @fileoverview Computes the difference between two texts to create a patch. + * Applies the patch onto another text, allowing for errors. + * @author fraser@google.com (Neil Fraser) + */ +/** + * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: + * + * 1. Delete anything not needed to use diff_cleanupSemantic method + * 2. Convert from prototype properties to var declarations + * 3. Convert Diff to class from constructor and prototype + * 4. Add type annotations for arguments and return values + * 5. Add exports + */ +/** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ +declare const DIFF_DELETE = -1; +declare const DIFF_INSERT = 1; +declare const DIFF_EQUAL = 0; +/** + * Class representing one diff tuple. + * Attempts to look like a two-element array (which is what this used to be). + * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. + * @param {string} text Text to be deleted, inserted, or retained. + * @constructor + */ +declare class Diff { + 0: number; + 1: string; + constructor(op: number, text: string); +} + +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +declare function diffLinesUnified(aLines: Array, bLines: Array, options?: DiffOptions): string; +declare function diffLinesUnified2(aLinesDisplay: Array, bLinesDisplay: Array, aLinesCompare: Array, bLinesCompare: Array, options?: DiffOptions): string; +declare function diffLinesRaw(aLines: Array, bLines: Array): Array; + +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string; +declare function diffStringsRaw(a: string, b: string, cleanup: boolean): Array; + +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @param a Expected value + * @param b Received value + * @param options Diff options + * @returns {string | null} a string diff + */ +declare function diff(a: any, b: any, options?: DiffOptions): string | null; + +export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified }; diff --git a/web/node_modules/@vitest/utils/dist/diff.js b/web/node_modules/@vitest/utils/dist/diff.js new file mode 100644 index 0000000000000000000000000000000000000000..202fd40be897f10b4f1300fb176798a6c647a91c --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/diff.js @@ -0,0 +1,1048 @@ +import { format, plugins } from 'pretty-format'; +import * as diff$1 from 'diff-sequences'; +import { g as getColors } from './chunk-colors.js'; + +function getType(value) { + if (value === void 0) { + return "undefined"; + } else if (value === null) { + return "null"; + } else if (Array.isArray(value)) { + return "array"; + } else if (typeof value === "boolean") { + return "boolean"; + } else if (typeof value === "function") { + return "function"; + } else if (typeof value === "number") { + return "number"; + } else if (typeof value === "string") { + return "string"; + } else if (typeof value === "bigint") { + return "bigint"; + } else if (typeof value === "object") { + if (value != null) { + if (value.constructor === RegExp) + return "regexp"; + else if (value.constructor === Map) + return "map"; + else if (value.constructor === Set) + return "set"; + else if (value.constructor === Date) + return "date"; + } + return "object"; + } else if (typeof value === "symbol") { + return "symbol"; + } + throw new Error(`value of unknown type: ${value}`); +} + +const DIFF_DELETE = -1; +const DIFF_INSERT = 1; +const DIFF_EQUAL = 0; +class Diff { + 0; + 1; + constructor(op, text) { + this[0] = op; + this[1] = text; + } +} +const diff_commonPrefix = function(text1, text2) { + if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) + return 0; + let pointermin = 0; + let pointermax = Math.min(text1.length, text2.length); + let pointermid = pointermax; + let pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +}; +const diff_commonSuffix = function(text1, text2) { + if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) + return 0; + let pointermin = 0; + let pointermax = Math.min(text1.length, text2.length); + let pointermid = pointermax; + let pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +}; +const diff_commonOverlap_ = function(text1, text2) { + const text1_length = text1.length; + const text2_length = text2.length; + if (text1_length === 0 || text2_length === 0) + return 0; + if (text1_length > text2_length) + text1 = text1.substring(text1_length - text2_length); + else if (text1_length < text2_length) + text2 = text2.substring(0, text1_length); + const text_length = Math.min(text1_length, text2_length); + if (text1 === text2) + return text_length; + let best = 0; + let length = 1; + while (true) { + const pattern = text1.substring(text_length - length); + const found = text2.indexOf(pattern); + if (found === -1) + return best; + length += found; + if (found === 0 || text1.substring(text_length - length) === text2.substring(0, length)) { + best = length; + length++; + } + } +}; +const diff_cleanupSemantic = function(diffs) { + let changes = false; + const equalities = []; + let equalitiesLength = 0; + let lastEquality = null; + let pointer = 0; + let length_insertions1 = 0; + let length_deletions1 = 0; + let length_insertions2 = 0; + let length_deletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] === DIFF_EQUAL) { + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer][1]; + } else { + if (diffs[pointer][0] === DIFF_INSERT) + length_insertions2 += diffs[pointer][1].length; + else + length_deletions2 += diffs[pointer][1].length; + if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) { + diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality)); + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + equalitiesLength--; + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + if (changes) + diff_cleanupMerge(diffs); + diff_cleanupSemanticLossless(diffs); + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { + const deletion = diffs[pointer - 1][1]; + const insertion = diffs[pointer][1]; + const overlap_length1 = diff_commonOverlap_(deletion, insertion); + const overlap_length2 = diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); + diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); + diffs[pointer + 1][1] = insertion.substring(overlap_length1); + pointer++; + } + } else { + if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } +}; +const nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; +const whitespaceRegex_ = /\s/; +const linebreakRegex_ = /[\r\n]/; +const blanklineEndRegex_ = /\n\r?\n$/; +const blanklineStartRegex_ = /^\r?\n\r?\n/; +function diff_cleanupSemanticLossless(diffs) { + function diff_cleanupSemanticScore_(one, two) { + if (!one || !two) { + return 6; + } + const char1 = one.charAt(one.length - 1); + const char2 = two.charAt(0); + const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); + const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); + const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); + const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); + const lineBreak1 = whitespace1 && char1.match(linebreakRegex_); + const lineBreak2 = whitespace2 && char2.match(linebreakRegex_); + const blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); + const blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); + if (blankLine1 || blankLine2) { + return 5; + } else if (lineBreak1 || lineBreak2) { + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + return 3; + } else if (whitespace1 || whitespace2) { + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + return 1; + } + return 0; + } + let pointer = 1; + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + let equality1 = diffs[pointer - 1][1]; + let edit = diffs[pointer][1]; + let equality2 = diffs[pointer + 1][1]; + const commonOffset = diff_commonSuffix(equality1, edit); + if (commonOffset) { + const commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } + let bestEquality1 = equality1; + let bestEdit = edit; + let bestEquality2 = equality2; + let bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + const score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + if (diffs[pointer - 1][1] !== bestEquality1) { + if (bestEquality1) { + diffs[pointer - 1][1] = bestEquality1; + } else { + diffs.splice(pointer - 1, 1); + pointer--; + } + diffs[pointer][1] = bestEdit; + if (bestEquality2) { + diffs[pointer + 1][1] = bestEquality2; + } else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + pointer++; + } +} +function diff_cleanupMerge(diffs) { + diffs.push(new Diff(DIFF_EQUAL, "")); + let pointer = 0; + let count_delete = 0; + let count_insert = 0; + let text_delete = ""; + let text_insert = ""; + let commonlength; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + commonlength = diff_commonPrefix(text_insert, text_delete); + if (commonlength !== 0) { + if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL) { + diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); + } else { + diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); + pointer++; + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + commonlength = diff_commonSuffix(text_insert, text_delete); + if (commonlength !== 0) { + diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; + text_insert = text_insert.substring(0, text_insert.length - commonlength); + text_delete = text_delete.substring(0, text_delete.length - commonlength); + } + } + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + if (text_delete.length) { + diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length) { + diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ""; + text_insert = ""; + break; + } + } + if (diffs[diffs.length - 1][1] === "") + diffs.pop(); + let changes = false; + pointer = 1; + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { + diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + if (changes) + diff_cleanupMerge(diffs); +} + +const NO_DIFF_MESSAGE = "Compared values have no visual difference."; +const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\nPrinting internal object structure without calling `toJSON` instead."; + +function formatTrailingSpaces(line, trailingSpaceFormatter) { + return line.replace(/\s+$/, (match) => trailingSpaceFormatter(match)); +} +function printDiffLine(line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder) { + return line.length !== 0 ? color( + `${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}` + ) : indicator !== " " ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) : ""; +} +function printDeleteLine(line, isFirstOrLast, { + aColor, + aIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder +}) { + return printDiffLine( + line, + isFirstOrLast, + aColor, + aIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); +} +function printInsertLine(line, isFirstOrLast, { + bColor, + bIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder +}) { + return printDiffLine( + line, + isFirstOrLast, + bColor, + bIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); +} +function printCommonLine(line, isFirstOrLast, { + commonColor, + commonIndicator, + commonLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder +}) { + return printDiffLine( + line, + isFirstOrLast, + commonColor, + commonIndicator, + commonLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); +} +function createPatchMark(aStart, aEnd, bStart, bEnd, { patchColor }) { + return patchColor( + `@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@` + ); +} +function joinAlignedDiffsNoExpand(diffs, options) { + const iLength = diffs.length; + const nContextLines = options.contextLines; + const nContextLines2 = nContextLines + nContextLines; + let jLength = iLength; + let hasExcessAtStartOrEnd = false; + let nExcessesBetweenChanges = 0; + let i = 0; + while (i !== iLength) { + const iStart = i; + while (i !== iLength && diffs[i][0] === DIFF_EQUAL) + i += 1; + if (iStart !== i) { + if (iStart === 0) { + if (i > nContextLines) { + jLength -= i - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else if (i === iLength) { + const n = i - iStart; + if (n > nContextLines) { + jLength -= n - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else { + const n = i - iStart; + if (n > nContextLines2) { + jLength -= n - nContextLines2; + nExcessesBetweenChanges += 1; + } + } + } + while (i !== iLength && diffs[i][0] !== DIFF_EQUAL) + i += 1; + } + const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; + if (nExcessesBetweenChanges !== 0) + jLength += nExcessesBetweenChanges + 1; + else if (hasExcessAtStartOrEnd) + jLength += 1; + const jLast = jLength - 1; + const lines = []; + let jPatchMark = 0; + if (hasPatch) + lines.push(""); + let aStart = 0; + let bStart = 0; + let aEnd = 0; + let bEnd = 0; + const pushCommonLine = (line) => { + const j = lines.length; + lines.push(printCommonLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + bEnd += 1; + }; + const pushDeleteLine = (line) => { + const j = lines.length; + lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + }; + const pushInsertLine = (line) => { + const j = lines.length; + lines.push(printInsertLine(line, j === 0 || j === jLast, options)); + bEnd += 1; + }; + i = 0; + while (i !== iLength) { + let iStart = i; + while (i !== iLength && diffs[i][0] === DIFF_EQUAL) + i += 1; + if (iStart !== i) { + if (iStart === 0) { + if (i > nContextLines) { + iStart = i - nContextLines; + aStart = iStart; + bStart = iStart; + aEnd = aStart; + bEnd = bStart; + } + for (let iCommon = iStart; iCommon !== i; iCommon += 1) + pushCommonLine(diffs[iCommon][1]); + } else if (i === iLength) { + const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) + pushCommonLine(diffs[iCommon][1]); + } else { + const nCommon = i - iStart; + if (nCommon > nContextLines2) { + const iEnd = iStart + nContextLines; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) + pushCommonLine(diffs[iCommon][1]); + lines[jPatchMark] = createPatchMark( + aStart, + aEnd, + bStart, + bEnd, + options + ); + jPatchMark = lines.length; + lines.push(""); + const nOmit = nCommon - nContextLines2; + aStart = aEnd + nOmit; + bStart = bEnd + nOmit; + aEnd = aStart; + bEnd = bStart; + for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) + pushCommonLine(diffs[iCommon][1]); + } else { + for (let iCommon = iStart; iCommon !== i; iCommon += 1) + pushCommonLine(diffs[iCommon][1]); + } + } + } + while (i !== iLength && diffs[i][0] === DIFF_DELETE) { + pushDeleteLine(diffs[i][1]); + i += 1; + } + while (i !== iLength && diffs[i][0] === DIFF_INSERT) { + pushInsertLine(diffs[i][1]); + i += 1; + } + } + if (hasPatch) + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + return lines.join("\n"); +} +function joinAlignedDiffsExpand(diffs, options) { + return diffs.map((diff, i, diffs2) => { + const line = diff[1]; + const isFirstOrLast = i === 0 || i === diffs2.length - 1; + switch (diff[0]) { + case DIFF_DELETE: + return printDeleteLine(line, isFirstOrLast, options); + case DIFF_INSERT: + return printInsertLine(line, isFirstOrLast, options); + default: + return printCommonLine(line, isFirstOrLast, options); + } + }).join("\n"); +} + +const noColor = (string) => string; +const DIFF_CONTEXT_DEFAULT = 5; +function getDefaultOptions() { + const c = getColors(); + return { + aAnnotation: "Expected", + aColor: c.green, + aIndicator: "-", + bAnnotation: "Received", + bColor: c.red, + bIndicator: "+", + changeColor: c.inverse, + changeLineTrailingSpaceColor: noColor, + commonColor: c.dim, + commonIndicator: " ", + commonLineTrailingSpaceColor: noColor, + compareKeys: void 0, + contextLines: DIFF_CONTEXT_DEFAULT, + emptyFirstOrLastLinePlaceholder: "", + expand: true, + includeChangeCounts: false, + omitAnnotationLines: false, + patchColor: c.yellow + }; +} +function getCompareKeys(compareKeys) { + return compareKeys && typeof compareKeys === "function" ? compareKeys : void 0; +} +function getContextLines(contextLines) { + return typeof contextLines === "number" && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; +} +function normalizeDiffOptions(options = {}) { + return { + ...getDefaultOptions(), + ...options, + compareKeys: getCompareKeys(options.compareKeys), + contextLines: getContextLines(options.contextLines) + }; +} + +function isEmptyString(lines) { + return lines.length === 1 && lines[0].length === 0; +} +function countChanges(diffs) { + let a = 0; + let b = 0; + diffs.forEach((diff2) => { + switch (diff2[0]) { + case DIFF_DELETE: + a += 1; + break; + case DIFF_INSERT: + b += 1; + break; + } + }); + return { a, b }; +} +function printAnnotation({ + aAnnotation, + aColor, + aIndicator, + bAnnotation, + bColor, + bIndicator, + includeChangeCounts, + omitAnnotationLines +}, changeCounts) { + if (omitAnnotationLines) + return ""; + let aRest = ""; + let bRest = ""; + if (includeChangeCounts) { + const aCount = String(changeCounts.a); + const bCount = String(changeCounts.b); + const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; + const aAnnotationPadding = " ".repeat(Math.max(0, baAnnotationLengthDiff)); + const bAnnotationPadding = " ".repeat(Math.max(0, -baAnnotationLengthDiff)); + const baCountLengthDiff = bCount.length - aCount.length; + const aCountPadding = " ".repeat(Math.max(0, baCountLengthDiff)); + const bCountPadding = " ".repeat(Math.max(0, -baCountLengthDiff)); + aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`; + bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`; + } + const a = `${aIndicator} ${aAnnotation}${aRest}`; + const b = `${bIndicator} ${bAnnotation}${bRest}`; + return `${aColor(a)} +${bColor(b)} + +`; +} +function printDiffLines(diffs, options) { + return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)); +} +function diffLinesUnified(aLines, bLines, options) { + return printDiffLines( + diffLinesRaw( + isEmptyString(aLines) ? [] : aLines, + isEmptyString(bLines) ? [] : bLines + ), + normalizeDiffOptions(options) + ); +} +function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options) { + if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { + aLinesDisplay = []; + aLinesCompare = []; + } + if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { + bLinesDisplay = []; + bLinesCompare = []; + } + if (aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length) { + return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); + } + const diffs = diffLinesRaw(aLinesCompare, bLinesCompare); + let aIndex = 0; + let bIndex = 0; + diffs.forEach((diff2) => { + switch (diff2[0]) { + case DIFF_DELETE: + diff2[1] = aLinesDisplay[aIndex]; + aIndex += 1; + break; + case DIFF_INSERT: + diff2[1] = bLinesDisplay[bIndex]; + bIndex += 1; + break; + default: + diff2[1] = bLinesDisplay[bIndex]; + aIndex += 1; + bIndex += 1; + } + }); + return printDiffLines(diffs, normalizeDiffOptions(options)); +} +function diffLinesRaw(aLines, bLines) { + const aLength = aLines.length; + const bLength = bLines.length; + const isCommon = (aIndex2, bIndex2) => aLines[aIndex2] === bLines[bIndex2]; + const diffs = []; + let aIndex = 0; + let bIndex = 0; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + for (; aIndex !== aCommon; aIndex += 1) + diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); + for (; bIndex !== bCommon; bIndex += 1) + diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); + for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) + diffs.push(new Diff(DIFF_EQUAL, bLines[bIndex])); + }; + const diffSequences = diff$1.default.default || diff$1.default; + diffSequences(aLength, bLength, isCommon, foundSubsequence); + for (; aIndex !== aLength; aIndex += 1) + diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); + for (; bIndex !== bLength; bIndex += 1) + diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); + return diffs; +} + +function diffStrings(a, b) { + const isCommon = (aIndex2, bIndex2) => a[aIndex2] === b[bIndex2]; + let aIndex = 0; + let bIndex = 0; + const diffs = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + if (aIndex !== aCommon) + diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))); + if (bIndex !== bCommon) + diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon))); + aIndex = aCommon + nCommon; + bIndex = bCommon + nCommon; + diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex))); + }; + const diffSequences = diff$1.default.default || diff$1.default; + diffSequences(a.length, b.length, isCommon, foundSubsequence); + if (aIndex !== a.length) + diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))); + if (bIndex !== b.length) + diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex))); + return diffs; +} + +function concatenateRelevantDiffs(op, diffs, changeColor) { + return diffs.reduce( + (reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op && diff[1].length !== 0 ? changeColor(diff[1]) : ""), + "" + ); +} +class ChangeBuffer { + op; + line; + // incomplete line + lines; + // complete lines + changeColor; + constructor(op, changeColor) { + this.op = op; + this.line = []; + this.lines = []; + this.changeColor = changeColor; + } + pushSubstring(substring) { + this.pushDiff(new Diff(this.op, substring)); + } + pushLine() { + this.lines.push( + this.line.length !== 1 ? new Diff( + this.op, + concatenateRelevantDiffs(this.op, this.line, this.changeColor) + ) : this.line[0][0] === this.op ? this.line[0] : new Diff(this.op, this.line[0][1]) + // was common diff + ); + this.line.length = 0; + } + isLineEmpty() { + return this.line.length === 0; + } + // Minor input to buffer. + pushDiff(diff) { + this.line.push(diff); + } + // Main input to buffer. + align(diff) { + const string = diff[1]; + if (string.includes("\n")) { + const substrings = string.split("\n"); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i < iLast) { + this.pushSubstring(substring); + this.pushLine(); + } else if (substring.length !== 0) { + this.pushSubstring(substring); + } + }); + } else { + this.pushDiff(diff); + } + } + // Output from buffer. + moveLinesTo(lines) { + if (!this.isLineEmpty()) + this.pushLine(); + lines.push(...this.lines); + this.lines.length = 0; + } +} +class CommonBuffer { + deleteBuffer; + insertBuffer; + lines; + constructor(deleteBuffer, insertBuffer) { + this.deleteBuffer = deleteBuffer; + this.insertBuffer = insertBuffer; + this.lines = []; + } + pushDiffCommonLine(diff) { + this.lines.push(diff); + } + pushDiffChangeLines(diff) { + const isDiffEmpty = diff[1].length === 0; + if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) + this.deleteBuffer.pushDiff(diff); + if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) + this.insertBuffer.pushDiff(diff); + } + flushChangeLines() { + this.deleteBuffer.moveLinesTo(this.lines); + this.insertBuffer.moveLinesTo(this.lines); + } + // Input to buffer. + align(diff) { + const op = diff[0]; + const string = diff[1]; + if (string.includes("\n")) { + const substrings = string.split("\n"); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i === 0) { + const subdiff = new Diff(op, substring); + if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) { + this.flushChangeLines(); + this.pushDiffCommonLine(subdiff); + } else { + this.pushDiffChangeLines(subdiff); + this.flushChangeLines(); + } + } else if (i < iLast) { + this.pushDiffCommonLine(new Diff(op, substring)); + } else if (substring.length !== 0) { + this.pushDiffChangeLines(new Diff(op, substring)); + } + }); + } else { + this.pushDiffChangeLines(diff); + } + } + // Output from buffer. + getLines() { + this.flushChangeLines(); + return this.lines; + } +} +function getAlignedDiffs(diffs, changeColor) { + const deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor); + const insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); + const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + deleteBuffer.align(diff); + break; + case DIFF_INSERT: + insertBuffer.align(diff); + break; + default: + commonBuffer.align(diff); + } + }); + return commonBuffer.getLines(); +} + +function hasCommonDiff(diffs, isMultiline) { + if (isMultiline) { + const iLast = diffs.length - 1; + return diffs.some( + (diff, i) => diff[0] === DIFF_EQUAL && (i !== iLast || diff[1] !== "\n") + ); + } + return diffs.some((diff) => diff[0] === DIFF_EQUAL); +} +function diffStringsUnified(a, b, options) { + if (a !== b && a.length !== 0 && b.length !== 0) { + const isMultiline = a.includes("\n") || b.includes("\n"); + const diffs = diffStringsRaw( + isMultiline ? `${a} +` : a, + isMultiline ? `${b} +` : b, + true + // cleanupSemantic + ); + if (hasCommonDiff(diffs, isMultiline)) { + const optionsNormalized = normalizeDiffOptions(options); + const lines = getAlignedDiffs(diffs, optionsNormalized.changeColor); + return printDiffLines(lines, optionsNormalized); + } + } + return diffLinesUnified(a.split("\n"), b.split("\n"), options); +} +function diffStringsRaw(a, b, cleanup) { + const diffs = diffStrings(a, b); + if (cleanup) + diff_cleanupSemantic(diffs); + return diffs; +} + +function getCommonMessage(message, options) { + const { commonColor } = normalizeDiffOptions(options); + return commonColor(message); +} +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +const FORMAT_OPTIONS = { + plugins: PLUGINS +}; +const FALLBACK_FORMAT_OPTIONS = { + callToJSON: false, + maxDepth: 10, + plugins: PLUGINS +}; +function diff(a, b, options) { + if (Object.is(a, b)) + return ""; + const aType = getType(a); + let expectedType = aType; + let omitDifference = false; + if (aType === "object" && typeof a.asymmetricMatch === "function") { + if (a.$$typeof !== Symbol.for("jest.asymmetricMatcher")) { + return null; + } + if (typeof a.getExpectedType !== "function") { + return null; + } + expectedType = a.getExpectedType(); + omitDifference = expectedType === "string"; + } + if (expectedType !== getType(b)) { + const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator } = normalizeDiffOptions(options); + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + const aDisplay = format(a, formatOptions); + const bDisplay = format(b, formatOptions); + const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} +${aDisplay}`; + const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} +${bDisplay}`; + return `${aDiff} + +${bDiff}`; + } + if (omitDifference) + return null; + switch (aType) { + case "string": + return diffLinesUnified(a.split("\n"), b.split("\n"), options); + case "boolean": + case "number": + return comparePrimitive(a, b, options); + case "map": + return compareObjects(sortMap(a), sortMap(b), options); + case "set": + return compareObjects(sortSet(a), sortSet(b), options); + default: + return compareObjects(a, b, options); + } +} +function comparePrimitive(a, b, options) { + const aFormat = format(a, FORMAT_OPTIONS); + const bFormat = format(b, FORMAT_OPTIONS); + return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options); +} +function sortMap(map) { + return new Map(Array.from(map.entries()).sort()); +} +function sortSet(set) { + return new Set(Array.from(set.values()).sort()); +} +function compareObjects(a, b, options) { + let difference; + let hasThrown = false; + try { + const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + } catch { + hasThrown = true; + } + const noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options); + if (difference === void 0 || difference === noDiffMessage) { + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + if (difference !== noDiffMessage && !hasThrown) { + difference = `${getCommonMessage( + SIMILAR_MESSAGE, + options + )} + +${difference}`; + } + } + return difference; +} +function getFormatOptions(formatOptions, options) { + const { compareKeys } = normalizeDiffOptions(options); + return { + ...formatOptions, + compareKeys + }; +} +function getObjectsDifference(a, b, formatOptions, options) { + const formatOptionsZeroIndent = { ...formatOptions, indent: 0 }; + const aCompare = format(a, formatOptionsZeroIndent); + const bCompare = format(b, formatOptionsZeroIndent); + if (aCompare === bCompare) { + return getCommonMessage(NO_DIFF_MESSAGE, options); + } else { + const aDisplay = format(a, formatOptions); + const bDisplay = format(b, formatOptions); + return diffLinesUnified2( + aDisplay.split("\n"), + bDisplay.split("\n"), + aCompare.split("\n"), + bCompare.split("\n"), + options + ); + } +} + +export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified }; diff --git a/web/node_modules/@vitest/utils/dist/error.d.ts b/web/node_modules/@vitest/utils/dist/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd657d5311ff3d255dc57a2f7224301d532a3177 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/error.d.ts @@ -0,0 +1,11 @@ +import { D as DiffOptions } from './types-widbdqe5.js'; +import 'pretty-format'; + +declare function serializeError(val: any, seen?: WeakMap): any; +declare function processError(err: any, diffOptions?: DiffOptions): any; +declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet, expectedReplaced?: WeakSet): { + replacedActual: any; + replacedExpected: any; +}; + +export { processError, replaceAsymmetricMatcher, serializeError }; diff --git a/web/node_modules/@vitest/utils/dist/error.js b/web/node_modules/@vitest/utils/dist/error.js new file mode 100644 index 0000000000000000000000000000000000000000..a8df0a7c11bb5b0ed3bb2dc59b48b8176b9cd5ca --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/error.js @@ -0,0 +1,148 @@ +import { diff } from './diff.js'; +import { f as format, s as stringify } from './chunk-display.js'; +import { deepClone, getOwnProperties, getType } from './helpers.js'; +import 'pretty-format'; +import 'diff-sequences'; +import './chunk-colors.js'; +import 'loupe'; + +const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; +const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@"; +function isImmutable(v) { + return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]); +} +const OBJECT_PROTO = Object.getPrototypeOf({}); +function getUnserializableMessage(err) { + if (err instanceof Error) + return `: ${err.message}`; + if (typeof err === "string") + return `: ${err}`; + return ""; +} +function serializeError(val, seen = /* @__PURE__ */ new WeakMap()) { + if (!val || typeof val === "string") + return val; + if (typeof val === "function") + return `Function<${val.name || "anonymous"}>`; + if (typeof val === "symbol") + return val.toString(); + if (typeof val !== "object") + return val; + if (isImmutable(val)) + return serializeError(val.toJSON(), seen); + if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction") + return "Promise"; + if (typeof Element !== "undefined" && val instanceof Element) + return val.tagName; + if (typeof val.asymmetricMatch === "function") + return `${val.toString()} ${format(val.sample)}`; + if (seen.has(val)) + return seen.get(val); + if (Array.isArray(val)) { + const clone = new Array(val.length); + seen.set(val, clone); + val.forEach((e, i) => { + try { + clone[i] = serializeError(e, seen); + } catch (err) { + clone[i] = getUnserializableMessage(err); + } + }); + return clone; + } else { + const clone = /* @__PURE__ */ Object.create(null); + seen.set(val, clone); + let obj = val; + while (obj && obj !== OBJECT_PROTO) { + Object.getOwnPropertyNames(obj).forEach((key) => { + if (key in clone) + return; + try { + clone[key] = serializeError(val[key], seen); + } catch (err) { + delete clone[key]; + clone[key] = getUnserializableMessage(err); + } + }); + obj = Object.getPrototypeOf(obj); + } + return clone; + } +} +function normalizeErrorMessage(message) { + return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, ""); +} +function processError(err, diffOptions) { + if (!err || typeof err !== "object") + return { message: err }; + if (err.stack) + err.stackStr = String(err.stack); + if (err.name) + err.nameStr = String(err.name); + if (err.showDiff || err.showDiff === void 0 && err.expected !== void 0 && err.actual !== void 0) { + const clonedActual = deepClone(err.actual, { forceWritable: true }); + const clonedExpected = deepClone(err.expected, { forceWritable: true }); + const { replacedActual, replacedExpected } = replaceAsymmetricMatcher(clonedActual, clonedExpected); + err.diff = diff(replacedExpected, replacedActual, { ...diffOptions, ...err.diffOptions }); + } + if (typeof err.expected !== "string") + err.expected = stringify(err.expected, 10); + if (typeof err.actual !== "string") + err.actual = stringify(err.actual, 10); + try { + if (typeof err.message === "string") + err.message = normalizeErrorMessage(err.message); + if (typeof err.cause === "object" && typeof err.cause.message === "string") + err.cause.message = normalizeErrorMessage(err.cause.message); + } catch { + } + try { + return serializeError(err); + } catch (e) { + return serializeError(new Error(`Failed to fully serialize error: ${e == null ? void 0 : e.message} +Inner error message: ${err == null ? void 0 : err.message}`)); + } +} +function isAsymmetricMatcher(data) { + const type = getType(data); + return type === "Object" && typeof data.asymmetricMatch === "function"; +} +function isReplaceable(obj1, obj2) { + const obj1Type = getType(obj1); + const obj2Type = getType(obj2); + return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array"); +} +function replaceAsymmetricMatcher(actual, expected, actualReplaced = /* @__PURE__ */ new WeakSet(), expectedReplaced = /* @__PURE__ */ new WeakSet()) { + if (!isReplaceable(actual, expected)) + return { replacedActual: actual, replacedExpected: expected }; + if (actualReplaced.has(actual) || expectedReplaced.has(expected)) + return { replacedActual: actual, replacedExpected: expected }; + actualReplaced.add(actual); + expectedReplaced.add(expected); + getOwnProperties(expected).forEach((key) => { + const expectedValue = expected[key]; + const actualValue = actual[key]; + if (isAsymmetricMatcher(expectedValue)) { + if (expectedValue.asymmetricMatch(actualValue)) + actual[key] = expectedValue; + } else if (isAsymmetricMatcher(actualValue)) { + if (actualValue.asymmetricMatch(expectedValue)) + expected[key] = actualValue; + } else if (isReplaceable(actualValue, expectedValue)) { + const replaced = replaceAsymmetricMatcher( + actualValue, + expectedValue, + actualReplaced, + expectedReplaced + ); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + }); + return { + replacedActual: actual, + replacedExpected: expected + }; +} + +export { processError, replaceAsymmetricMatcher, serializeError }; diff --git a/web/node_modules/@vitest/utils/dist/helpers.d.ts b/web/node_modules/@vitest/utils/dist/helpers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8f345a929a2efaca7fa0c38af567c441bcabac4 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/helpers.d.ts @@ -0,0 +1,35 @@ +import { Nullable, Arrayable } from './types.js'; + +interface CloneOptions { + forceWritable?: boolean; +} +declare function notNullish(v: T | null | undefined): v is NonNullable; +declare function assertTypes(value: unknown, name: string, types: string[]): void; +declare function isPrimitive(value: unknown): boolean; +declare function slash(path: string): string; +declare function parseRegexp(input: string): RegExp; +declare function toArray(array?: Nullable>): Array; +declare function isObject(item: unknown): boolean; +declare function getType(value: unknown): string; +declare function getOwnProperties(obj: any): (string | symbol)[]; +declare function deepClone(val: T, options?: CloneOptions): T; +declare function clone(val: T, seen: WeakMap, options?: CloneOptions): T; +declare function noop(): void; +declare function objectAttr(source: any, path: string, defaultValue?: undefined): any; +type DeferPromise = Promise & { + resolve: (value: T | PromiseLike) => void; + reject: (reason?: any) => void; +}; +declare function createDefer(): DeferPromise; +/** + * If code starts with a function call, will return its last index, respecting arguments. + * This will return 25 - last ending character of toMatch ")" + * Also works with callbacks + * ``` + * toMatch({ test: '123' }); + * toBeAliased('123') + * ``` + */ +declare function getCallLastIndex(code: string): number | null; + +export { type DeferPromise, assertTypes, clone, createDefer, deepClone, getCallLastIndex, getOwnProperties, getType, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray }; diff --git a/web/node_modules/@vitest/utils/dist/helpers.js b/web/node_modules/@vitest/utils/dist/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..7b9365a7ff05ac8117d50a959f8bd9731cc12815 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/helpers.js @@ -0,0 +1,148 @@ +function notNullish(v) { + return v != null; +} +function assertTypes(value, name, types) { + const receivedType = typeof value; + const pass = types.includes(receivedType); + if (!pass) + throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`); +} +function isPrimitive(value) { + return value === null || typeof value !== "function" && typeof value !== "object"; +} +function slash(path) { + return path.replace(/\\/g, "/"); +} +function parseRegexp(input) { + const m = input.match(/(\/?)(.+)\1([a-z]*)/i); + if (!m) + return /$^/; + if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) + return RegExp(input); + return new RegExp(m[2], m[3]); +} +function toArray(array) { + if (array === null || array === void 0) + array = []; + if (Array.isArray(array)) + return array; + return [array]; +} +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} +function isFinalObj(obj) { + return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype; +} +function getType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +function collectOwnProperties(obj, collector) { + const collect = typeof collector === "function" ? collector : (key) => collector.add(key); + Object.getOwnPropertyNames(obj).forEach(collect); + Object.getOwnPropertySymbols(obj).forEach(collect); +} +function getOwnProperties(obj) { + const ownProps = /* @__PURE__ */ new Set(); + if (isFinalObj(obj)) + return []; + collectOwnProperties(obj, ownProps); + return Array.from(ownProps); +} +const defaultCloneOptions = { forceWritable: false }; +function deepClone(val, options = defaultCloneOptions) { + const seen = /* @__PURE__ */ new WeakMap(); + return clone(val, seen, options); +} +function clone(val, seen, options = defaultCloneOptions) { + let k, out; + if (seen.has(val)) + return seen.get(val); + if (Array.isArray(val)) { + out = Array(k = val.length); + seen.set(val, out); + while (k--) + out[k] = clone(val[k], seen, options); + return out; + } + if (Object.prototype.toString.call(val) === "[object Object]") { + out = Object.create(Object.getPrototypeOf(val)); + seen.set(val, out); + const props = getOwnProperties(val); + for (const k2 of props) { + const descriptor = Object.getOwnPropertyDescriptor(val, k2); + if (!descriptor) + continue; + const cloned = clone(val[k2], seen, options); + if ("get" in descriptor) { + Object.defineProperty(out, k2, { + ...descriptor, + get() { + return cloned; + } + }); + } else { + Object.defineProperty(out, k2, { + ...descriptor, + writable: options.forceWritable ? true : descriptor.writable, + value: cloned + }); + } + } + return out; + } + return val; +} +function noop() { +} +function objectAttr(source, path, defaultValue = void 0) { + const paths = path.replace(/\[(\d+)\]/g, ".$1").split("."); + let result = source; + for (const p of paths) { + result = Object(result)[p]; + if (result === void 0) + return defaultValue; + } + return result; +} +function createDefer() { + let resolve = null; + let reject = null; + const p = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + p.resolve = resolve; + p.reject = reject; + return p; +} +function getCallLastIndex(code) { + let charIndex = -1; + let inString = null; + let startedBracers = 0; + let endedBracers = 0; + let beforeChar = null; + while (charIndex <= code.length) { + beforeChar = code[charIndex]; + charIndex++; + const char = code[charIndex]; + const isCharString = char === '"' || char === "'" || char === "`"; + if (isCharString && beforeChar !== "\\") { + if (inString === char) + inString = null; + else if (!inString) + inString = char; + } + if (!inString) { + if (char === "(") + startedBracers++; + if (char === ")") + endedBracers++; + } + if (startedBracers && endedBracers && startedBracers === endedBracers) + return charIndex; + } + return null; +} + +export { assertTypes, clone, createDefer, deepClone, getCallLastIndex, getOwnProperties, getType, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray }; diff --git a/web/node_modules/@vitest/utils/dist/index.d.ts b/web/node_modules/@vitest/utils/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b39085b89f8fbdf7f2823cadeb2a25cc05698870 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/index.d.ts @@ -0,0 +1,110 @@ +export { DeferPromise, assertTypes, clone, createDefer, deepClone, getCallLastIndex, getOwnProperties, getType, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray } from './helpers.js'; +export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, ErrorWithDiff, MergeInsertions, MutableArray, Nullable, ParsedStack } from './types.js'; +import { PrettyFormatOptions } from 'pretty-format'; + +declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: PrettyFormatOptions & { + maxLength?: number; +}): string; + +declare function getSafeTimers(): { + nextTick: any; + setTimeout: any; + setInterval: any; + clearInterval: any; + clearTimeout: any; + setImmediate: any; + clearImmediate: any; +}; +declare function setSafeTimers(): void; + +declare function shuffle(array: T[], seed?: number): T[]; + +interface LoupeOptions { + showHidden?: boolean | undefined; + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + getters?: 'get' | 'set' | boolean | undefined; + numericSeparator?: boolean | undefined; + truncate?: number; +} +declare function format(...args: unknown[]): string; +declare function inspect(obj: unknown, options?: LoupeOptions): string; +declare function objDisplay(obj: unknown, options?: LoupeOptions): string; + +declare const SAFE_TIMERS_SYMBOL: unique symbol; +declare const SAFE_COLORS_SYMBOL: unique symbol; + +declare const colorsMap: { + readonly bold: readonly ["\u001B[1m", "\u001B[22m", "\u001B[22m\u001B[1m"]; + readonly dim: readonly ["\u001B[2m", "\u001B[22m", "\u001B[22m\u001B[2m"]; + readonly italic: readonly ["\u001B[3m", "\u001B[23m"]; + readonly underline: readonly ["\u001B[4m", "\u001B[24m"]; + readonly inverse: readonly ["\u001B[7m", "\u001B[27m"]; + readonly hidden: readonly ["\u001B[8m", "\u001B[28m"]; + readonly strikethrough: readonly ["\u001B[9m", "\u001B[29m"]; + readonly black: readonly ["\u001B[30m", "\u001B[39m"]; + readonly red: readonly ["\u001B[31m", "\u001B[39m"]; + readonly green: readonly ["\u001B[32m", "\u001B[39m"]; + readonly yellow: readonly ["\u001B[33m", "\u001B[39m"]; + readonly blue: readonly ["\u001B[34m", "\u001B[39m"]; + readonly magenta: readonly ["\u001B[35m", "\u001B[39m"]; + readonly cyan: readonly ["\u001B[36m", "\u001B[39m"]; + readonly white: readonly ["\u001B[37m", "\u001B[39m"]; + readonly gray: readonly ["\u001B[90m", "\u001B[39m"]; + readonly bgBlack: readonly ["\u001B[40m", "\u001B[49m"]; + readonly bgRed: readonly ["\u001B[41m", "\u001B[49m"]; + readonly bgGreen: readonly ["\u001B[42m", "\u001B[49m"]; + readonly bgYellow: readonly ["\u001B[43m", "\u001B[49m"]; + readonly bgBlue: readonly ["\u001B[44m", "\u001B[49m"]; + readonly bgMagenta: readonly ["\u001B[45m", "\u001B[49m"]; + readonly bgCyan: readonly ["\u001B[46m", "\u001B[49m"]; + readonly bgWhite: readonly ["\u001B[47m", "\u001B[49m"]; +}; +type ColorName = keyof typeof colorsMap; +interface ColorMethod { + (input: unknown): string; + open: string; + close: string; +} +type ColorsMethods = { + [Key in ColorName]: ColorMethod; +}; +type Colors$1 = ColorsMethods & { + isColorSupported: boolean; + reset: (input: unknown) => string; +}; +declare function getDefaultColors(): Colors$1; +declare function getColors(): Colors$1; +declare function createColors(isTTY?: boolean): Colors$1; +declare function setupColors(colors: Colors$1): void; + +interface ErrorOptions { + message?: string; + stackTraceLimit?: number; +} +/** + * Get original stacktrace without source map support the most performant way. + * - Create only 1 stack frame. + * - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). + */ +declare function createSimpleStackTrace(options?: ErrorOptions): string; + +declare const lineSplitRE: RegExp; +declare function positionToOffset(source: string, lineNumber: number, columnNumber: number): number; +declare function offsetToLineNumber(source: string, offset: number): number; + +type Colors = Record string>; +interface HighlightOptions { + jsx?: boolean; + colors?: Colors; +} +declare function highlight(code: string, options?: HighlightOptions): string; + +export { type ColorMethod, type ColorName, type Colors$1 as Colors, type ColorsMethods, SAFE_COLORS_SYMBOL, SAFE_TIMERS_SYMBOL, createColors, createSimpleStackTrace, format, getColors, getDefaultColors, getSafeTimers, highlight, inspect, lineSplitRE, objDisplay, offsetToLineNumber, positionToOffset, setSafeTimers, setupColors, shuffle, stringify }; diff --git a/web/node_modules/@vitest/utils/dist/index.js b/web/node_modules/@vitest/utils/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d512d3a492d8126d55a3d00986defc1c72a59b --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/index.js @@ -0,0 +1,643 @@ +export { assertTypes, clone, createDefer, deepClone, getCallLastIndex, getOwnProperties, getType, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray } from './helpers.js'; +export { f as format, i as inspect, o as objDisplay, s as stringify } from './chunk-display.js'; +import { S as SAFE_TIMERS_SYMBOL, g as getColors } from './chunk-colors.js'; +export { a as SAFE_COLORS_SYMBOL, c as createColors, b as getDefaultColors, s as setupColors } from './chunk-colors.js'; +import 'pretty-format'; +import 'loupe'; + +function getSafeTimers() { + const { + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate + } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis; + const { + nextTick: safeNextTick + } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || { nextTick: (cb) => cb() }; + return { + nextTick: safeNextTick, + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate + }; +} +function setSafeTimers() { + const { + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate + } = globalThis; + const { + nextTick: safeNextTick + } = globalThis.process || { nextTick: (cb) => cb() }; + const timers = { + nextTick: safeNextTick, + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate + }; + globalThis[SAFE_TIMERS_SYMBOL] = timers; +} + +const RealDate = Date; +function random(seed) { + const x = Math.sin(seed++) * 1e4; + return x - Math.floor(x); +} +function shuffle(array, seed = RealDate.now()) { + let length = array.length; + while (length) { + const index = Math.floor(random(seed) * length--); + const previous = array[length]; + array[length] = array[index]; + array[index] = previous; + ++seed; + } + return array; +} + +function createSimpleStackTrace(options) { + const { message = "error", stackTraceLimit = 1 } = options || {}; + const limit = Error.stackTraceLimit; + const prepareStackTrace = Error.prepareStackTrace; + Error.stackTraceLimit = stackTraceLimit; + Error.prepareStackTrace = (e) => e.stack; + const err = new Error(message); + const stackTrace = err.stack || ""; + Error.prepareStackTrace = prepareStackTrace; + Error.stackTraceLimit = limit; + return stackTrace; +} + +const lineSplitRE = /\r?\n/; +function positionToOffset(source, lineNumber, columnNumber) { + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let start = 0; + if (lineNumber > lines.length) + return source.length; + for (let i = 0; i < lineNumber - 1; i++) + start += lines[i].length + nl; + return start + columnNumber; +} +function offsetToLineNumber(source, offset) { + if (offset > source.length) { + throw new Error( + `offset is longer than source length! offset ${offset} > length ${source.length}` + ); + } + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let counted = 0; + let line = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + nl; + if (counted + lineLength >= offset) + break; + counted += lineLength; + } + return line + 1; +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +// Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell +// License: MIT. +var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; +RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu; +Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; +Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu; +StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y; +NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; +Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y; +WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu; +LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; +MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y; +SingleLineComment = /\/\/.*/y; +JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; +JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu; +JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y; +JSXText = /[^<>{}]+/y; +TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; +TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; +KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; +KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; +Newline = RegExp(LineTerminatorSequence.source); +var jsTokens_1 = function*(input, {jsx = false} = {}) { + var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; + ({length} = input); + lastIndex = 0; + lastSignificantToken = ""; + stack = [ + {tag: "JS"} + ]; + braces = []; + parenNesting = 0; + postfixIncDec = false; + while (lastIndex < length) { + mode = stack[stack.length - 1]; + switch (mode.tag) { + case "JS": + case "JSNonExpressionParen": + case "InterpolationInTemplate": + case "InterpolationInJSX": + if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + RegularExpressionLiteral.lastIndex = lastIndex; + if (match = RegularExpressionLiteral.exec(input)) { + lastIndex = RegularExpressionLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "RegularExpressionLiteral", + value: match[0], + closed: match[1] !== void 0 && match[1] !== "\\" + }); + continue; + } + } + Punctuator.lastIndex = lastIndex; + if (match = Punctuator.exec(input)) { + punctuator = match[0]; + nextLastIndex = Punctuator.lastIndex; + nextLastSignificantToken = punctuator; + switch (punctuator) { + case "(": + if (lastSignificantToken === "?NonExpressionParenKeyword") { + stack.push({ + tag: "JSNonExpressionParen", + nesting: parenNesting + }); + } + parenNesting++; + postfixIncDec = false; + break; + case ")": + parenNesting--; + postfixIncDec = true; + if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { + stack.pop(); + nextLastSignificantToken = "?NonExpressionParenEnd"; + postfixIncDec = false; + } + break; + case "{": + Punctuator.lastIndex = 0; + isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); + braces.push(isExpression); + postfixIncDec = false; + break; + case "}": + switch (mode.tag) { + case "InterpolationInTemplate": + if (braces.length === mode.nesting) { + Template.lastIndex = lastIndex; + match = Template.exec(input); + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + postfixIncDec = false; + yield ({ + type: "TemplateMiddle", + value: match[0] + }); + } else { + stack.pop(); + postfixIncDec = true; + yield ({ + type: "TemplateTail", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "InterpolationInJSX": + if (braces.length === mode.nesting) { + stack.pop(); + lastIndex += 1; + lastSignificantToken = "}"; + yield ({ + type: "JSXPunctuator", + value: "}" + }); + continue; + } + } + postfixIncDec = braces.pop(); + nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; + break; + case "]": + postfixIncDec = true; + break; + case "++": + case "--": + nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; + break; + case "<": + if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + stack.push({tag: "JSXTag"}); + lastIndex += 1; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: punctuator + }); + continue; + } + postfixIncDec = false; + break; + default: + postfixIncDec = false; + } + lastIndex = nextLastIndex; + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "Punctuator", + value: punctuator + }); + continue; + } + Identifier.lastIndex = lastIndex; + if (match = Identifier.exec(input)) { + lastIndex = Identifier.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "for": + case "if": + case "while": + case "with": + if (lastSignificantToken !== "." && lastSignificantToken !== "?.") { + nextLastSignificantToken = "?NonExpressionParenKeyword"; + } + } + lastSignificantToken = nextLastSignificantToken; + postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); + yield ({ + type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", + value: match[0] + }); + continue; + } + StringLiteral.lastIndex = lastIndex; + if (match = StringLiteral.exec(input)) { + lastIndex = StringLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "StringLiteral", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + NumericLiteral.lastIndex = lastIndex; + if (match = NumericLiteral.exec(input)) { + lastIndex = NumericLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "NumericLiteral", + value: match[0] + }); + continue; + } + Template.lastIndex = lastIndex; + if (match = Template.exec(input)) { + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + stack.push({ + tag: "InterpolationInTemplate", + nesting: braces.length + }); + postfixIncDec = false; + yield ({ + type: "TemplateHead", + value: match[0] + }); + } else { + postfixIncDec = true; + yield ({ + type: "NoSubstitutionTemplate", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "JSXTag": + case "JSXTagEnd": + JSXPunctuator.lastIndex = lastIndex; + if (match = JSXPunctuator.exec(input)) { + lastIndex = JSXPunctuator.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "<": + stack.push({tag: "JSXTag"}); + break; + case ">": + stack.pop(); + if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { + nextLastSignificantToken = "?JSX"; + postfixIncDec = true; + } else { + stack.push({tag: "JSXChildren"}); + } + break; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + nextLastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + break; + case "/": + if (lastSignificantToken === "<") { + stack.pop(); + if (stack[stack.length - 1].tag === "JSXChildren") { + stack.pop(); + } + stack.push({tag: "JSXTagEnd"}); + } + } + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "JSXPunctuator", + value: match[0] + }); + continue; + } + JSXIdentifier.lastIndex = lastIndex; + if (match = JSXIdentifier.exec(input)) { + lastIndex = JSXIdentifier.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXIdentifier", + value: match[0] + }); + continue; + } + JSXString.lastIndex = lastIndex; + if (match = JSXString.exec(input)) { + lastIndex = JSXString.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXString", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + break; + case "JSXChildren": + JSXText.lastIndex = lastIndex; + if (match = JSXText.exec(input)) { + lastIndex = JSXText.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXText", + value: match[0] + }); + continue; + } + switch (input[lastIndex]) { + case "<": + stack.push({tag: "JSXTag"}); + lastIndex++; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: "<" + }); + continue; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + lastIndex++; + lastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + yield ({ + type: "JSXPunctuator", + value: "{" + }); + continue; + } + } + WhiteSpace.lastIndex = lastIndex; + if (match = WhiteSpace.exec(input)) { + lastIndex = WhiteSpace.lastIndex; + yield ({ + type: "WhiteSpace", + value: match[0] + }); + continue; + } + LineTerminatorSequence.lastIndex = lastIndex; + if (match = LineTerminatorSequence.exec(input)) { + lastIndex = LineTerminatorSequence.lastIndex; + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + yield ({ + type: "LineTerminatorSequence", + value: match[0] + }); + continue; + } + MultiLineComment.lastIndex = lastIndex; + if (match = MultiLineComment.exec(input)) { + lastIndex = MultiLineComment.lastIndex; + if (Newline.test(match[0])) { + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + } + yield ({ + type: "MultiLineComment", + value: match[0], + closed: match[1] !== void 0 + }); + continue; + } + SingleLineComment.lastIndex = lastIndex; + if (match = SingleLineComment.exec(input)) { + lastIndex = SingleLineComment.lastIndex; + postfixIncDec = false; + yield ({ + type: "SingleLineComment", + value: match[0] + }); + continue; + } + firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); + lastIndex += firstCodePoint.length; + lastSignificantToken = firstCodePoint; + postfixIncDec = false; + yield ({ + type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", + value: firstCodePoint + }); + } + return void 0; +}; + +var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokens_1); + +// src/index.ts +var reservedWords = { + keyword: [ + "break", + "case", + "catch", + "continue", + "debugger", + "default", + "do", + "else", + "finally", + "for", + "function", + "if", + "return", + "switch", + "throw", + "try", + "var", + "const", + "while", + "with", + "new", + "this", + "super", + "class", + "extends", + "export", + "import", + "null", + "true", + "false", + "in", + "instanceof", + "typeof", + "void", + "delete" + ], + strict: [ + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield" + ] +}, keywords = new Set(reservedWords.keyword), reservedWordsStrictSet = new Set(reservedWords.strict), sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]); +function isReservedWord(word) { + return word === "await" || word === "enum"; +} +function isStrictReservedWord(word) { + return isReservedWord(word) || reservedWordsStrictSet.has(word); +} +function isKeyword(word) { + return keywords.has(word); +} +var BRACKET = /^[()[\]{}]$/, getTokenType = function(token) { + if (token.type === "IdentifierName") { + if (isKeyword(token.value) || isStrictReservedWord(token.value) || sometimesKeywords.has(token.value)) + return "Keyword"; + if (token.value[0] && token.value[0] !== token.value[0].toLowerCase()) + return "IdentifierCapitalized"; + } + return token.type === "Punctuator" && BRACKET.test(token.value) ? "Bracket" : token.type === "Invalid" && (token.value === "@" || token.value === "#") ? "Punctuator" : token.type; +}; +function getCallableType(token) { + if (token.type === "IdentifierName") + return "IdentifierCallable"; + if (token.type === "PrivateIdentifier") + return "PrivateIdentifierCallable"; + throw new Error("Not a callable token"); +} +var colorize = (defs, type, value) => { + let colorize2 = defs[type]; + return colorize2 ? colorize2(value) : value; +}, highlightTokens = (defs, text, jsx) => { + let highlighted = "", lastPotentialCallable = null, stackedHighlight = ""; + for (let token of jsTokens(text, { jsx })) { + let type = getTokenType(token); + if (type === "IdentifierName" || type === "PrivateIdentifier") { + lastPotentialCallable && (highlighted += colorize(defs, getTokenType(lastPotentialCallable), lastPotentialCallable.value) + stackedHighlight, stackedHighlight = ""), lastPotentialCallable = token; + continue; + } + if (lastPotentialCallable && (token.type === "WhiteSpace" || token.type === "LineTerminatorSequence" || token.type === "Punctuator" && (token.value === "?." || token.value === "!"))) { + stackedHighlight += colorize(defs, type, token.value); + continue; + } + if (stackedHighlight && !lastPotentialCallable && (highlighted += stackedHighlight, stackedHighlight = ""), lastPotentialCallable) { + let type2 = token.type === "Punctuator" && token.value === "(" ? getCallableType(lastPotentialCallable) : getTokenType(lastPotentialCallable); + highlighted += colorize(defs, type2, lastPotentialCallable.value) + stackedHighlight, stackedHighlight = "", lastPotentialCallable = null; + } + highlighted += colorize(defs, type, token.value); + } + return highlighted; +}; +function highlight$1(code, options = { jsx: !1, colors: {} }) { + return code && highlightTokens(options.colors || {}, code, options.jsx); +} + +function getDefs(c) { + const Invalid = (text) => c.white(c.bgRed(c.bold(text))); + return { + Keyword: c.magenta, + IdentifierCapitalized: c.yellow, + Punctuator: c.yellow, + StringLiteral: c.green, + NoSubstitutionTemplate: c.green, + MultiLineComment: c.gray, + SingleLineComment: c.gray, + RegularExpressionLiteral: c.cyan, + NumericLiteral: c.blue, + TemplateHead: (text) => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)), + TemplateTail: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)), + TemplateMiddle: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)), + IdentifierCallable: c.blue, + PrivateIdentifierCallable: (text) => `#${c.blue(text.slice(1))}`, + Invalid, + JSXString: c.green, + JSXIdentifier: c.yellow, + JSXInvalid: Invalid, + JSXPunctuator: c.yellow + }; +} +function highlight(code, options = { jsx: false }) { + return highlight$1(code, { + jsx: options.jsx, + colors: getDefs(options.colors || getColors()) + }); +} + +export { SAFE_TIMERS_SYMBOL, createSimpleStackTrace, getColors, getSafeTimers, highlight, lineSplitRE, offsetToLineNumber, positionToOffset, setSafeTimers, shuffle }; diff --git a/web/node_modules/@vitest/utils/dist/source-map.d.ts b/web/node_modules/@vitest/utils/dist/source-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1fd92627b3308d35b43666b7c22007fa0a7b22d --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/source-map.d.ts @@ -0,0 +1,111 @@ +import { ParsedStack, ErrorWithDiff } from './types.js'; + +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +type GeneratedMapping = { + line: number; + column: number; +}; +type InvalidGeneratedMapping = { + line: null; + column: null; +}; +type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +type SourceMapInput = string | Ro | Ro | TraceMap; +type Needle = { + line: number; + column: number; + bias?: Bias; +}; +type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +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']; +} +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; +}; + +declare const LEAST_UPPER_BOUND = -1; +declare const GREATEST_LOWER_BOUND = 1; +/** + * 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. + */ +declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} + +interface StackTraceParserOptions { + ignoreStackEntries?: (RegExp | string)[]; + getSourceMap?: (file: string) => unknown; + frameFilter?: (error: Error, frame: ParsedStack) => boolean | void; +} +declare function parseSingleFFOrSafariStack(raw: string): ParsedStack | null; +declare function parseSingleStack(raw: string): ParsedStack | null; +declare function parseSingleV8Stack(raw: string): ParsedStack | null; +declare function parseStacktrace(stack: string, options?: StackTraceParserOptions): ParsedStack[]; +declare function parseErrorStacktrace(e: ErrorWithDiff, options?: StackTraceParserOptions): ParsedStack[]; + +export { type SourceMapInput, type StackTraceParserOptions, TraceMap, generatedPositionFor, originalPositionFor, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; diff --git a/web/node_modules/@vitest/utils/dist/source-map.js b/web/node_modules/@vitest/utils/dist/source-map.js new file mode 100644 index 0000000000000000000000000000000000000000..bed71fb97b90f720c7997890d9167fdc758f0da8 --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/source-map.js @@ -0,0 +1,878 @@ +import { notNullish, isPrimitive } from './helpers.js'; + +function normalizeWindowsPath(input = "") { + if (!input || !input.includes("\\")) { + return input; + } + return input.replace(/\\/g, "/"); +} +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +function cwd() { + if (typeof process !== "undefined") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve$2 = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; + +const comma = ','.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; +} +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator$1); +} +function sortComparator$1(a, b) { + return a[0] - b[0]; +} + +// 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; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +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: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.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('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.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 <= UrlType.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$1(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.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 UrlType.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 UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.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 UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +function resolve(input, base) { + // The base 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 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$1(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + 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, 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]; +} + +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]); + * ``` + */ +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, + }; +} +/** + * 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. + */ +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) { + // 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)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +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 sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (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. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [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; +} +// 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() { + return { __proto__: null }; +} + +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)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * 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. + */ +let originalPositionFor; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +let generatedPositionFor; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : 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; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + originalPositionFor = (map, { line, column, bias }) => { + 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, 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); + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + function generatedPosition(map, source, line, column, bias, all) { + 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 = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = 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]); + } +})(); +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); + // 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 (!found && 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 = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + 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; +} + +const CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code])?$/; +const stackIgnorePatterns = [ + "node:internal", + /\/packages\/\w+\/dist\//, + /\/@vitest\/\w+\/dist\//, + "/vitest/dist/", + "/vitest/src/", + "/vite-node/dist/", + "/vite-node/src/", + "/node_modules/chai/", + "/node_modules/tinypool/", + "/node_modules/tinyspy/", + "/deps/chai.js", + /__vitest_browser__/ +]; +function extractLocation(urlLike) { + if (!urlLike.includes(":")) + return [urlLike]; + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) + return [urlLike]; + let url = parts[1]; + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + url = urlObj.pathname; + } + if (url.startsWith("/@fs/")) { + url = url.slice(typeof process !== "undefined" && process.platform === "win32" ? 5 : 4); + } + return [url, parts[2] || void 0, parts[3] || void 0]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) + return null; + if (line.includes(" > eval")) + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + if (!line.includes("@") && !line.includes(":")) + return null; + const functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/; + const matches = line.match(functionNameRegex); + const functionName = matches && matches[1] ? matches[1] : void 0; + const [url, lineNumber, columnNumber] = extractLocation(line.replace(functionNameRegex, "")); + if (!url || !lineNumber || !columnNumber) + return null; + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseSingleStack(raw) { + const line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) + return parseSingleFFOrSafariStack(line); + return parseSingleV8Stack(line); +} +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) + return null; + if (line.includes("(eval ")) + line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); + let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); + const location = sanitizedLine.match(/ (\(.+\)$)/); + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? void 0 : url; + if (!file || !lineNumber || !columnNumber) + return null; + if (method.startsWith("async ")) + method = method.slice(6); + if (file.startsWith("file://")) + file = file.slice(7); + file = resolve$2(file); + if (method) + method = method.replace(/__vite_ssr_import_\d+__\./g, ""); + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseStacktrace(stack, options = {}) { + const { ignoreStackEntries = stackIgnorePatterns } = options; + let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); + if (ignoreStackEntries.length) + stacks = stacks.filter((stack2) => !ignoreStackEntries.some((p) => stack2.file.match(p))); + return stacks.map((stack2) => { + var _a; + const map = (_a = options.getSourceMap) == null ? void 0 : _a.call(options, stack2.file); + if (!map || typeof map !== "object" || !map.version) + return stack2; + const traceMap = new TraceMap(map); + const { line, column } = originalPositionFor(traceMap, stack2); + if (line != null && column != null) + return { ...stack2, line, column }; + return stack2; + }); +} +function parseFFOrSafariStackTrace(stack) { + return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); +} +function parseV8Stacktrace(stack) { + return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); +} +function parseErrorStacktrace(e, options = {}) { + if (!e || isPrimitive(e)) + return []; + if (e.stacks) + return e.stacks; + const stackStr = e.stack || e.stackStr || ""; + let stackFrames = parseStacktrace(stackStr, options); + if (options.frameFilter) + stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); + e.stacks = stackFrames; + return stackFrames; +} + +export { TraceMap, generatedPositionFor, originalPositionFor, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; diff --git a/web/node_modules/@vitest/utils/dist/types-widbdqe5.d.ts b/web/node_modules/@vitest/utils/dist/types-widbdqe5.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d54f9a8a1ae4368f76b0d165a3c2ea0467866c8a --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/types-widbdqe5.d.ts @@ -0,0 +1,32 @@ +import { CompareKeys } from 'pretty-format'; + +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +type DiffOptionsColor = (arg: string) => string; +interface DiffOptions { + aAnnotation?: string; + aColor?: DiffOptionsColor; + aIndicator?: string; + bAnnotation?: string; + bColor?: DiffOptionsColor; + bIndicator?: string; + changeColor?: DiffOptionsColor; + changeLineTrailingSpaceColor?: DiffOptionsColor; + commonColor?: DiffOptionsColor; + commonIndicator?: string; + commonLineTrailingSpaceColor?: DiffOptionsColor; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + patchColor?: DiffOptionsColor; + compareKeys?: CompareKeys; +} + +export type { DiffOptions as D, DiffOptionsColor as a }; diff --git a/web/node_modules/@vitest/utils/dist/types.d.ts b/web/node_modules/@vitest/utils/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23e2a27964c489e71f248ea4e365830063f31b5a --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/types.d.ts @@ -0,0 +1,39 @@ +type Awaitable = T | PromiseLike; +type Nullable = T | null | undefined; +type Arrayable = T | Array; +type ArgumentsType = T extends (...args: infer U) => any ? U : never; +type MergeInsertions = T extends object ? { + [K in keyof T]: MergeInsertions; +} : T; +type DeepMerge = MergeInsertions<{ + [K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never; +}>; +type MutableArray = { + -readonly [k in keyof T]: T[k]; +}; +interface Constructable { + new (...args: any[]): any; +} +interface ParsedStack { + method: string; + file: string; + line: number; + column: number; +} +interface ErrorWithDiff extends Error { + name: string; + nameStr?: string; + stack?: string; + stackStr?: string; + stacks?: ParsedStack[]; + showDiff?: boolean; + actual?: any; + expected?: any; + operator?: string; + type?: string; + frame?: string; + diff?: string; + codeFrame?: string; +} + +export type { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, ErrorWithDiff, MergeInsertions, MutableArray, Nullable, ParsedStack }; diff --git a/web/node_modules/@vitest/utils/dist/types.js b/web/node_modules/@vitest/utils/dist/types.js new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/web/node_modules/@vitest/utils/dist/types.js @@ -0,0 +1 @@ + diff --git a/web/node_modules/@vitest/utils/error.d.ts b/web/node_modules/@vitest/utils/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9329baa87d94cc608a51d289e80c88bcbb5e0b99 --- /dev/null +++ b/web/node_modules/@vitest/utils/error.d.ts @@ -0,0 +1 @@ +export * from './dist/error.js' diff --git a/web/node_modules/@vitest/utils/helpers.d.ts b/web/node_modules/@vitest/utils/helpers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0add1d0f2bd1444960da3a46d4525117a9b2f1ea --- /dev/null +++ b/web/node_modules/@vitest/utils/helpers.d.ts @@ -0,0 +1 @@ +export * from './dist/helpers.js' diff --git a/web/node_modules/@vitest/utils/package.json b/web/node_modules/@vitest/utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8923f23d6c0ce6b0886fa32f1f05dbd60585c199 --- /dev/null +++ b/web/node_modules/@vitest/utils/package.json @@ -0,0 +1,74 @@ +{ + "name": "@vitest/utils", + "type": "module", + "version": "1.3.1", + "description": "Shared Vitest utility functions", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/utils" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./diff": { + "types": "./dist/diff.d.ts", + "default": "./dist/diff.js" + }, + "./ast": { + "types": "./dist/ast.d.ts", + "default": "./dist/ast.js" + }, + "./error": { + "types": "./dist/error.d.ts", + "default": "./dist/error.js" + }, + "./helpers": { + "types": "./dist/helpers.d.ts", + "default": "./dist/helpers.js" + }, + "./source-map": { + "types": "./dist/source-map.d.ts", + "default": "./dist/source-map.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "source-map": [ + "dist/source-map.d.ts" + ] + } + }, + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "diff-sequences": "^29.6.3", + "estree-walker": "^3.0.3", + "loupe": "^2.3.7", + "pretty-format": "^29.7.0" + }, + "devDependencies": { + "@jridgewell/trace-mapping": "^0.3.22", + "@types/estree": "^1.0.5", + "tinyhighlight": "^0.3.2" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/web/node_modules/acorn-walk/CHANGELOG.md b/web/node_modules/acorn-walk/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..0b4eea8a95d3eda2a03d9e885c39a2d11883acb6 --- /dev/null +++ b/web/node_modules/acorn-walk/CHANGELOG.md @@ -0,0 +1,181 @@ +## 8.3.1 (2023-12-06) + +### Bug fixes + +Add `Function` and `Class` to the `AggregateType` type, so that they can be used in walkers without raising a type error. + +Visitor functions are now called in such a way that their `this` refers to the object they are part of. + +## 8.3.0 (2023-10-26) + +### New features + +Use a set of new, much more precise, TypeScript types. + +## 8.2.0 (2021-09-06) + +### New features + +Add support for walking ES2022 class static blocks. + +## 8.1.1 (2021-06-29) + +### Bug fixes + +Include `base` in the type declarations. + +## 8.1.0 (2021-04-24) + +### New features + +Support node types for class fields and private methods. + +## 8.0.2 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.0 (2021-01-05) + +### Bug fixes + +Fix a bug where `full` and `fullAncestor` would skip nodes with overridden types. + +## 8.0.0 (2020-08-12) + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +## 7.2.0 (2020-06-17) + +### New features + +Support optional chaining and nullish coalescing. + +Support `import.meta`. + +Add support for `export * as ns from "source"`. + +## 7.1.1 (2020-02-13) + +### Bug fixes + +Clean up the type definitions to actually work well with the main parser. + +## 7.1.0 (2020-02-11) + +### New features + +Add a TypeScript definition file for the library. + +## 7.0.0 (2017-08-12) + +### New features + +Support walking `ImportExpression` nodes. + +## 6.2.0 (2017-07-04) + +### New features + +Add support for `Import` nodes. + +## 6.1.0 (2018-09-28) + +### New features + +The walker now walks `TemplateElement` nodes. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix bad "main" field in package.json. + +## 6.0.0 (2018-09-14) + +### Breaking changes + +This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package. + +The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported. + +## 5.7.1 (2018-06-15) + +### Bug fixes + +Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions). + +## 5.7.0 (2018-06-15) + +### Bug fixes + +Fix crash in walker when walking a binding-less catch node. + +## 5.6.2 (2018-06-05) + +### Bug fixes + +In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere. + +## 5.6.1 (2018-06-01) + +### Bug fixes + +Fix regression when passing `null` as fourth argument to `walk.recursive`. + +## 5.6.0 (2018-05-31) + +### Bug fixes + +Fix a bug in the walker that caused a crash when walking an object pattern spread. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix regression in walker causing property values in object patterns to be walked as expressions. + +## 5.5.0 (2018-02-27) + +### Bug fixes + +Support object spread in the AST walker. + +## 5.4.1 (2018-02-02) + +### Bug fixes + +5.4.0 somehow accidentally included an old version of walk.js. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +The `full` and `fullAncestor` walkers no longer visit nodes multiple times. + +## 5.1.0 (2017-07-05) + +### New features + +New walker functions `full` and `fullAncestor`. + +## 3.2.0 (2016-06-07) + +### New features + +Make it possible to use `visit.ancestor` with a walk state. + +## 3.1.0 (2016-04-18) + +### New features + +The walker now allows defining handlers for `CatchClause` nodes. + +## 2.5.2 (2015-10-27) + +### Fixes + +Fix bug where the walker walked an exported `let` statement as an expression. diff --git a/web/node_modules/acorn-walk/LICENSE b/web/node_modules/acorn-walk/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d6be6db2cfff576dd96f97180707581bfb6b726c --- /dev/null +++ b/web/node_modules/acorn-walk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2020 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/web/node_modules/acorn-walk/README.md b/web/node_modules/acorn-walk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3c18a2c76a938e426503ba488233bc2703acf17c --- /dev/null +++ b/web/node_modules/acorn-walk/README.md @@ -0,0 +1,124 @@ +# Acorn AST walker + +An abstract syntax tree walker for the +[ESTree](https://github.com/estree/estree) format. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn-walk +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +An algorithm for recursing through a syntax tree is stored as an +object, with a property for each tree node type holding a function +that will recurse through such a node. There are several ways to run +such a walker. + +**simple**`(node, visitors, base, state)` does a 'simple' walk over a +tree. `node` should be the AST node to walk, and `visitors` an object +with properties whose names correspond to node types in the [ESTree +spec](https://github.com/estree/estree). The properties should contain +functions that will be called with the node object and, if applicable +the state at that point. The last two arguments are optional. `base` +is a walker algorithm, and `state` is a start state. The default +walker will simply visit all statements and expressions and not +produce a meaningful state. (An example of a use of state is to track +scope at each point in the tree.) + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.simple(acorn.parse("let x = 10"), { + Literal(node) { + console.log(`Found a literal: ${node.value}`) + } +}) +``` + +**ancestor**`(node, visitors, base, state)` does a 'simple' walk over +a tree, building up an array of ancestor nodes (including the current node) +and passing the array to the callbacks as a third parameter. + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.ancestor(acorn.parse("foo('hi')"), { + Literal(_node, _state, ancestors) { + console.log("This literal's ancestors are:", ancestors.map(n => n.type)) + } +}) +``` + +**recursive**`(node, state, functions, base)` does a 'recursive' +walk, where the walker functions are responsible for continuing the +walk on the child nodes of their target node. `state` is the start +state, and `functions` should contain an object that maps node types +to walker functions. Such functions are called with `(node, state, c)` +arguments, and can cause the walk to continue on a sub-node by calling +the `c` argument on it with `(node, state)` arguments. The optional +`base` argument provides the fallback walker functions for node types +that aren't handled in the `functions` object. If not given, the +default walkers will be used. + +**make**`(functions, base)` builds a new walker object by using the +walker functions in `functions` and filling in the missing ones by +taking defaults from `base`. + +**full**`(node, callback, base, state)` does a 'full' walk over a +tree, calling the callback with the arguments (node, state, type) for +each node + +**fullAncestor**`(node, callback, base, state)` does a 'full' walk +over a tree, building up an array of ancestor nodes (including the +current node) and passing the array to the callbacks as a third +parameter. + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.full(acorn.parse("1 + 1"), node => { + console.log(`There's a ${node.type} node at ${node.ch}`) +}) +``` + +**findNodeAt**`(node, start, end, test, base, state)` tries to locate +a node in a tree at the given start and/or end offsets, which +satisfies the predicate `test`. `start` and `end` can be either `null` +(as wildcard) or a number. `test` may be a string (indicating a node +type) or a function that takes `(nodeType, node)` arguments and +returns a boolean indicating whether this node is interesting. `base` +and `state` are optional, and can be used to specify a custom walker. +Nodes are tested from inner to outer, so if two nodes match the +boundaries, the inner one will be preferred. + +**findNodeAround**`(node, pos, test, base, state)` is a lot like +`findNodeAt`, but will match any node that exists 'around' (spanning) +the given position. + +**findNodeAfter**`(node, pos, test, base, state)` is similar to +`findNodeAround`, but will match all nodes *after* the given position +(testing outer nodes before inner nodes). diff --git a/web/node_modules/acorn-walk/dist/walk.d.mts b/web/node_modules/acorn-walk/dist/walk.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e07a6afaf8e336137fe00b1321f6de3b7f0085ea --- /dev/null +++ b/web/node_modules/acorn-walk/dist/walk.d.mts @@ -0,0 +1,177 @@ +import * as acorn from "acorn" + +export type FullWalkerCallback = ( + node: acorn.Node, + state: TState, + type: string +) => void + +export type FullAncestorWalkerCallback = ( + node: acorn.Node, + state: TState, + ancestors: acorn.Node[], + type: string +) => void + +type AggregateType = { + Expression: acorn.Expression, + Statement: acorn.Statement, + Function: acorn.Function, + Class: acorn.Class, + Pattern: acorn.Pattern, + ForInit: acorn.VariableDeclaration | acorn.Expression +} + +export type SimpleVisitors = { + [type in acorn.AnyNode["type"]]?: (node: Extract, state: TState) => void +} & { + [type in keyof AggregateType]?: (node: AggregateType[type], state: TState) => void +} + +export type AncestorVisitors = { + [type in acorn.AnyNode["type"]]?: ( node: Extract, state: TState, ancestors: acorn.Node[] +) => void +} & { + [type in keyof AggregateType]?: (node: AggregateType[type], state: TState, ancestors: acorn.Node[]) => void +} + +export type WalkerCallback = (node: acorn.Node, state: TState) => void + +export type RecursiveVisitors = { + [type in acorn.AnyNode["type"]]?: ( node: Extract, state: TState, callback: WalkerCallback) => void +} & { + [type in keyof AggregateType]?: (node: AggregateType[type], state: TState, callback: WalkerCallback) => void +} + +export type FindPredicate = (type: string, node: acorn.Node) => boolean + +export interface Found { + node: acorn.Node, + state: TState +} + +/** + * does a 'simple' walk over a tree + * @param node the AST node to walk + * @param visitors an object with properties whose names correspond to node types in the {@link https://github.com/estree/estree | ESTree spec}. The properties should contain functions that will be called with the node object and, if applicable the state at that point. + * @param base a walker algorithm + * @param state a start state. The default walker will simply visit all statements and expressions and not produce a meaningful state. (An example of a use of state is to track scope at each point in the tree.) + */ +export function simple( + node: acorn.Node, + visitors: SimpleVisitors, + base?: RecursiveVisitors, + state?: TState +): void + +/** + * does a 'simple' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. + * @param node + * @param visitors + * @param base + * @param state + */ +export function ancestor( + node: acorn.Node, + visitors: AncestorVisitors, + base?: RecursiveVisitors, + state?: TState + ): void + +/** + * does a 'recursive' walk, where the walker functions are responsible for continuing the walk on the child nodes of their target node. + * @param node + * @param state the start state + * @param functions contain an object that maps node types to walker functions + * @param base provides the fallback walker functions for node types that aren't handled in the {@link functions} object. If not given, the default walkers will be used. + */ +export function recursive( + node: acorn.Node, + state: TState, + functions: RecursiveVisitors, + base?: RecursiveVisitors +): void + +/** + * does a 'full' walk over a tree, calling the {@link callback} with the arguments (node, state, type) for each node + * @param node + * @param callback + * @param base + * @param state + */ +export function full( + node: acorn.Node, + callback: FullWalkerCallback, + base?: RecursiveVisitors, + state?: TState +): void + +/** + * does a 'full' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. + * @param node + * @param callback + * @param base + * @param state + */ +export function fullAncestor( + node: acorn.Node, + callback: FullAncestorWalkerCallback, + base?: RecursiveVisitors, + state?: TState +): void + +/** + * builds a new walker object by using the walker functions in {@link functions} and filling in the missing ones by taking defaults from {@link base}. + * @param functions + * @param base + */ +export function make( + functions: RecursiveVisitors, + base?: RecursiveVisitors +): RecursiveVisitors + +/** + * tries to locate a node in a tree at the given start and/or end offsets, which satisfies the predicate test. {@link start} and {@link end} can be either `null` (as wildcard) or a `number`. {@link test} may be a string (indicating a node type) or a function that takes (nodeType, node) arguments and returns a boolean indicating whether this node is interesting. {@link base} and {@link state} are optional, and can be used to specify a custom walker. Nodes are tested from inner to outer, so if two nodes match the boundaries, the inner one will be preferred. + * @param node + * @param start + * @param end + * @param type + * @param base + * @param state + */ +export function findNodeAt( + node: acorn.Node, + start: number | undefined, + end?: number | undefined, + type?: FindPredicate | string, + base?: RecursiveVisitors, + state?: TState +): Found | undefined + +/** + * like {@link findNodeAt}, but will match any node that exists 'around' (spanning) the given position. + * @param node + * @param start + * @param type + * @param base + * @param state + */ +export function findNodeAround( + node: acorn.Node, + start: number | undefined, + type?: FindPredicate | string, + base?: RecursiveVisitors, + state?: TState +): Found | undefined + +/** + * Find the outermost matching node after a given position. + */ +export const findNodeAfter: typeof findNodeAround + +/** + * Find the outermost matching node before a given position. + */ +export const findNodeBefore: typeof findNodeAround + +export const base: RecursiveVisitors diff --git a/web/node_modules/acorn-walk/dist/walk.d.ts b/web/node_modules/acorn-walk/dist/walk.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e07a6afaf8e336137fe00b1321f6de3b7f0085ea --- /dev/null +++ b/web/node_modules/acorn-walk/dist/walk.d.ts @@ -0,0 +1,177 @@ +import * as acorn from "acorn" + +export type FullWalkerCallback = ( + node: acorn.Node, + state: TState, + type: string +) => void + +export type FullAncestorWalkerCallback = ( + node: acorn.Node, + state: TState, + ancestors: acorn.Node[], + type: string +) => void + +type AggregateType = { + Expression: acorn.Expression, + Statement: acorn.Statement, + Function: acorn.Function, + Class: acorn.Class, + Pattern: acorn.Pattern, + ForInit: acorn.VariableDeclaration | acorn.Expression +} + +export type SimpleVisitors = { + [type in acorn.AnyNode["type"]]?: (node: Extract, state: TState) => void +} & { + [type in keyof AggregateType]?: (node: AggregateType[type], state: TState) => void +} + +export type AncestorVisitors = { + [type in acorn.AnyNode["type"]]?: ( node: Extract, state: TState, ancestors: acorn.Node[] +) => void +} & { + [type in keyof AggregateType]?: (node: AggregateType[type], state: TState, ancestors: acorn.Node[]) => void +} + +export type WalkerCallback = (node: acorn.Node, state: TState) => void + +export type RecursiveVisitors = { + [type in acorn.AnyNode["type"]]?: ( node: Extract, state: TState, callback: WalkerCallback) => void +} & { + [type in keyof AggregateType]?: (node: AggregateType[type], state: TState, callback: WalkerCallback) => void +} + +export type FindPredicate = (type: string, node: acorn.Node) => boolean + +export interface Found { + node: acorn.Node, + state: TState +} + +/** + * does a 'simple' walk over a tree + * @param node the AST node to walk + * @param visitors an object with properties whose names correspond to node types in the {@link https://github.com/estree/estree | ESTree spec}. The properties should contain functions that will be called with the node object and, if applicable the state at that point. + * @param base a walker algorithm + * @param state a start state. The default walker will simply visit all statements and expressions and not produce a meaningful state. (An example of a use of state is to track scope at each point in the tree.) + */ +export function simple( + node: acorn.Node, + visitors: SimpleVisitors, + base?: RecursiveVisitors, + state?: TState +): void + +/** + * does a 'simple' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. + * @param node + * @param visitors + * @param base + * @param state + */ +export function ancestor( + node: acorn.Node, + visitors: AncestorVisitors, + base?: RecursiveVisitors, + state?: TState + ): void + +/** + * does a 'recursive' walk, where the walker functions are responsible for continuing the walk on the child nodes of their target node. + * @param node + * @param state the start state + * @param functions contain an object that maps node types to walker functions + * @param base provides the fallback walker functions for node types that aren't handled in the {@link functions} object. If not given, the default walkers will be used. + */ +export function recursive( + node: acorn.Node, + state: TState, + functions: RecursiveVisitors, + base?: RecursiveVisitors +): void + +/** + * does a 'full' walk over a tree, calling the {@link callback} with the arguments (node, state, type) for each node + * @param node + * @param callback + * @param base + * @param state + */ +export function full( + node: acorn.Node, + callback: FullWalkerCallback, + base?: RecursiveVisitors, + state?: TState +): void + +/** + * does a 'full' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. + * @param node + * @param callback + * @param base + * @param state + */ +export function fullAncestor( + node: acorn.Node, + callback: FullAncestorWalkerCallback, + base?: RecursiveVisitors, + state?: TState +): void + +/** + * builds a new walker object by using the walker functions in {@link functions} and filling in the missing ones by taking defaults from {@link base}. + * @param functions + * @param base + */ +export function make( + functions: RecursiveVisitors, + base?: RecursiveVisitors +): RecursiveVisitors + +/** + * tries to locate a node in a tree at the given start and/or end offsets, which satisfies the predicate test. {@link start} and {@link end} can be either `null` (as wildcard) or a `number`. {@link test} may be a string (indicating a node type) or a function that takes (nodeType, node) arguments and returns a boolean indicating whether this node is interesting. {@link base} and {@link state} are optional, and can be used to specify a custom walker. Nodes are tested from inner to outer, so if two nodes match the boundaries, the inner one will be preferred. + * @param node + * @param start + * @param end + * @param type + * @param base + * @param state + */ +export function findNodeAt( + node: acorn.Node, + start: number | undefined, + end?: number | undefined, + type?: FindPredicate | string, + base?: RecursiveVisitors, + state?: TState +): Found | undefined + +/** + * like {@link findNodeAt}, but will match any node that exists 'around' (spanning) the given position. + * @param node + * @param start + * @param type + * @param base + * @param state + */ +export function findNodeAround( + node: acorn.Node, + start: number | undefined, + type?: FindPredicate | string, + base?: RecursiveVisitors, + state?: TState +): Found | undefined + +/** + * Find the outermost matching node after a given position. + */ +export const findNodeAfter: typeof findNodeAround + +/** + * Find the outermost matching node before a given position. + */ +export const findNodeBefore: typeof findNodeAround + +export const base: RecursiveVisitors diff --git a/web/node_modules/acorn-walk/dist/walk.js b/web/node_modules/acorn-walk/dist/walk.js new file mode 100644 index 0000000000000000000000000000000000000000..580df6413725f8f085ae3af9f878320afaff2022 --- /dev/null +++ b/web/node_modules/acorn-walk/dist/walk.js @@ -0,0 +1,461 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {}))); +})(this, (function (exports) { 'use strict'; + + // AST walker module for ESTree compatible trees + + // A simple walk is one where you simply specify callbacks to be + // called on specific nodes. The last two arguments are optional. A + // simple use would be + // + // walk.simple(myTree, { + // Expression: function(node) { ... } + // }); + // + // to do something with all expressions. All ESTree node types + // can be used to identify node types, as well as Expression and + // Statement, which denote categories of nodes. + // + // The base argument can be used to pass a custom (recursive) + // walker, and state can be used to give this walked an initial + // state. + + function simple(node, visitors, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type; + baseVisitor[type](node, st, c); + if (visitors[type]) { visitors[type](node, st); } + })(node, state, override); + } + + // An ancestor walk keeps an array of ancestor nodes (including the + // current node) and passes them to the callback as third parameter + // (and also as state parameter when no other state is present). + function ancestor(node, visitors, baseVisitor, state, override) { + var ancestors = []; + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (visitors[type]) { visitors[type](node, st || ancestors, ancestors); } + if (isNew) { ancestors.pop(); } + })(node, state, override); + } + + // A recursive walk is one where your functions override the default + // walkers. They can modify and replace the state parameter that's + // threaded through the walk, and can opt how and whether to walk + // their child nodes (by calling their third argument on these + // nodes). + function recursive(node, state, funcs, baseVisitor, override) { + var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor + ;(function c(node, st, override) { + visitor[override || node.type](node, st, c); + })(node, state, override); + } + + function makeTest(test) { + if (typeof test === "string") + { return function (type) { return type === test; } } + else if (!test) + { return function () { return true; } } + else + { return test } + } + + var Found = function Found(node, state) { this.node = node; this.state = state; }; + + // A full walk triggers the callback on each node + function full(node, callback, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base; } + var last + ;(function c(node, st, override) { + var type = override || node.type; + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st, type); + last = node; + } + })(node, state, override); + } + + // An fullAncestor walk is like an ancestor walk, but triggers + // the callback on each node + function fullAncestor(node, callback, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + var ancestors = [], last + ;(function c(node, st, override) { + var type = override || node.type; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st || ancestors, ancestors, type); + last = node; + } + if (isNew) { ancestors.pop(); } + })(node, state); + } + + // Find a node with a given start, end, and type (all are optional, + // null can be used as wildcard). Returns a {node, state} object, or + // undefined when it doesn't find a matching node. + function findNodeAt(node, start, end, test, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + test = makeTest(test); + try { + (function c(node, st, override) { + var type = override || node.type; + if ((start == null || node.start <= start) && + (end == null || node.end >= end)) + { baseVisitor[type](node, st, c); } + if ((start == null || node.start === start) && + (end == null || node.end === end) && + test(type, node)) + { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } + } + + // Find the innermost node of a given type that contains the given + // position. Interface similar to findNodeAt. + function findNodeAround(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + var type = override || node.type; + if (node.start > pos || node.end < pos) { return } + baseVisitor[type](node, st, c); + if (test(type, node)) { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } + } + + // Find the outermost matching node after a given position. + function findNodeAfter(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + if (node.end < pos) { return } + var type = override || node.type; + if (node.start >= pos && test(type, node)) { throw new Found(node, st) } + baseVisitor[type](node, st, c); + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } + } + + // Find the outermost matching node before a given position. + function findNodeBefore(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + var max + ;(function c(node, st, override) { + if (node.start > pos) { return } + var type = override || node.type; + if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) + { max = new Found(node, st); } + baseVisitor[type](node, st, c); + })(node, state); + return max + } + + // Used to create a custom walker. Will fill in all missing node + // type properties with the defaults. + function make(funcs, baseVisitor) { + var visitor = Object.create(baseVisitor || base); + for (var type in funcs) { visitor[type] = funcs[type]; } + return visitor + } + + function skipThrough(node, st, c) { c(node, st); } + function ignore(_node, _st, _c) {} + + // Node walkers. + + var base = {}; + + base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var stmt = list[i]; + + c(stmt, st, "Statement"); + } + }; + base.Statement = skipThrough; + base.EmptyStatement = ignore; + base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = + function (node, st, c) { return c(node.expression, st, "Expression"); }; + base.IfStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) { c(node.alternate, st, "Statement"); } + }; + base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; + base.BreakStatement = base.ContinueStatement = ignore; + base.WithStatement = function (node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); + }; + base.SwitchStatement = function (node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { + var cs = list$1[i$1]; + + if (cs.test) { c(cs.test, st, "Expression"); } + for (var i = 0, list = cs.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } + } + }; + base.SwitchCase = function (node, st, c) { + if (node.test) { c(node.test, st, "Expression"); } + for (var i = 0, list = node.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } + }; + base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { + if (node.argument) { c(node.argument, st, "Expression"); } + }; + base.ThrowStatement = base.SpreadElement = + function (node, st, c) { return c(node.argument, st, "Expression"); }; + base.TryStatement = function (node, st, c) { + c(node.block, st, "Statement"); + if (node.handler) { c(node.handler, st); } + if (node.finalizer) { c(node.finalizer, st, "Statement"); } + }; + base.CatchClause = function (node, st, c) { + if (node.param) { c(node.param, st, "Pattern"); } + c(node.body, st, "Statement"); + }; + base.WhileStatement = base.DoWhileStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); + }; + base.ForStatement = function (node, st, c) { + if (node.init) { c(node.init, st, "ForInit"); } + if (node.test) { c(node.test, st, "Expression"); } + if (node.update) { c(node.update, st, "Expression"); } + c(node.body, st, "Statement"); + }; + base.ForInStatement = base.ForOfStatement = function (node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); + }; + base.ForInit = function (node, st, c) { + if (node.type === "VariableDeclaration") { c(node, st); } + else { c(node, st, "Expression"); } + }; + base.DebuggerStatement = ignore; + + base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; + base.VariableDeclaration = function (node, st, c) { + for (var i = 0, list = node.declarations; i < list.length; i += 1) + { + var decl = list[i]; + + c(decl, st); + } + }; + base.VariableDeclarator = function (node, st, c) { + c(node.id, st, "Pattern"); + if (node.init) { c(node.init, st, "Expression"); } + }; + + base.Function = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + c(param, st, "Pattern"); + } + c(node.body, st, node.expression ? "Expression" : "Statement"); + }; + + base.Pattern = function (node, st, c) { + if (node.type === "Identifier") + { c(node, st, "VariablePattern"); } + else if (node.type === "MemberExpression") + { c(node, st, "MemberPattern"); } + else + { c(node, st); } + }; + base.VariablePattern = ignore; + base.MemberPattern = skipThrough; + base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; + base.ArrayPattern = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Pattern"); } + } + }; + base.ObjectPattern = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + if (prop.type === "Property") { + if (prop.computed) { c(prop.key, st, "Expression"); } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } + }; + + base.Expression = skipThrough; + base.ThisExpression = base.Super = base.MetaProperty = ignore; + base.ArrayExpression = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Expression"); } + } + }; + base.ObjectExpression = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) + { + var prop = list[i]; + + c(prop, st); + } + }; + base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; + base.SequenceExpression = function (node, st, c) { + for (var i = 0, list = node.expressions; i < list.length; i += 1) + { + var expr = list[i]; + + c(expr, st, "Expression"); + } + }; + base.TemplateLiteral = function (node, st, c) { + for (var i = 0, list = node.quasis; i < list.length; i += 1) + { + var quasi = list[i]; + + c(quasi, st); + } + + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) + { + var expr = list$1[i$1]; + + c(expr, st, "Expression"); + } + }; + base.TemplateElement = ignore; + base.UnaryExpression = base.UpdateExpression = function (node, st, c) { + c(node.argument, st, "Expression"); + }; + base.BinaryExpression = base.LogicalExpression = function (node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); + }; + base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { + c(node.left, st, "Pattern"); + c(node.right, st, "Expression"); + }; + base.ConditionalExpression = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); + }; + base.NewExpression = base.CallExpression = function (node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) + { for (var i = 0, list = node.arguments; i < list.length; i += 1) + { + var arg = list[i]; + + c(arg, st, "Expression"); + } } + }; + base.MemberExpression = function (node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) { c(node.property, st, "Expression"); } + }; + base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { + if (node.declaration) + { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } + if (node.source) { c(node.source, st, "Expression"); } + }; + base.ExportAllDeclaration = function (node, st, c) { + if (node.exported) + { c(node.exported, st); } + c(node.source, st, "Expression"); + }; + base.ImportDeclaration = function (node, st, c) { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) + { + var spec = list[i]; + + c(spec, st); + } + c(node.source, st, "Expression"); + }; + base.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); + }; + base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; + + base.TaggedTemplateExpression = function (node, st, c) { + c(node.tag, st, "Expression"); + c(node.quasi, st, "Expression"); + }; + base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; + base.Class = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + if (node.superClass) { c(node.superClass, st, "Expression"); } + c(node.body, st); + }; + base.ClassBody = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var elt = list[i]; + + c(elt, st); + } + }; + base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { + if (node.computed) { c(node.key, st, "Expression"); } + if (node.value) { c(node.value, st, "Expression"); } + }; + + exports.ancestor = ancestor; + exports.base = base; + exports.findNodeAfter = findNodeAfter; + exports.findNodeAround = findNodeAround; + exports.findNodeAt = findNodeAt; + exports.findNodeBefore = findNodeBefore; + exports.full = full; + exports.fullAncestor = fullAncestor; + exports.make = make; + exports.recursive = recursive; + exports.simple = simple; + +})); diff --git a/web/node_modules/acorn-walk/dist/walk.mjs b/web/node_modules/acorn-walk/dist/walk.mjs new file mode 100644 index 0000000000000000000000000000000000000000..19eebc0e70f59857e8ca63285617d8e62e1e8b6f --- /dev/null +++ b/web/node_modules/acorn-walk/dist/walk.mjs @@ -0,0 +1,443 @@ +// AST walker module for ESTree compatible trees + +// A simple walk is one where you simply specify callbacks to be +// called on specific nodes. The last two arguments are optional. A +// simple use would be +// +// walk.simple(myTree, { +// Expression: function(node) { ... } +// }); +// +// to do something with all expressions. All ESTree node types +// can be used to identify node types, as well as Expression and +// Statement, which denote categories of nodes. +// +// The base argument can be used to pass a custom (recursive) +// walker, and state can be used to give this walked an initial +// state. + +function simple(node, visitors, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type; + baseVisitor[type](node, st, c); + if (visitors[type]) { visitors[type](node, st); } + })(node, state, override); +} + +// An ancestor walk keeps an array of ancestor nodes (including the +// current node) and passes them to the callback as third parameter +// (and also as state parameter when no other state is present). +function ancestor(node, visitors, baseVisitor, state, override) { + var ancestors = []; + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (visitors[type]) { visitors[type](node, st || ancestors, ancestors); } + if (isNew) { ancestors.pop(); } + })(node, state, override); +} + +// A recursive walk is one where your functions override the default +// walkers. They can modify and replace the state parameter that's +// threaded through the walk, and can opt how and whether to walk +// their child nodes (by calling their third argument on these +// nodes). +function recursive(node, state, funcs, baseVisitor, override) { + var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor + ;(function c(node, st, override) { + visitor[override || node.type](node, st, c); + })(node, state, override); +} + +function makeTest(test) { + if (typeof test === "string") + { return function (type) { return type === test; } } + else if (!test) + { return function () { return true; } } + else + { return test } +} + +var Found = function Found(node, state) { this.node = node; this.state = state; }; + +// A full walk triggers the callback on each node +function full(node, callback, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base; } + var last + ;(function c(node, st, override) { + var type = override || node.type; + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st, type); + last = node; + } + })(node, state, override); +} + +// An fullAncestor walk is like an ancestor walk, but triggers +// the callback on each node +function fullAncestor(node, callback, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + var ancestors = [], last + ;(function c(node, st, override) { + var type = override || node.type; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st || ancestors, ancestors, type); + last = node; + } + if (isNew) { ancestors.pop(); } + })(node, state); +} + +// Find a node with a given start, end, and type (all are optional, +// null can be used as wildcard). Returns a {node, state} object, or +// undefined when it doesn't find a matching node. +function findNodeAt(node, start, end, test, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + test = makeTest(test); + try { + (function c(node, st, override) { + var type = override || node.type; + if ((start == null || node.start <= start) && + (end == null || node.end >= end)) + { baseVisitor[type](node, st, c); } + if ((start == null || node.start === start) && + (end == null || node.end === end) && + test(type, node)) + { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +// Find the innermost node of a given type that contains the given +// position. Interface similar to findNodeAt. +function findNodeAround(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + var type = override || node.type; + if (node.start > pos || node.end < pos) { return } + baseVisitor[type](node, st, c); + if (test(type, node)) { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +// Find the outermost matching node after a given position. +function findNodeAfter(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + if (node.end < pos) { return } + var type = override || node.type; + if (node.start >= pos && test(type, node)) { throw new Found(node, st) } + baseVisitor[type](node, st, c); + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +// Find the outermost matching node before a given position. +function findNodeBefore(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + var max + ;(function c(node, st, override) { + if (node.start > pos) { return } + var type = override || node.type; + if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) + { max = new Found(node, st); } + baseVisitor[type](node, st, c); + })(node, state); + return max +} + +// Used to create a custom walker. Will fill in all missing node +// type properties with the defaults. +function make(funcs, baseVisitor) { + var visitor = Object.create(baseVisitor || base); + for (var type in funcs) { visitor[type] = funcs[type]; } + return visitor +} + +function skipThrough(node, st, c) { c(node, st); } +function ignore(_node, _st, _c) {} + +// Node walkers. + +var base = {}; + +base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var stmt = list[i]; + + c(stmt, st, "Statement"); + } +}; +base.Statement = skipThrough; +base.EmptyStatement = ignore; +base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = + function (node, st, c) { return c(node.expression, st, "Expression"); }; +base.IfStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) { c(node.alternate, st, "Statement"); } +}; +base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; +base.BreakStatement = base.ContinueStatement = ignore; +base.WithStatement = function (node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.SwitchStatement = function (node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { + var cs = list$1[i$1]; + + if (cs.test) { c(cs.test, st, "Expression"); } + for (var i = 0, list = cs.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } + } +}; +base.SwitchCase = function (node, st, c) { + if (node.test) { c(node.test, st, "Expression"); } + for (var i = 0, list = node.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } +}; +base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { + if (node.argument) { c(node.argument, st, "Expression"); } +}; +base.ThrowStatement = base.SpreadElement = + function (node, st, c) { return c(node.argument, st, "Expression"); }; +base.TryStatement = function (node, st, c) { + c(node.block, st, "Statement"); + if (node.handler) { c(node.handler, st); } + if (node.finalizer) { c(node.finalizer, st, "Statement"); } +}; +base.CatchClause = function (node, st, c) { + if (node.param) { c(node.param, st, "Pattern"); } + c(node.body, st, "Statement"); +}; +base.WhileStatement = base.DoWhileStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForStatement = function (node, st, c) { + if (node.init) { c(node.init, st, "ForInit"); } + if (node.test) { c(node.test, st, "Expression"); } + if (node.update) { c(node.update, st, "Expression"); } + c(node.body, st, "Statement"); +}; +base.ForInStatement = base.ForOfStatement = function (node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForInit = function (node, st, c) { + if (node.type === "VariableDeclaration") { c(node, st); } + else { c(node, st, "Expression"); } +}; +base.DebuggerStatement = ignore; + +base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; +base.VariableDeclaration = function (node, st, c) { + for (var i = 0, list = node.declarations; i < list.length; i += 1) + { + var decl = list[i]; + + c(decl, st); + } +}; +base.VariableDeclarator = function (node, st, c) { + c(node.id, st, "Pattern"); + if (node.init) { c(node.init, st, "Expression"); } +}; + +base.Function = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + c(param, st, "Pattern"); + } + c(node.body, st, node.expression ? "Expression" : "Statement"); +}; + +base.Pattern = function (node, st, c) { + if (node.type === "Identifier") + { c(node, st, "VariablePattern"); } + else if (node.type === "MemberExpression") + { c(node, st, "MemberPattern"); } + else + { c(node, st); } +}; +base.VariablePattern = ignore; +base.MemberPattern = skipThrough; +base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; +base.ArrayPattern = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Pattern"); } + } +}; +base.ObjectPattern = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + if (prop.type === "Property") { + if (prop.computed) { c(prop.key, st, "Expression"); } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } +}; + +base.Expression = skipThrough; +base.ThisExpression = base.Super = base.MetaProperty = ignore; +base.ArrayExpression = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Expression"); } + } +}; +base.ObjectExpression = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) + { + var prop = list[i]; + + c(prop, st); + } +}; +base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; +base.SequenceExpression = function (node, st, c) { + for (var i = 0, list = node.expressions; i < list.length; i += 1) + { + var expr = list[i]; + + c(expr, st, "Expression"); + } +}; +base.TemplateLiteral = function (node, st, c) { + for (var i = 0, list = node.quasis; i < list.length; i += 1) + { + var quasi = list[i]; + + c(quasi, st); + } + + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) + { + var expr = list$1[i$1]; + + c(expr, st, "Expression"); + } +}; +base.TemplateElement = ignore; +base.UnaryExpression = base.UpdateExpression = function (node, st, c) { + c(node.argument, st, "Expression"); +}; +base.BinaryExpression = base.LogicalExpression = function (node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); +}; +base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { + c(node.left, st, "Pattern"); + c(node.right, st, "Expression"); +}; +base.ConditionalExpression = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); +}; +base.NewExpression = base.CallExpression = function (node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) + { for (var i = 0, list = node.arguments; i < list.length; i += 1) + { + var arg = list[i]; + + c(arg, st, "Expression"); + } } +}; +base.MemberExpression = function (node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) { c(node.property, st, "Expression"); } +}; +base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { + if (node.declaration) + { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } + if (node.source) { c(node.source, st, "Expression"); } +}; +base.ExportAllDeclaration = function (node, st, c) { + if (node.exported) + { c(node.exported, st); } + c(node.source, st, "Expression"); +}; +base.ImportDeclaration = function (node, st, c) { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) + { + var spec = list[i]; + + c(spec, st); + } + c(node.source, st, "Expression"); +}; +base.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); +}; +base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; + +base.TaggedTemplateExpression = function (node, st, c) { + c(node.tag, st, "Expression"); + c(node.quasi, st, "Expression"); +}; +base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; +base.Class = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + if (node.superClass) { c(node.superClass, st, "Expression"); } + c(node.body, st); +}; +base.ClassBody = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var elt = list[i]; + + c(elt, st); + } +}; +base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { + if (node.computed) { c(node.key, st, "Expression"); } + if (node.value) { c(node.value, st, "Expression"); } +}; + +export { ancestor, base, findNodeAfter, findNodeAround, findNodeAt, findNodeBefore, full, fullAncestor, make, recursive, simple }; diff --git a/web/node_modules/acorn-walk/package.json b/web/node_modules/acorn-walk/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9d3b7e5248fb837067e4f6610ff4a7afc773dd51 --- /dev/null +++ b/web/node_modules/acorn-walk/package.json @@ -0,0 +1,47 @@ +{ + "name": "acorn-walk", + "description": "ECMAScript (ESTree) AST walker", + "homepage": "https://github.com/acornjs/acorn", + "main": "dist/walk.js", + "types": "dist/walk.d.ts", + "module": "dist/walk.mjs", + "exports": { + ".": [ + { + "import": "./dist/walk.mjs", + "require": "./dist/walk.js", + "default": "./dist/walk.js" + }, + "./dist/walk.js" + ], + "./package.json": "./package.json" + }, + "version": "8.3.2", + "engines": { + "node": ">=0.4.0" + }, + "maintainers": [ + { + "name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "web": "https://marijnhaverbeke.nl" + }, + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "web": "https://rreverser.com/" + }, + { + "name": "Adrian Heine", + "web": "http://adrianheine.de" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/acornjs/acorn.git" + }, + "scripts": { + "prepare": "cd ..; npm run build:walk" + }, + "license": "MIT" +} diff --git a/web/node_modules/acorn/CHANGELOG.md b/web/node_modules/acorn/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..eb848a58b8a091e66932dafa949fd827f62d0a59 --- /dev/null +++ b/web/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,880 @@ +## 8.11.3 (2023-12-29) + +### Bug fixes + +Add `Function` and `Class` to the `AggregateType` type, so that they can be used in walkers without raising a type error. + +Make sure `onToken` get an `import` keyword token when parsing `import.meta`. + +Fix a bug where `.loc.start` could be undefined for `new.target` `meta` nodes. + +## 8.11.2 (2023-10-27) + +### Bug fixes + +Fix a bug that caused regular expressions after colon tokens to not be properly tokenized in some circumstances. + +## 8.11.1 (2023-10-26) + +### Bug fixes + +Fix a regression where `onToken` would receive 'name' tokens for 'new' keyword tokens. + +## 8.11.0 (2023-10-26) + +### Bug fixes + +Fix an issue where tokenizing (without parsing) an object literal with a property named `class` or `function` could, in some circumstance, put the tokenizer into an invalid state. + +Fix an issue where a slash after a call to a propery named the same as some keywords would be tokenized as a regular expression. + +### New features + +Upgrade to Unicode 15.1. + +Use a set of new, much more precise, TypeScript types. + +## 8.10.0 (2023-07-05) + +### New features + +Add a `checkPrivateFields` option that disables strict checking of private property use. + +## 8.9.0 (2023-06-16) + +### Bug fixes + +Forbid dynamic import after `new`, even when part of a member expression. + +### New features + +Add Unicode properties for ES2023. + +Add support for the `v` flag to regular expressions. + +## 8.8.2 (2023-01-23) + +### Bug fixes + +Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`. + +Fix an exception when passing no option object to `parse` or `new Parser`. + +Fix incorrect parse error on `if (0) let\n[astral identifier char]`. + +## 8.8.1 (2022-10-24) + +### Bug fixes + +Make type for `Comment` compatible with estree types. + +## 8.8.0 (2022-07-21) + +### Bug fixes + +Allow parentheses around spread args in destructuring object assignment. + +Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them. + +### New features + +Support hashbang comments by default in ECMAScript 2023 and later. + +## 8.7.1 (2021-04-26) + +### Bug fixes + +Stop handling `"use strict"` directives in ECMAScript versions before 5. + +Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked. + +Add missing type for `tokTypes`. + +## 8.7.0 (2021-12-27) + +### New features + +Support quoted export names. + +Upgrade to Unicode 14. + +Add support for Unicode 13 properties in regular expressions. + +### Bug fixes + +Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code. + +## 8.6.0 (2021-11-18) + +### Bug fixes + +Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment. + +### New features + +Support class private fields with the `in` operator. + +## 8.5.0 (2021-09-06) + +### Bug fixes + +Improve context-dependent tokenization in a number of corner cases. + +Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number). + +Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators. + +Fix wrong end locations stored on SequenceExpression nodes. + +Implement restriction that `for`/`of` loop LHS can't start with `let`. + +### New features + +Add support for ES2022 class static blocks. + +Allow multiple input files to be passed to the CLI tool. + +## 8.4.1 (2021-06-24) + +### Bug fixes + +Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources. + +## 8.4.0 (2021-06-11) + +### New features + +A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context. + +## 8.3.0 (2021-05-31) + +### New features + +Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher. + +Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag. + +## 8.2.4 (2021-05-04) + +### Bug fixes + +Fix spec conformity in corner case 'for await (async of ...)'. + +## 8.2.3 (2021-05-04) + +### Bug fixes + +Fix an issue where the library couldn't parse 'for (async of ...)'. + +Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances. + +## 8.2.2 (2021-04-29) + +### Bug fixes + +Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield. + +## 8.2.1 (2021-04-24) + +### Bug fixes + +Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse. + +## 8.2.0 (2021-04-24) + +### New features + +Add support for ES2022 class fields and private methods. + +## 8.1.1 (2021-04-12) + +### Various + +Stop shipping source maps in the NPM package. + +## 8.1.0 (2021-03-09) + +### Bug fixes + +Fix a spurious error in nested destructuring arrays. + +### New features + +Expose `allowAwaitOutsideFunction` in CLI interface. + +Make `allowImportExportAnywhere` also apply to `import.meta`. + +## 8.0.5 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.4 (2020-10-05) + +### Bug fixes + +Make `await x ** y` an error, following the spec. + +Fix potentially exponential regular expression. + +## 8.0.3 (2020-10-02) + +### Bug fixes + +Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`. + +## 8.0.2 (2020-09-30) + +### Bug fixes + +Make the TypeScript types reflect the current allowed values for `ecmaVersion`. + +Fix another regexp/division tokenizer issue. + +## 8.0.1 (2020-08-12) + +### Bug fixes + +Provide the correct value in the `version` export. + +## 8.0.0 (2020-08-12) + +### Bug fixes + +Disallow expressions like `(a = b) = c`. + +Make non-octal escape sequences a syntax error in strict mode. + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +Update to the set of Unicode properties from ES2021. + +### Breaking changes + +The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release. + +Some changes to method signatures that may be used by plugins. + +## 7.4.0 (2020-08-03) + +### New features + +Add support for logical assignment operators. + +Add support for numeric separators. + +## 7.3.1 (2020-06-11) + +### Bug fixes + +Make the string in the `version` export match the actual library version. + +## 7.3.0 (2020-06-11) + +### Bug fixes + +Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail. + +### New features + +Add support for optional chaining (`?.`). + +## 7.2.0 (2020-05-09) + +### Bug fixes + +Fix precedence issue in parsing of async arrow functions. + +### New features + +Add support for nullish coalescing. + +Add support for `import.meta`. + +Support `export * as ...` syntax. + +Upgrade to Unicode 13. + +## 6.4.1 (2020-03-09) + +### Bug fixes + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.1 (2020-03-01) + +### Bug fixes + +Treat `\8` and `\9` as invalid escapes in template strings. + +Allow unicode escapes in property names that are keywords. + +Don't error on an exponential operator expression as argument to `await`. + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.0 (2019-09-24) + +### Bug fixes + +Disallow trailing object literal commas when ecmaVersion is less than 5. + +### New features + +Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on. + +## 7.0.0 (2019-08-13) + +### Breaking changes + +Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression). + +Makes 10 (ES2019) the default value for the `ecmaVersion` option. + +## 6.3.0 (2019-08-12) + +### New features + +`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard. + +## 6.2.1 (2019-07-21) + +### Bug fixes + +Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such. + +Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances. + +## 6.2.0 (2019-07-04) + +### Bug fixes + +Improve valid assignment checking in `for`/`in` and `for`/`of` loops. + +Disallow binding `let` in patterns. + +### New features + +Support bigint syntax with `ecmaVersion` >= 11. + +Support dynamic `import` syntax with `ecmaVersion` >= 11. + +Upgrade to Unicode version 12. + +## 6.1.1 (2019-02-27) + +### Bug fixes + +Fix bug that caused parsing default exports of with names to fail. + +## 6.1.0 (2019-02-08) + +### Bug fixes + +Fix scope checking when redefining a `var` as a lexical binding. + +### New features + +Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. + +## 6.0.7 (2019-02-04) + +### Bug fixes + +Check that exported bindings are defined. + +Don't treat `\u180e` as a whitespace character. + +Check for duplicate parameter names in methods. + +Don't allow shorthand properties when they are generators or async methods. + +Forbid binding `await` in async arrow function's parameter list. + +## 6.0.6 (2019-01-30) + +### Bug fixes + +The content of class declarations and expressions is now always parsed in strict mode. + +Don't allow `let` or `const` to bind the variable name `let`. + +Treat class declarations as lexical. + +Don't allow a generator function declaration as the sole body of an `if` or `else`. + +Ignore `"use strict"` when after an empty statement. + +Allow string line continuations with special line terminator characters. + +Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. + +Fix bug with parsing `yield` in a `for` loop initializer. + +Implement special cases around scope checking for functions. + +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/web/node_modules/acorn/LICENSE b/web/node_modules/acorn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9d71cc63a35e7d878787e5159b5b163739486220 --- /dev/null +++ b/web/node_modules/acorn/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2022 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/web/node_modules/acorn/README.md b/web/node_modules/acorn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cfc51b384a3e2bb3cf8de57c82bc133fb74f7aaf --- /dev/null +++ b/web/node_modules/acorn/README.md @@ -0,0 +1,283 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` must be an object setting +some of the options listed below. The return value will be an abstract +syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +let acorn = require("acorn"); +console.log(acorn.parse("1 + 1", {ecmaVersion: 2020})); +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options are provided by in a second argument, which should be an +object containing any of these fields (only `ecmaVersion` is +required): + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be + either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019), + 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` (the + latest the library supports). This influences support for strict + mode, the set of reserved words, and support for new syntax + features. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features must be + implemented through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"` or `"module"`. This influences global strict mode + and parsing of `import` and `export` declarations. + + **NOTE**: If set to `"module"`, then static `import` / `export` syntax + will be valid, even if `ecmaVersion` is less than 6. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed, + and also allows `import.meta` expressions to appear in scripts + (when `sourceType` is not `"module"`). + +- **allowAwaitOutsideFunction**: If `false`, `await` expressions can + only appear inside `async` functions. Defaults to `true` in modules + for `ecmaVersion` 2022 and later, `false` for lower versions. + Setting this option to `true` allows to have top-level `await` + expressions. They are still not allowed in non-`async` functions, + though. + +- **allowSuperOutsideMethod**: By default, `super` outside a method + raises an error. Set this to `true` to accept such code. + +- **allowHashBang**: When this is enabled, if the code starts with the + characters `#!` (as in a shellscript), the first line will be + treated as a comment. Defaults to true when `ecmaVersion` >= 2023. + +- **checkPrivateFields**: By default, the parser will verify that + private properties are only used in places where they are valid and + have been declared. Set this to false to turn such checks off. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +Note that tokenizing JavaScript without parsing it is, in modern +versions of the language, not really possible due to the way syntax is +overloaded in ways that can only be disambiguated by the parse +context. This package applies a bunch of heuristics to try and do a +reasonable job, but you are advised to use `parse` with the `onToken` +option instead of this. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)]; +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +var JSXParser = acorn.Parser.extend(jsx()); +JSXParser.parse("foo()", {ecmaVersion: 2020}); +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--allow-await-outside-function`: Allows top-level `await` expressions. + See the `allowAwaitOutsideFunction` option for more information. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) diff --git a/web/node_modules/acorn/bin/acorn b/web/node_modules/acorn/bin/acorn new file mode 100644 index 0000000000000000000000000000000000000000..3ef3c124b08bd4fb0f27cd13301dfeeae4a6464c --- /dev/null +++ b/web/node_modules/acorn/bin/acorn @@ -0,0 +1,4 @@ +#!/usr/bin/env node +"use strict" + +require("../dist/bin.js") diff --git a/web/node_modules/acorn/dist/acorn.d.mts b/web/node_modules/acorn/dist/acorn.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6ad58121195c96dab6b6c704ae0c0a31fefc2778 --- /dev/null +++ b/web/node_modules/acorn/dist/acorn.d.mts @@ -0,0 +1,857 @@ +export interface Node { + start: number + end: number + type: string + range?: [number, number] + loc?: SourceLocation | null +} + +export interface SourceLocation { + source?: string | null + start: Position + end: Position +} + +export interface Position { + /** 1-based */ + line: number + /** 0-based */ + column: number +} + +export interface Identifier extends Node { + type: "Identifier" + name: string +} + +export interface Literal extends Node { + type: "Literal" + value?: string | boolean | null | number | RegExp | bigint + raw?: string + regex?: { + pattern: string + flags: string + } + bigint?: string +} + +export interface Program extends Node { + type: "Program" + body: Array + sourceType: "script" | "module" +} + +export interface Function extends Node { + id?: Identifier | null + params: Array + body: BlockStatement | Expression + generator: boolean + expression: boolean + async: boolean +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement" + expression: Expression | Literal + directive?: string +} + +export interface BlockStatement extends Node { + type: "BlockStatement" + body: Array +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement" +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement" +} + +export interface WithStatement extends Node { + type: "WithStatement" + object: Expression + body: Statement +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement" + argument?: Expression | null +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement" + label: Identifier + body: Statement +} + +export interface BreakStatement extends Node { + type: "BreakStatement" + label?: Identifier | null +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement" + label?: Identifier | null +} + +export interface IfStatement extends Node { + type: "IfStatement" + test: Expression + consequent: Statement + alternate?: Statement | null +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement" + discriminant: Expression + cases: Array +} + +export interface SwitchCase extends Node { + type: "SwitchCase" + test?: Expression | null + consequent: Array +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement" + argument: Expression +} + +export interface TryStatement extends Node { + type: "TryStatement" + block: BlockStatement + handler?: CatchClause | null + finalizer?: BlockStatement | null +} + +export interface CatchClause extends Node { + type: "CatchClause" + param?: Pattern | null + body: BlockStatement +} + +export interface WhileStatement extends Node { + type: "WhileStatement" + test: Expression + body: Statement +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement" + body: Statement + test: Expression +} + +export interface ForStatement extends Node { + type: "ForStatement" + init?: VariableDeclaration | Expression | null + test?: Expression | null + update?: Expression | null + body: Statement +} + +export interface ForInStatement extends Node { + type: "ForInStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement +} + +export interface FunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: Identifier + body: BlockStatement +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration" + declarations: Array + kind: "var" | "let" | "const" +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator" + id: Pattern + init?: Expression | null +} + +export interface ThisExpression extends Node { + type: "ThisExpression" +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression" + elements: Array +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression" + properties: Array +} + +export interface Property extends Node { + type: "Property" + key: Expression + value: Expression + kind: "init" | "get" | "set" + method: boolean + shorthand: boolean + computed: boolean +} + +export interface FunctionExpression extends Function { + type: "FunctionExpression" + body: BlockStatement +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression" + operator: UnaryOperator + prefix: boolean + argument: Expression +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" + +export interface UpdateExpression extends Node { + type: "UpdateExpression" + operator: UpdateOperator + argument: Expression + prefix: boolean +} + +export type UpdateOperator = "++" | "--" + +export interface BinaryExpression extends Node { + type: "BinaryExpression" + operator: BinaryOperator + left: Expression | PrivateIdentifier + right: Expression +} + +export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**" + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression" + operator: AssignmentOperator + left: Pattern + right: Expression +} + +export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??=" + +export interface LogicalExpression extends Node { + type: "LogicalExpression" + operator: LogicalOperator + left: Expression + right: Expression +} + +export type LogicalOperator = "||" | "&&" | "??" + +export interface MemberExpression extends Node { + type: "MemberExpression" + object: Expression | Super + property: Expression | PrivateIdentifier + computed: boolean + optional: boolean +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression" + test: Expression + alternate: Expression + consequent: Expression +} + +export interface CallExpression extends Node { + type: "CallExpression" + callee: Expression | Super + arguments: Array + optional: boolean +} + +export interface NewExpression extends Node { + type: "NewExpression" + callee: Expression + arguments: Array +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression" + expressions: Array +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement + await: boolean +} + +export interface Super extends Node { + type: "Super" +} + +export interface SpreadElement extends Node { + type: "SpreadElement" + argument: Expression +} + +export interface ArrowFunctionExpression extends Function { + type: "ArrowFunctionExpression" +} + +export interface YieldExpression extends Node { + type: "YieldExpression" + argument?: Expression | null + delegate: boolean +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral" + quasis: Array + expressions: Array +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression" + tag: Expression + quasi: TemplateLiteral +} + +export interface TemplateElement extends Node { + type: "TemplateElement" + tail: boolean + value: { + cooked?: string | null + raw: string + } +} + +export interface AssignmentProperty extends Node { + type: "Property" + key: Expression + value: Pattern + kind: "init" + method: false + shorthand: boolean + computed: boolean +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern" + properties: Array +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern" + elements: Array +} + +export interface RestElement extends Node { + type: "RestElement" + argument: Pattern +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern" + left: Pattern + right: Expression +} + +export interface Class extends Node { + id?: Identifier | null + superClass?: Expression | null + body: ClassBody +} + +export interface ClassBody extends Node { + type: "ClassBody" + body: Array +} + +export interface MethodDefinition extends Node { + type: "MethodDefinition" + key: Expression | PrivateIdentifier + value: FunctionExpression + kind: "constructor" | "method" | "get" | "set" + computed: boolean + static: boolean +} + +export interface ClassDeclaration extends Class { + type: "ClassDeclaration" + id: Identifier +} + +export interface ClassExpression extends Class { + type: "ClassExpression" +} + +export interface MetaProperty extends Node { + type: "MetaProperty" + meta: Identifier + property: Identifier +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration" + specifiers: Array + source: Literal +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier" + imported: Identifier | Literal + local: Identifier +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier" + local: Identifier +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier" + local: Identifier +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration" + declaration?: Declaration | null + specifiers: Array + source?: Literal | null +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier" + exported: Identifier | Literal + local: Identifier | Literal +} + +export interface AnonymousFunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: null + body: BlockStatement +} + +export interface AnonymousClassDeclaration extends Class { + type: "ClassDeclaration" + id: null +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration" + declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration" + source: Literal + exported?: Identifier | Literal | null +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression" + argument: Expression +} + +export interface ChainExpression extends Node { + type: "ChainExpression" + expression: MemberExpression | CallExpression +} + +export interface ImportExpression extends Node { + type: "ImportExpression" + source: Expression +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression" + expression: Expression +} + +export interface PropertyDefinition extends Node { + type: "PropertyDefinition" + key: Expression | PrivateIdentifier + value?: Expression | null + computed: boolean + static: boolean +} + +export interface PrivateIdentifier extends Node { + type: "PrivateIdentifier" + name: string +} + +export interface StaticBlock extends Node { + type: "StaticBlock" + body: Array +} + +export type Statement = +| ExpressionStatement +| BlockStatement +| EmptyStatement +| DebuggerStatement +| WithStatement +| ReturnStatement +| LabeledStatement +| BreakStatement +| ContinueStatement +| IfStatement +| SwitchStatement +| ThrowStatement +| TryStatement +| WhileStatement +| DoWhileStatement +| ForStatement +| ForInStatement +| ForOfStatement +| Declaration + +export type Declaration = +| FunctionDeclaration +| VariableDeclaration +| ClassDeclaration + +export type Expression = +| Identifier +| Literal +| ThisExpression +| ArrayExpression +| ObjectExpression +| FunctionExpression +| UnaryExpression +| UpdateExpression +| BinaryExpression +| AssignmentExpression +| LogicalExpression +| MemberExpression +| ConditionalExpression +| CallExpression +| NewExpression +| SequenceExpression +| ArrowFunctionExpression +| YieldExpression +| TemplateLiteral +| TaggedTemplateExpression +| ClassExpression +| MetaProperty +| AwaitExpression +| ChainExpression +| ImportExpression +| ParenthesizedExpression + +export type Pattern = +| Identifier +| MemberExpression +| ObjectPattern +| ArrayPattern +| RestElement +| AssignmentPattern + +export type ModuleDeclaration = +| ImportDeclaration +| ExportNamedDeclaration +| ExportDefaultDeclaration +| ExportAllDeclaration + +export type AnyNode = Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock + +export function parse(input: string, options: Options): Program + +export function parseExpressionAt(input: string, pos: number, options: Options): Expression + +export function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator +} + +export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | "latest" + +export interface Options { + /** + * `ecmaVersion` indicates the ECMAScript version to parse. Must be + * either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + * (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + * (the latest version the library supports). This influences + * support for strict mode, the set of reserved words, and support + * for new syntax features. + */ + ecmaVersion: ecmaVersion + + /** + * `sourceType` indicates the mode the code should be parsed in. + * Can be either `"script"` or `"module"`. This influences global + * strict mode and parsing of `import` and `export` declarations. + */ + sourceType?: "script" | "module" + + /** + * a callback that will be called when a semicolon is automatically inserted. + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if {@link locations} is enabled + */ + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * similar to `onInsertedSemicolon`, but for trailing commas + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if `locations` is enabled + */ + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * By default, reserved words are only enforced if ecmaVersion >= 5. + * Set `allowReserved` to a boolean value to explicitly turn this on + * an off. When this option has the value "never", reserved words + * and keywords can also not be used as property names. + */ + allowReserved?: boolean | "never" + + /** + * When enabled, a return at the top level is not considered an error. + */ + allowReturnOutsideFunction?: boolean + + /** + * When enabled, import/export statements are not constrained to + * appearing at the top of the program, and an import.meta expression + * in a script isn't considered an error. + */ + allowImportExportEverywhere?: boolean + + /** + * By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022. + * When enabled, await identifiers are allowed to appear at the top-level scope, + * but they are still not allowed in non-async functions. + */ + allowAwaitOutsideFunction?: boolean + + /** + * When enabled, super identifiers are not constrained to + * appearing in methods and do not raise an error when they appear elsewhere. + */ + allowSuperOutsideMethod?: boolean + + /** + * When enabled, hashbang directive in the beginning of file is + * allowed and treated as a line comment. Enabled by default when + * {@link ecmaVersion} >= 2023. + */ + allowHashBang?: boolean + + /** + * By default, the parser will verify that private properties are + * only used in places where they are valid and have been declared. + * Set this to false to turn such checks off. + */ + checkPrivateFields?: boolean + + /** + * When `locations` is on, `loc` properties holding objects with + * `start` and `end` properties as {@link Position} objects will be attached to the + * nodes. + */ + locations?: boolean + + /** + * a callback that will cause Acorn to call that export function with object in the same + * format as tokens returned from `tokenizer().getToken()`. Note + * that you are not allowed to call the parser from the + * callback—that will corrupt its internal state. + */ + onToken?: ((token: Token) => void) | Token[] + + + /** + * This takes a export function or an array. + * + * When a export function is passed, Acorn will call that export function with `(block, text, start, + * end)` parameters whenever a comment is skipped. `block` is a + * boolean indicating whether this is a block (`/* *\/`) comment, + * `text` is the content of the comment, and `start` and `end` are + * character offsets that denote the start and end of the comment. + * When the {@link locations} option is on, two more parameters are + * passed, the full locations of {@link Position} export type of the start and + * end of the comments. + * + * When a array is passed, each found comment of {@link Comment} export type is pushed to the array. + * + * Note that you are not allowed to call the + * parser from the callback—that will corrupt its internal state. + */ + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + + /** + * Nodes have their start and end characters offsets recorded in + * `start` and `end` properties (directly on the node, rather than + * the `loc` object, which holds line/column data. To also add a + * [semi-standardized][range] `range` property holding a `[start, + * end]` array with the same numbers, set the `ranges` option to + * `true`. + */ + ranges?: boolean + + /** + * It is possible to parse multiple files into a single AST by + * passing the tree produced by parsing the first file as + * `program` option in subsequent parses. This will add the + * toplevel forms of the parsed file to the `Program` (top) node + * of an existing parse tree. + */ + program?: Node + + /** + * When {@link locations} is on, you can pass this to record the source + * file in every node's `loc` object. + */ + sourceFile?: string + + /** + * This value, if given, is stored in every node, whether {@link locations} is on or off. + */ + directSourceFile?: string + + /** + * When enabled, parenthesized expressions are represented by + * (non-standard) ParenthesizedExpression nodes + */ + preserveParens?: boolean +} + +export class Parser { + options: Options + input: string + + private constructor(options: Options, input: string, startPos?: number) + parse(): Program + + static parse(input: string, options: Options): Program + static parseExpressionAt(input: string, pos: number, options: Options): Expression + static tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser +} + +export const defaultOptions: Options + +export function getLineInfo(input: string, offset: number): Position + +export class TokenType { + label: string + keyword: string | undefined +} + +export const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType +} + +export interface Comment { + type: "Line" | "Block" + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export class Token { + type: TokenType + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export const version: string diff --git a/web/node_modules/acorn/dist/acorn.d.ts b/web/node_modules/acorn/dist/acorn.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ad58121195c96dab6b6c704ae0c0a31fefc2778 --- /dev/null +++ b/web/node_modules/acorn/dist/acorn.d.ts @@ -0,0 +1,857 @@ +export interface Node { + start: number + end: number + type: string + range?: [number, number] + loc?: SourceLocation | null +} + +export interface SourceLocation { + source?: string | null + start: Position + end: Position +} + +export interface Position { + /** 1-based */ + line: number + /** 0-based */ + column: number +} + +export interface Identifier extends Node { + type: "Identifier" + name: string +} + +export interface Literal extends Node { + type: "Literal" + value?: string | boolean | null | number | RegExp | bigint + raw?: string + regex?: { + pattern: string + flags: string + } + bigint?: string +} + +export interface Program extends Node { + type: "Program" + body: Array + sourceType: "script" | "module" +} + +export interface Function extends Node { + id?: Identifier | null + params: Array + body: BlockStatement | Expression + generator: boolean + expression: boolean + async: boolean +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement" + expression: Expression | Literal + directive?: string +} + +export interface BlockStatement extends Node { + type: "BlockStatement" + body: Array +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement" +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement" +} + +export interface WithStatement extends Node { + type: "WithStatement" + object: Expression + body: Statement +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement" + argument?: Expression | null +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement" + label: Identifier + body: Statement +} + +export interface BreakStatement extends Node { + type: "BreakStatement" + label?: Identifier | null +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement" + label?: Identifier | null +} + +export interface IfStatement extends Node { + type: "IfStatement" + test: Expression + consequent: Statement + alternate?: Statement | null +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement" + discriminant: Expression + cases: Array +} + +export interface SwitchCase extends Node { + type: "SwitchCase" + test?: Expression | null + consequent: Array +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement" + argument: Expression +} + +export interface TryStatement extends Node { + type: "TryStatement" + block: BlockStatement + handler?: CatchClause | null + finalizer?: BlockStatement | null +} + +export interface CatchClause extends Node { + type: "CatchClause" + param?: Pattern | null + body: BlockStatement +} + +export interface WhileStatement extends Node { + type: "WhileStatement" + test: Expression + body: Statement +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement" + body: Statement + test: Expression +} + +export interface ForStatement extends Node { + type: "ForStatement" + init?: VariableDeclaration | Expression | null + test?: Expression | null + update?: Expression | null + body: Statement +} + +export interface ForInStatement extends Node { + type: "ForInStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement +} + +export interface FunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: Identifier + body: BlockStatement +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration" + declarations: Array + kind: "var" | "let" | "const" +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator" + id: Pattern + init?: Expression | null +} + +export interface ThisExpression extends Node { + type: "ThisExpression" +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression" + elements: Array +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression" + properties: Array +} + +export interface Property extends Node { + type: "Property" + key: Expression + value: Expression + kind: "init" | "get" | "set" + method: boolean + shorthand: boolean + computed: boolean +} + +export interface FunctionExpression extends Function { + type: "FunctionExpression" + body: BlockStatement +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression" + operator: UnaryOperator + prefix: boolean + argument: Expression +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" + +export interface UpdateExpression extends Node { + type: "UpdateExpression" + operator: UpdateOperator + argument: Expression + prefix: boolean +} + +export type UpdateOperator = "++" | "--" + +export interface BinaryExpression extends Node { + type: "BinaryExpression" + operator: BinaryOperator + left: Expression | PrivateIdentifier + right: Expression +} + +export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**" + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression" + operator: AssignmentOperator + left: Pattern + right: Expression +} + +export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??=" + +export interface LogicalExpression extends Node { + type: "LogicalExpression" + operator: LogicalOperator + left: Expression + right: Expression +} + +export type LogicalOperator = "||" | "&&" | "??" + +export interface MemberExpression extends Node { + type: "MemberExpression" + object: Expression | Super + property: Expression | PrivateIdentifier + computed: boolean + optional: boolean +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression" + test: Expression + alternate: Expression + consequent: Expression +} + +export interface CallExpression extends Node { + type: "CallExpression" + callee: Expression | Super + arguments: Array + optional: boolean +} + +export interface NewExpression extends Node { + type: "NewExpression" + callee: Expression + arguments: Array +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression" + expressions: Array +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement + await: boolean +} + +export interface Super extends Node { + type: "Super" +} + +export interface SpreadElement extends Node { + type: "SpreadElement" + argument: Expression +} + +export interface ArrowFunctionExpression extends Function { + type: "ArrowFunctionExpression" +} + +export interface YieldExpression extends Node { + type: "YieldExpression" + argument?: Expression | null + delegate: boolean +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral" + quasis: Array + expressions: Array +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression" + tag: Expression + quasi: TemplateLiteral +} + +export interface TemplateElement extends Node { + type: "TemplateElement" + tail: boolean + value: { + cooked?: string | null + raw: string + } +} + +export interface AssignmentProperty extends Node { + type: "Property" + key: Expression + value: Pattern + kind: "init" + method: false + shorthand: boolean + computed: boolean +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern" + properties: Array +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern" + elements: Array +} + +export interface RestElement extends Node { + type: "RestElement" + argument: Pattern +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern" + left: Pattern + right: Expression +} + +export interface Class extends Node { + id?: Identifier | null + superClass?: Expression | null + body: ClassBody +} + +export interface ClassBody extends Node { + type: "ClassBody" + body: Array +} + +export interface MethodDefinition extends Node { + type: "MethodDefinition" + key: Expression | PrivateIdentifier + value: FunctionExpression + kind: "constructor" | "method" | "get" | "set" + computed: boolean + static: boolean +} + +export interface ClassDeclaration extends Class { + type: "ClassDeclaration" + id: Identifier +} + +export interface ClassExpression extends Class { + type: "ClassExpression" +} + +export interface MetaProperty extends Node { + type: "MetaProperty" + meta: Identifier + property: Identifier +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration" + specifiers: Array + source: Literal +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier" + imported: Identifier | Literal + local: Identifier +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier" + local: Identifier +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier" + local: Identifier +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration" + declaration?: Declaration | null + specifiers: Array + source?: Literal | null +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier" + exported: Identifier | Literal + local: Identifier | Literal +} + +export interface AnonymousFunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: null + body: BlockStatement +} + +export interface AnonymousClassDeclaration extends Class { + type: "ClassDeclaration" + id: null +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration" + declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration" + source: Literal + exported?: Identifier | Literal | null +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression" + argument: Expression +} + +export interface ChainExpression extends Node { + type: "ChainExpression" + expression: MemberExpression | CallExpression +} + +export interface ImportExpression extends Node { + type: "ImportExpression" + source: Expression +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression" + expression: Expression +} + +export interface PropertyDefinition extends Node { + type: "PropertyDefinition" + key: Expression | PrivateIdentifier + value?: Expression | null + computed: boolean + static: boolean +} + +export interface PrivateIdentifier extends Node { + type: "PrivateIdentifier" + name: string +} + +export interface StaticBlock extends Node { + type: "StaticBlock" + body: Array +} + +export type Statement = +| ExpressionStatement +| BlockStatement +| EmptyStatement +| DebuggerStatement +| WithStatement +| ReturnStatement +| LabeledStatement +| BreakStatement +| ContinueStatement +| IfStatement +| SwitchStatement +| ThrowStatement +| TryStatement +| WhileStatement +| DoWhileStatement +| ForStatement +| ForInStatement +| ForOfStatement +| Declaration + +export type Declaration = +| FunctionDeclaration +| VariableDeclaration +| ClassDeclaration + +export type Expression = +| Identifier +| Literal +| ThisExpression +| ArrayExpression +| ObjectExpression +| FunctionExpression +| UnaryExpression +| UpdateExpression +| BinaryExpression +| AssignmentExpression +| LogicalExpression +| MemberExpression +| ConditionalExpression +| CallExpression +| NewExpression +| SequenceExpression +| ArrowFunctionExpression +| YieldExpression +| TemplateLiteral +| TaggedTemplateExpression +| ClassExpression +| MetaProperty +| AwaitExpression +| ChainExpression +| ImportExpression +| ParenthesizedExpression + +export type Pattern = +| Identifier +| MemberExpression +| ObjectPattern +| ArrayPattern +| RestElement +| AssignmentPattern + +export type ModuleDeclaration = +| ImportDeclaration +| ExportNamedDeclaration +| ExportDefaultDeclaration +| ExportAllDeclaration + +export type AnyNode = Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock + +export function parse(input: string, options: Options): Program + +export function parseExpressionAt(input: string, pos: number, options: Options): Expression + +export function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator +} + +export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | "latest" + +export interface Options { + /** + * `ecmaVersion` indicates the ECMAScript version to parse. Must be + * either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + * (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + * (the latest version the library supports). This influences + * support for strict mode, the set of reserved words, and support + * for new syntax features. + */ + ecmaVersion: ecmaVersion + + /** + * `sourceType` indicates the mode the code should be parsed in. + * Can be either `"script"` or `"module"`. This influences global + * strict mode and parsing of `import` and `export` declarations. + */ + sourceType?: "script" | "module" + + /** + * a callback that will be called when a semicolon is automatically inserted. + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if {@link locations} is enabled + */ + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * similar to `onInsertedSemicolon`, but for trailing commas + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if `locations` is enabled + */ + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * By default, reserved words are only enforced if ecmaVersion >= 5. + * Set `allowReserved` to a boolean value to explicitly turn this on + * an off. When this option has the value "never", reserved words + * and keywords can also not be used as property names. + */ + allowReserved?: boolean | "never" + + /** + * When enabled, a return at the top level is not considered an error. + */ + allowReturnOutsideFunction?: boolean + + /** + * When enabled, import/export statements are not constrained to + * appearing at the top of the program, and an import.meta expression + * in a script isn't considered an error. + */ + allowImportExportEverywhere?: boolean + + /** + * By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022. + * When enabled, await identifiers are allowed to appear at the top-level scope, + * but they are still not allowed in non-async functions. + */ + allowAwaitOutsideFunction?: boolean + + /** + * When enabled, super identifiers are not constrained to + * appearing in methods and do not raise an error when they appear elsewhere. + */ + allowSuperOutsideMethod?: boolean + + /** + * When enabled, hashbang directive in the beginning of file is + * allowed and treated as a line comment. Enabled by default when + * {@link ecmaVersion} >= 2023. + */ + allowHashBang?: boolean + + /** + * By default, the parser will verify that private properties are + * only used in places where they are valid and have been declared. + * Set this to false to turn such checks off. + */ + checkPrivateFields?: boolean + + /** + * When `locations` is on, `loc` properties holding objects with + * `start` and `end` properties as {@link Position} objects will be attached to the + * nodes. + */ + locations?: boolean + + /** + * a callback that will cause Acorn to call that export function with object in the same + * format as tokens returned from `tokenizer().getToken()`. Note + * that you are not allowed to call the parser from the + * callback—that will corrupt its internal state. + */ + onToken?: ((token: Token) => void) | Token[] + + + /** + * This takes a export function or an array. + * + * When a export function is passed, Acorn will call that export function with `(block, text, start, + * end)` parameters whenever a comment is skipped. `block` is a + * boolean indicating whether this is a block (`/* *\/`) comment, + * `text` is the content of the comment, and `start` and `end` are + * character offsets that denote the start and end of the comment. + * When the {@link locations} option is on, two more parameters are + * passed, the full locations of {@link Position} export type of the start and + * end of the comments. + * + * When a array is passed, each found comment of {@link Comment} export type is pushed to the array. + * + * Note that you are not allowed to call the + * parser from the callback—that will corrupt its internal state. + */ + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + + /** + * Nodes have their start and end characters offsets recorded in + * `start` and `end` properties (directly on the node, rather than + * the `loc` object, which holds line/column data. To also add a + * [semi-standardized][range] `range` property holding a `[start, + * end]` array with the same numbers, set the `ranges` option to + * `true`. + */ + ranges?: boolean + + /** + * It is possible to parse multiple files into a single AST by + * passing the tree produced by parsing the first file as + * `program` option in subsequent parses. This will add the + * toplevel forms of the parsed file to the `Program` (top) node + * of an existing parse tree. + */ + program?: Node + + /** + * When {@link locations} is on, you can pass this to record the source + * file in every node's `loc` object. + */ + sourceFile?: string + + /** + * This value, if given, is stored in every node, whether {@link locations} is on or off. + */ + directSourceFile?: string + + /** + * When enabled, parenthesized expressions are represented by + * (non-standard) ParenthesizedExpression nodes + */ + preserveParens?: boolean +} + +export class Parser { + options: Options + input: string + + private constructor(options: Options, input: string, startPos?: number) + parse(): Program + + static parse(input: string, options: Options): Program + static parseExpressionAt(input: string, pos: number, options: Options): Expression + static tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser +} + +export const defaultOptions: Options + +export function getLineInfo(input: string, offset: number): Position + +export class TokenType { + label: string + keyword: string | undefined +} + +export const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType +} + +export interface Comment { + type: "Line" | "Block" + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export class Token { + type: TokenType + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export const version: string diff --git a/web/node_modules/acorn/dist/acorn.js b/web/node_modules/acorn/dist/acorn.js new file mode 100644 index 0000000000000000000000000000000000000000..3a6a3a2aeed54cfbb562ff14b3245578eb05fefa --- /dev/null +++ b/web/node_modules/acorn/dist/acorn.js @@ -0,0 +1,6002 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {})); +})(this, (function (exports) { 'use strict'; + + // This file was generated. Do not modify manually! + var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + // This file was generated. Do not modify manually! + var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. + + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + return false + } + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; + + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + + // Map keyword names to token types. + + var keywords = {}; + + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords[name] = new TokenType(name, options) + } + + var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); + + function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 + } + + function nextLineBreak(code, from, end) { + if ( end === void 0 ) end = code.length; + + for (var i = from; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) + { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } + } + return -1 + } + + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; + + var hasOwn = Object.hasOwn || (function (obj, propName) { return ( + hasOwnProperty.call(obj, propName) + ); }); + + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + + var regexpCache = Object.create(null); + + function wordsRegexp(words) { + return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")) + } + + function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { return String.fromCharCode(code) } + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) + } + + var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; + + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. + + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; + + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; + + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + var nextBreak = nextLineBreak(input, cur, offset); + if (nextBreak < 0) { return new Position(line, offset - cur) } + ++line; + cur = nextBreak; + } + } + + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called when + // a semicolon is automatically inserted. It will be passed the + // position of the inserted semicolon as an offset, and if + // `locations` is enabled, it is given the location as a `{line, + // column}` object as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + // When this option has an array as value, objects representing the + // comments are pushed to it. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; + + // Interpret and default an options object + + var warnedAboutEcmaVersion = false; + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (!opts || opts.allowHashBang == null) + { options.allowHashBang = options.ecmaVersion >= 14; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options + } + + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } + } + + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } + + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types$1.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; + + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; + + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod + }; + + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + + prototypeAccessors.allowNewDotTarget.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit + }; + + prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 + }; + + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; + + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; + + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp$9 = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; + pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { return false } + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; + + // Tests whether parsed token is a contextual keyword. + + pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc + }; + + // Consumes contextual keyword if possible. + + pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; + + // Asserts that following token is given contextual keyword. + + pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; + + // Test whether a semicolon can be inserted at the current position. + + pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || + this.type === types$1.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } + }; + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); + }; + + // Raise an unexpected token error. + + pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; + + var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + }; + + pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } + }; + + pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$8 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$8.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92) { return true } // '[', '/' + if (context) { return false } + + if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false + }; + + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. + + pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types$1._debugger: return this.parseDebuggerStatement(node) + case types$1._do: return this.parseDoStatement(node) + case types$1._for: return this.parseForStatement(node) + case types$1._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types$1._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types$1._if: return this.parseIfStatement(node) + case types$1._return: return this.parseReturnStatement(node) + case types$1._switch: return this.parseSwitchStatement(node) + case types$1._throw: return this.parseThrowStatement(node) + case types$1._try: return this.parseTryStatement(node) + case types$1._const: case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types$1._while: return this.parseWhileStatement(node) + case types$1._with: return this.parseWithStatement(node) + case types$1.braceL: return this.parseBlock(true, node) + case types$1.semi: return this.parseEmptyStatement(node) + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } + }; + + pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types$1.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; + + pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; + + pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types$1.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; + + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + + pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; + + pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; + + pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types$1.braceR;) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; + + pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; + + // Reused empty array added for node fields that are always empty. + + var empty$1 = []; + + pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + + return param + }; + + pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; + + pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; + + pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; + + pp$8.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; + + pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; + + pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; + + pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; + + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. + + pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; + + // Parse a list of variable declarations. + + pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { break } + } + return node + }; + + pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; + + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). + + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types$1.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; + + pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; + + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$8.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node + }; + + pp$8.isClassElementNameStart = function() { + return ( + this.type === types$1.name || + this.type === types$1.privateId || + this.type === types$1.num || + this.type === types$1.string || + this.type === types$1.bracketL || + this.type.keyword + ) + }; + + pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; + + pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") + }; + + pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types$1.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") + }; + + pp$8.parseClassStaticBlock = function(node) { + node.body = []; + + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + + return this.finishNode(node, "StaticBlock") + }; + + pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } + }; + + pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; + }; + + pp$8.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$8.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + if (!this.options.checkPrivateFields) { return } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } + }; + + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } + } + + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$8.parseExportAllDeclaration = function(node, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + }; + + pp$8.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports) + } + if (this.eat(types$1._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") + }; + + pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null) + }; + + pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID") + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration + } + }; + + pp$8.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (typeof name !== "string") + { name = name.type === "Identifier" ? name.name : name.value; } + if (hasOwn(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + }; + + pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } + }; + + pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; + + // Parses a comma-separated list of module exports. + + pp$8.parseExportSpecifier = function(exports) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + + return this.finishNode(node, "ExportSpecifier") + }; + + pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes + }; + + // Parses import declaration. + + pp$8.parseImport = function(node) { + this.next(); + + // import '...' + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; + + // Parses a comma-separated list of module imports. + + pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + + return this.finishNode(node, "ImportSpecifier") + }; + + pp$8.parseImportDefaultSpecifier = function() { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier") + }; + + pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier") + }; + + pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { return nodes } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseImportSpecifier()); + } + return nodes + }; + + pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral + } + return this.parseIdent(true) + }; + + // Set `ExpressionStatement#directive` property for directive prologues. + pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$8.isDirectiveCandidate = function(statement) { + return ( + this.options.ecmaVersion >= 5 && + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; + + var pp$7 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; + + // Convert list of expression atoms to binding list. + + pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; + + // Parses spread element. + + pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; + + pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") + }; + + // Parses lvalue (assignable) atom. + + pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types$1.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; + + pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types$1.comma); } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts + }; + + pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem + }; + + pp$7.parseBindingListItem = function(param) { + return param + }; + + // Parses assignment pattern around given atom if possible. + + pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } + }; + + pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } + }; + + // The algorithm used to determine whether a regexp can appear at a + // given point in the program is loosely based on sweet.js' approach. + // See https://github.com/mozilla/sweet.js/wiki/design + + + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; + + var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; + + var pp$6 = Parser.prototype; + + pp$6.initialContext = function() { + return [types.b_stat] + }; + + pp$6.curContext = function() { + return this.context[this.context.length - 1] + }; + + pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) + { return true } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) + { return true } + if (prevType === types$1.braceL) + { return parent === types.b_stat } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) + { return false } + return !this.exprAllowed + }; + + pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false + }; + + pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; + + // Used to handle edge cases when token context could not be inferred correctly during tokenization phase + + pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } + }; + + // Token-specific context update code + + types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; + }; + + types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; + }; + + types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; + }; + + types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; + }; + + types$1.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; + + types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && + !(prevType === types$1.semi && this.curContext() !== types.p_stat) && + !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) + { this.context.push(types.f_expr); } + else + { this.context.push(types.f_stat); } + this.exprAllowed = false; + }; + + types$1.colon.updateContext = function() { + if (this.curContext().token === "function") { this.context.pop(); } + this.exprAllowed = true; + }; + + types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types.q_tmpl); } + this.exprAllowed = false; + }; + + types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) + { this.context[index] = types.f_expr_gen; } + else + { this.context[index] = types.f_gen; } + } + this.exprAllowed = true; + }; + + types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; + }; + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + + var pp$5 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key.start; + } + } else { + this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types$1.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; + + pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; + + // Parse unary operators, both prefix and postfix. + + pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } + expr = this.parsePrivateIdent(); + // only could be private fields in 'in', such as #x in obj + if (this.type !== types$1._in) { this.unexpected(); } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr + } + }; + + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) + } + + // Parse call, dot, and `[]`-subscript expressions. + + pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; + + pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } + }; + + pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow) + }; + + pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) + }; + + pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types$1.bracketL); + if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types$1.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) + } + } + return id + + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types$1.num: case types$1.string: + return this.parseLiteral(this.value) + + case types$1._null: case types$1._true: case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors) + + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types$1._class: + return this.parseClass(this.startNode(), false) + + case types$1._new: + return this.parseNew() + + case types$1.backQuote: + return this.parseTemplate() + + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew) + } else { + return this.unexpected() + } + + default: + return this.parseExprAtomDefault() + } + }; + + pp$5.parseExprAtomDefault = function() { + this.unexpected(); + }; + + pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + this.next(); + + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node) + } else if (this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "import"; + node.meta = this.finishNode(meta, "Identifier"); + return this.parseImportMeta(node) + } else { + this.unexpected(); + } + }; + + pp$5.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") + }; + + pp$5.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val + }; + + pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon() + }; + + pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } + }; + + pp$5.parseParenItem = function(item) { + return item + }; + + pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty = []; + + pp$5.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "new"; + node.meta = this.finishNode(meta, "Identifier"); + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$5.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement") + }; + + pp$5.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; + + pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + // Parse an object literal or binding pattern. + + pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; + + pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types$1.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; + + pp$5.parseGetterSetter = function(prop) { + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + }; + + pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) + { this.unexpected(); } + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; + + // Initialize empty function node. + + pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + + // Parse object or class method. + + pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + }; + + pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types$1.comma) + { elt = null; } + else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts + }; + + pp$5.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } + }; + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + this.type = types$1.name; + } else { + this.unexpected(); + } + return node + }; + + pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + + return node + }; + + // Parses yield expression inside generator. + + pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = Parser.prototype; + + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. + + pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; + + pp$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$3 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$3.exitScope = function() { + this.scopeStack.pop(); + }; + + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$3.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; + + pp$3.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } + }; + + pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } + }; + + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } + }; + + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; + + // Start an AST node, attaching a start offset. + + var pp$2 = Parser.prototype; + + pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; + + // Finish an AST node, adding `type` and `end` properties. + + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } + + pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // This file contains Unicode properties extracted from the ECMAScript specification. + // The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var ecma13BinaryProperties = ecma12BinaryProperties; + var ecma14BinaryProperties = ecma13BinaryProperties; + + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties + }; + + // #table-binary-unicode-properties-of-strings + var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; + + var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings + }; + + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; + var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; + + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues + }; + + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + + for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + var ecmaVersion = list[i]; + + buildUnicodeData(ecmaVersion); + } + + var pp$1 = Parser.prototype; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; + }; + + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } + }; + + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; + + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; + + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; + + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) + }; + + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; + + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); + }; + + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; + + RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { + if ( forceU === void 0 ) forceU = false; + + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + + var current = this.at(pos, forceU); + if (current === -1 || current !== ch) { + return false + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true + }; + + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + var u = false; + var v = false; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { u = true; } + if (flag === "v") { v = true; } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } + }; + + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$1.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$1.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$1.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$1.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; + + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } + }; + + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false + }; + + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false + }; + + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } + + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$1.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$1.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; + + // Return values used by character set parsing methods, needed to + // forbid negation of sets that can match strings. + var CharSetNone = 0; // Nothing parsed + var CharSetOk = 1; // Construct parsed, cannot contain strings + var CharSetString = 2; // Construct parsed, can contain strings + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk + } + + var negate = false; + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + var result; + if ( + state.eat(0x7B /* { */) && + (result = this.regexp_eatUnicodePropertyValueExpression(state)) && + state.eat(0x7D /* } */) + ) { + if (negate && result === CharSetString) { state.raise("Invalid property name"); } + return result + } + state.raise("Invalid property name"); + } + + return CharSetNone + }; + + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } + + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) + } + return CharSetNone + }; + + pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + + pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } + state.raise("Invalid property name"); + }; + + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } + + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } + + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (!state.eat(0x5D /* ] */)) + { state.raise("Unterminated character class"); } + if (negate && result === CharSetString) + { state.raise("Negated character class may contain strings"); } + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassContents + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + pp$1.regexp_classContents = function(state) { + if (state.current() === 0x5D /* ] */) { return CharSetOk } + if (state.switchV) { return this.regexp_classSetExpression(state) } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; + + // https://tc39.es/ecma262/#prod-ClassSetExpression + // https://tc39.es/ecma262/#prod-ClassUnion + // https://tc39.es/ecma262/#prod-ClassIntersection + // https://tc39.es/ecma262/#prod-ClassSubtraction + pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { result = CharSetString; } + // https://tc39.es/ecma262/#prod-ClassIntersection + var start = state.pos; + while (state.eatChars([0x26, 0x26] /* && */)) { + if ( + state.current() !== 0x26 /* & */ && + (subResult = this.regexp_eatClassSetOperand(state)) + ) { + if (subResult !== CharSetString) { result = CharSetOk; } + continue + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + // https://tc39.es/ecma262/#prod-ClassSubtraction + while (state.eatChars([0x2D, 0x2D] /* -- */)) { + if (this.regexp_eatClassSetOperand(state)) { continue } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + } else { + state.raise("Invalid character in character class"); + } + // https://tc39.es/ecma262/#prod-ClassUnion + for (;;) { + if (this.regexp_eatClassSetRange(state)) { continue } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { return result } + if (subResult === CharSetString) { result = CharSetString; } + } + }; + + // https://tc39.es/ecma262/#prod-ClassSetRange + pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true + } + state.pos = start; + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetOperand + pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) + }; + + // https://tc39.es/ecma262/#prod-NestedClass + pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (state.eat(0x5D /* ] */)) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result + } + state.pos = start; + } + if (state.eat(0x5C /* \ */)) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1 + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunction + pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars([0x5C, 0x71] /* \q */)) { + if (state.eat(0x7B /* { */)) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat(0x7D /* } */)) { + return result + } + } else { + // Make the same message as V8. + state.raise("Invalid escape"); + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents + pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat(0x7C /* | */)) { + if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } + } + return result + }; + + // https://tc39.es/ecma262/#prod-ClassString + // https://tc39.es/ecma262/#prod-NonEmptyClassString + pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { count++; } + return count === 1 ? CharSetOk : CharSetString + }; + + // https://tc39.es/ecma262/#prod-ClassSetCharacter + pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if ( + this.regexp_eatCharacterEscape(state) || + this.regexp_eatClassSetReservedPunctuator(state) + ) { + return true + } + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + state.pos = start; + return false + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } + if (isClassSetSyntaxCharacter(ch)) { return false } + state.advance(); + state.lastIntValue = ch; + return true + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator + function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ( + ch === 0x21 /* ! */ || + ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || + ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || + ch === 0x2E /* . */ || + ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || + ch === 0x5E /* ^ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter + function isClassSetSyntaxCharacter(ch) { + return ( + ch === 0x28 /* ( */ || + ch === 0x29 /* ) */ || + ch === 0x2D /* - */ || + ch === 0x2F /* / */ || + ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + function isClassSetReservedPunctuator(ch) { + return ( + ch === 0x21 /* ! */ || + ch === 0x23 /* # */ || + ch === 0x25 /* % */ || + ch === 0x26 /* & */ || + ch === 0x2C /* , */ || + ch === 0x2D /* - */ || + ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || + ch === 0x40 /* @ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true + }; + + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; + + // ## Tokenizer + + var pp = Parser.prototype; + + // Move to the next token + + pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; + + pp.getToken = function() { + this.next(); + return new Token(this) + }; + + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + } + } + } + }; } + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + // Read a single token, updating the parser object's token-related + // properties. + + pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; + + pp.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) + }; + + pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; + + pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; + + pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types$1.ellipsis) + } else { + ++this.pos; + return this.finishToken(types$1.dot) + } + }; + + pp.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.slash, 1) + }; + + pp.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types$1.assign, 3) } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) + }; + + pp.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.bitwiseXOR, 1) + }; + + pp.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) + }; + + pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) +}; + +pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // ` + +- [Install](#install) +- [Usage](#usage) + - [Simple Parsing](#simple-parsing) + - [Display Help Message and Version](#display-help-message-and-version) + - [Command-specific Options](#command-specific-options) + - [Dash in option names](#dash-in-option-names) + - [Brackets](#brackets) + - [Negated Options](#negated-options) + - [Variadic Arguments](#variadic-arguments) + - [Dot-nested Options](#dot-nested-options) + - [Default Command](#default-command) + - [Supply an array as option value](#supply-an-array-as-option-value) + - [Error Handling](#error-handling) + - [With TypeScript](#with-typescript) + - [With Deno](#with-deno) +- [Projects Using CAC](#projects-using-cac) +- [References](#references) + - [CLI Instance](#cli-instance) + - [cac(name?)](#cacname) + - [cli.command(name, description, config?)](#clicommandname-description-config) + - [cli.option(name, description, config?)](#clioptionname-description-config) + - [cli.parse(argv?)](#cliparseargv) + - [cli.version(version, customFlags?)](#cliversionversion-customflags) + - [cli.help(callback?)](#clihelpcallback) + - [cli.outputHelp()](#clioutputhelp) + - [cli.usage(text)](#cliusagetext) + - [Command Instance](#command-instance) + - [command.option()](#commandoption) + - [command.action(callback)](#commandactioncallback) + - [command.alias(name)](#commandaliasname) + - [command.allowUnknownOptions()](#commandallowunknownoptions) + - [command.example(example)](#commandexampleexample) + - [command.usage(text)](#commandusagetext) + - [Events](#events) +- [FAQ](#faq) + - [How is the name written and pronounced?](#how-is-the-name-written-and-pronounced) + - [Why not use Commander.js?](#why-not-use-commanderjs) +- [Project Stats](#project-stats) +- [Contributing](#contributing) +- [Author](#author) + + + +## Install + +```bash +yarn add cac +``` + +## Usage + +### Simple Parsing + +Use CAC as simple argument parser: + +```js +// examples/basic-usage.js +const cli = require('cac')() + +cli.option('--type ', 'Choose a project type', { + default: 'node', +}) + +const parsed = cli.parse() + +console.log(JSON.stringify(parsed, null, 2)) +``` + +2018-11-26 12 28 03 + +### Display Help Message and Version + +```js +// examples/help.js +const cli = require('cac')() + +cli.option('--type [type]', 'Choose a project type', { + default: 'node', +}) +cli.option('--name ', 'Provide your name') + +cli.command('lint [...files]', 'Lint files').action((files, options) => { + console.log(files, options) +}) + +// Display help message when `-h` or `--help` appears +cli.help() +// Display version number when `-v` or `--version` appears +// It's also used in help message +cli.version('0.0.0') + +cli.parse() +``` + +2018-11-25 8 21 14 + +### Command-specific Options + +You can attach options to a command. + +```js +const cli = require('cac')() + +cli + .command('rm ', 'Remove a dir') + .option('-r, --recursive', 'Remove recursively') + .action((dir, options) => { + console.log('remove ' + dir + (options.recursive ? ' recursively' : '')) + }) + +cli.help() + +cli.parse() +``` + +A command's options 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. If you really want to use unknown options, use [`command.allowUnknownOptions`](#commandallowunknownoptions). + +command options + +### Dash in option names + +Options in kebab-case should be referenced in camelCase in your code: + +```js +cli + .command('dev', 'Start dev server') + .option('--clear-screen', 'Clear screen') + .action((options) => { + console.log(options.clearScreen) + }) +``` + +In fact `--clear-screen` and `--clearScreen` are both mapped to `options.clearScreen`. + +### Brackets + +When using brackets in command name, angled brackets indicate required command arguments, while square bracket indicate optional arguments. + +When using brackets in option name, angled brackets indicate that a string / number value is required, while square bracket indicate that the value can also be `true`. + +```js +const cli = require('cac')() + +cli + .command('deploy ', 'Deploy a folder to AWS') + .option('--scale [level]', 'Scaling level') + .action((folder, options) => { + // ... + }) + +cli + .command('build [project]', 'Build a project') + .option('--out ', 'Output directory') + .action((folder, options) => { + // ... + }) + +cli.parse() +``` + +### Negated Options + +To allow an option whose value is `false`, you need to manually specify a negated option: + +```js +cli + .command('build [project]', 'Build a project') + .option('--no-config', 'Disable config file') + .option('--config ', 'Use a custom config file') +``` + +This will let CAC set the default value of `config` to true, and you can use `--no-config` flag to set it to `false`. + +### Variadic Arguments + +The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to add `...` to the start of argument name, just like the rest operator in JavaScript. Here is an example: + +```js +const cli = require('cac')() + +cli + .command('build [...otherFiles]', 'Build your app') + .option('--foo', 'Foo option') + .action((entry, otherFiles, options) => { + console.log(entry) + console.log(otherFiles) + console.log(options) + }) + +cli.help() + +cli.parse() +``` + +2018-11-25 8 25 30 + +### Dot-nested Options + +Dot-nested options will be merged into a single option. + +```js +const cli = require('cac')() + +cli + .command('build', 'desc') + .option('--env ', 'Set envs') + .example('--env.API_SECRET xxx') + .action((options) => { + console.log(options) + }) + +cli.help() + +cli.parse() +``` + +2018-11-25 9 37 53 + +### Default Command + +Register a command that will be used when no other command is matched. + +```js +const cli = require('cac')() + +cli + // Simply omit the command name, just brackets + .command('[...files]', 'Build files') + .option('--minimize', 'Minimize output') + .action((files, options) => { + console.log(files) + console.log(options.minimize) + }) + +cli.parse() +``` + +### Supply an array as option value + +```bash +node cli.js --include project-a +# The parsed options will be: +# { include: 'project-a' } + +node cli.js --include project-a --include project-b +# The parsed options will be: +# { include: ['project-a', 'project-b'] } +``` + +### Error Handling + +To handle command errors globally: + +```js +try { + // Parse CLI args without running the command + cli.parse(process.argv, { run: false }) + // Run the command yourself + // You only need `await` when your command action returns a Promise + await cli.runMatchedCommand() +} catch (error) { + // Handle error here.. + // e.g. + // console.error(error.stack) + // process.exit(1) +} +``` + +### With TypeScript + +First you need `@types/node` to be installed as a dev dependency in your project: + +```bash +yarn add @types/node --dev +``` + +Then everything just works out of the box: + +```js +const { cac } = require('cac') +// OR ES modules +import { cac } from 'cac' +``` + +### With Deno + +```ts +import { cac } from 'https://unpkg.com/cac/mod.ts' + +const cli = cac('my-program') +``` + +## Projects Using CAC + +Projects that use **CAC**: + +- [VuePress](https://github.com/vuejs/vuepress): :memo: Minimalistic Vue-powered static site generator. +- [SAO](https://github.com/egoist/sao): ⚔️ Futuristic scaffolding tool. +- [DocPad](https://github.com/docpad/docpad): 🏹 Powerful Static Site Generator. +- [Poi](https://github.com/egoist/poi): ⚡️ Delightful web development. +- [bili](https://github.com/egoist/bili): 🥂 Schweizer Armeemesser for bundling JavaScript libraries. +- [Lad](https://github.com/ladjs/lad): 👦 Lad scaffolds a Koa webapp and API framework for Node.js. +- [Lass](https://github.com/lassjs/lass): 💁🏻 Scaffold a modern package boilerplate for Node.js. +- [Foy](https://github.com/zaaack/foy): 🏗 A lightweight and modern task runner and build tool for general purpose. +- [Vuese](https://github.com/vuese/vuese): 🤗 One-stop solution for vue component documentation. +- [NUT](https://github.com/nut-project/nut): 🌰 A framework born for microfrontends +- Feel free to add yours here... + +## References + +**💁 Check out [the generated docs](https://cac-api-doc.egoist.sh/classes/_cac_.cac.html) from source code if you want a more in-depth API references.** + +Below is a brief overview. + +### CLI Instance + +CLI instance is created by invoking the `cac` function: + +```js +const cac = require('cac') +const cli = cac() +``` + +#### cac(name?) + +Create a CLI instance, optionally specify the program name which will be used to display in help and version message. When not set we use the basename of `argv[1]`. + +#### cli.command(name, description, config?) + +- Type: `(name: string, description: string) => Command` + +Create a command instance. + +The option also accepts a third argument `config` for additional command config: + +- `config.allowUnknownOptions`: `boolean` Allow unknown options in this command. +- `config.ignoreOptionDefaultValue`: `boolean` Don't use the options's default value in parsed options, only display them in help message. + +#### cli.option(name, description, config?) + +- Type: `(name: string, description: string, config?: OptionConfig) => CLI` + +Add a global option. + +The option also accepts a third argument `config` for additional option config: + +- `config.default`: Default value for the option. +- `config.type`: `any[]` When set to `[]`, the option value returns an array type. You can also use a conversion function such as `[String]`, which will invoke the option value with `String`. + +#### cli.parse(argv?) + +- Type: `(argv = process.argv) => ParsedArgv` + +```ts +interface ParsedArgv { + args: string[] + options: { + [k: string]: any + } +} +``` + +When this method is called, `cli.rawArgs` `cli.args` `cli.options` `cli.matchedCommand` will also be available. + +#### cli.version(version, customFlags?) + +- Type: `(version: string, customFlags = '-v, --version') => CLI` + +Output version number when `-v, --version` flag appears. + +#### cli.help(callback?) + +- Type: `(callback?: HelpCallback) => CLI` + +Output help message when `-h, --help` flag appears. + +Optional `callback` allows post-processing of help text before it is displayed: + +```ts +type HelpCallback = (sections: HelpSection[]) => void + +interface HelpSection { + title?: string + body: string +} +``` + +#### cli.outputHelp() + +- Type: `() => CLI` + +Output help message. + +#### cli.usage(text) + +- Type: `(text: string) => CLI` + +Add a global usage text. This is not used by sub-commands. + +### Command Instance + +Command instance is created by invoking the `cli.command` method: + +```js +const command = cli.command('build [...files]', 'Build given files') +``` + +#### command.option() + +Basically the same as `cli.option` but this adds the option to specific command. + +#### command.action(callback) + +- Type: `(callback: ActionCallback) => Command` + +Use a callback function as the command action when the command matches user inputs. + +```ts +type ActionCallback = ( + // Parsed CLI args + // The last arg will be an array if it's a variadic argument + ...args: string | string[] | number | number[] + // Parsed CLI options + options: Options +) => any + +interface Options { + [k: string]: any +} +``` + +#### command.alias(name) + +- Type: `(name: string) => Command` + +Add an alias name to this command, the `name` here can't contain brackets. + +#### command.allowUnknownOptions() + +- Type: `() => Command` + +Allow unknown options in this command, by default CAC will log an error when unknown options are used. + +#### command.example(example) + +- Type: `(example: CommandExample) => Command` + +Add an example which will be displayed at the end of help message. + +```ts +type CommandExample = ((name: string) => string) | string +``` + +#### command.usage(text) + +- Type: `(text: string) => Command` + +Add a usage text for this command. + +### Events + +Listen to commands: + +```js +// Listen to the `foo` command +cli.on('command:foo', () => { + // Do something +}) + +// Listen to the default command +cli.on('command:!', () => { + // Do something +}) + +// Listen to unknown commands +cli.on('command:*', () => { + console.error('Invalid command: %s', cli.args.join(' ')) + process.exit(1) +}) +``` + +## FAQ + +### How is the name written and pronounced? + +CAC, or cac, pronounced `C-A-C`. + +This project is dedicated to our lovely C.C. sama. Maybe CAC stands for C&C as well :P + + + +### Why not use Commander.js? + +CAC is very similar to Commander.js, while the latter does not support dot nested options, i.e. something like `--env.API_SECRET foo`. Besides, you can't use unknown options in Commander.js either. + +_And maybe more..._ + +Basically I made CAC to fulfill my own needs for building CLI apps like [Poi](https://poi.js.org), [SAO](https://sao.vercel.app) and all my CLI apps. It's small, simple but powerful :P + +## Project Stats + +![Alt](https://repobeats.axiom.co/api/embed/58caf6203631bcdb9bbe22f0728a0af1683dc0bb.svg 'Repobeats analytics image') + +## Contributing + +1. Fork it! +2. Create your feature branch: `git checkout -b my-new-feature` +3. Commit your changes: `git commit -am 'Add some feature'` +4. Push to the branch: `git push origin my-new-feature` +5. Submit a pull request :D + +## Author + +**CAC** © [EGOIST](https://github.com/egoist), Released under the [MIT](./LICENSE) License.
+Authored and maintained by egoist with help from contributors ([list](https://github.com/cacjs/cac/contributors)). + +> [Website](https://egoist.sh) · GitHub [@egoist](https://github.com/egoist) · Twitter [@\_egoistlily](https://twitter.com/_egoistlily) diff --git a/web/node_modules/cac/deno/CAC.ts b/web/node_modules/cac/deno/CAC.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ced3b1f69b8c7422b6b1acb4eff1144a9e68a42 --- /dev/null +++ b/web/node_modules/cac/deno/CAC.ts @@ -0,0 +1,331 @@ +import { EventEmitter } from "https://deno.land/std@0.114.0/node/events.ts"; +import mri from "https://cdn.skypack.dev/mri"; +import Command, { GlobalCommand, CommandConfig, HelpCallback, CommandExample } from "./Command.ts"; +import { OptionConfig } from "./Option.ts"; +import { getMriOptions, setDotProp, setByType, getFileName, camelcaseOptionName } from "./utils.ts"; +import { processArgs } from "./deno.ts"; +interface ParsedArgv { + args: ReadonlyArray; + options: { + [k: string]: any; + }; +} + +class CAC extends EventEmitter { + /** The program name to display in help and version message */ + name: string; + commands: Command[]; + globalCommand: GlobalCommand; + matchedCommand?: Command; + matchedCommandName?: string; + /** + * Raw CLI arguments + */ + + rawArgs: string[]; + /** + * Parsed CLI arguments + */ + + args: ParsedArgv['args']; + /** + * Parsed CLI options, camelCased + */ + + options: ParsedArgv['options']; + showHelpOnExit?: boolean; + showVersionOnExit?: boolean; + /** + * @param name The program name to display in help and version message + */ + + constructor(name = '') { + super(); + this.name = name; + this.commands = []; + this.rawArgs = []; + this.args = []; + this.options = {}; + this.globalCommand = new GlobalCommand(this); + this.globalCommand.usage(' [options]'); + } + /** + * Add a global usage text. + * + * This is not used by sub-commands. + */ + + + usage(text: string) { + this.globalCommand.usage(text); + return this; + } + /** + * Add a sub-command + */ + + + command(rawName: string, description?: string, config?: CommandConfig) { + const command = new Command(rawName, description || '', config, this); + command.globalCommand = this.globalCommand; + this.commands.push(command); + return command; + } + /** + * Add a global CLI option. + * + * Which is also applied to sub-commands. + */ + + + option(rawName: string, description: string, config?: OptionConfig) { + this.globalCommand.option(rawName, description, config); + return this; + } + /** + * Show help message when `-h, --help` flags appear. + * + */ + + + help(callback?: HelpCallback) { + this.globalCommand.option('-h, --help', 'Display this message'); + this.globalCommand.helpCallback = callback; + this.showHelpOnExit = true; + return this; + } + /** + * Show version number when `-v, --version` flags appear. + * + */ + + + version(version: string, customFlags = '-v, --version') { + this.globalCommand.version(version, customFlags); + this.showVersionOnExit = true; + return this; + } + /** + * Add a global example. + * + * This example added here will not be used by sub-commands. + */ + + + example(example: CommandExample) { + this.globalCommand.example(example); + return this; + } + /** + * Output the corresponding help message + * When a sub-command is matched, output the help message for the command + * Otherwise output the global one. + * + */ + + + outputHelp() { + if (this.matchedCommand) { + this.matchedCommand.outputHelp(); + } else { + this.globalCommand.outputHelp(); + } + } + /** + * Output the version number. + * + */ + + + outputVersion() { + this.globalCommand.outputVersion(); + } + + private setParsedInfo({ + args, + options + }: ParsedArgv, matchedCommand?: Command, matchedCommandName?: string) { + this.args = args; + this.options = options; + + if (matchedCommand) { + this.matchedCommand = matchedCommand; + } + + if (matchedCommandName) { + this.matchedCommandName = matchedCommandName; + } + + return this; + } + + unsetMatchedCommand() { + this.matchedCommand = undefined; + this.matchedCommandName = undefined; + } + /** + * Parse argv + */ + + + parse(argv = processArgs, { + /** Whether to run the action for matched command */ + run = true + } = {}): ParsedArgv { + this.rawArgs = argv; + + if (!this.name) { + this.name = argv[1] ? getFileName(argv[1]) : 'cli'; + } + + let shouldParse = true; // Search sub-commands + + for (const command of this.commands) { + const parsed = this.mri(argv.slice(2), command); + const commandName = parsed.args[0]; + + if (command.isMatched(commandName)) { + shouldParse = false; + const parsedInfo = { ...parsed, + args: parsed.args.slice(1) + }; + this.setParsedInfo(parsedInfo, command, commandName); + this.emit(`command:${commandName}`, command); + } + } + + if (shouldParse) { + // Search the default command + for (const command of this.commands) { + if (command.name === '') { + shouldParse = false; + const parsed = this.mri(argv.slice(2), command); + this.setParsedInfo(parsed, command); + this.emit(`command:!`, command); + } + } + } + + if (shouldParse) { + const parsed = this.mri(argv.slice(2)); + this.setParsedInfo(parsed); + } + + if (this.options.help && this.showHelpOnExit) { + this.outputHelp(); + run = false; + this.unsetMatchedCommand(); + } + + if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) { + this.outputVersion(); + run = false; + this.unsetMatchedCommand(); + } + + const parsedArgv = { + args: this.args, + options: this.options + }; + + if (run) { + this.runMatchedCommand(); + } + + if (!this.matchedCommand && this.args[0]) { + this.emit('command:*'); + } + + return parsedArgv; + } + + private mri(argv: string[], + /** Matched command */ + command?: Command): ParsedArgv { + // All added options + const cliOptions = [...this.globalCommand.options, ...(command ? command.options : [])]; + const mriOptions = getMriOptions(cliOptions); // Extract everything after `--` since mri doesn't support it + + let argsAfterDoubleDashes: string[] = []; + const doubleDashesIndex = argv.indexOf('--'); + + if (doubleDashesIndex > -1) { + argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); + argv = argv.slice(0, doubleDashesIndex); + } + + let parsed = mri(argv, mriOptions); + parsed = Object.keys(parsed).reduce((res, name) => { + return { ...res, + [camelcaseOptionName(name)]: parsed[name] + }; + }, { + _: [] + }); + const args = parsed._; + const options: { + [k: string]: any; + } = { + '--': argsAfterDoubleDashes + }; // Set option default value + + const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; + let transforms = Object.create(null); + + for (const cliOption of cliOptions) { + if (!ignoreDefault && cliOption.config.default !== undefined) { + for (const name of cliOption.names) { + options[name] = cliOption.config.default; + } + } // If options type is defined + + + if (Array.isArray(cliOption.config.type)) { + if (transforms[cliOption.name] === undefined) { + transforms[cliOption.name] = Object.create(null); + transforms[cliOption.name]['shouldTransform'] = true; + transforms[cliOption.name]['transformFunction'] = cliOption.config.type[0]; + } + } + } // Set option values (support dot-nested property name) + + + for (const key of Object.keys(parsed)) { + if (key !== '_') { + const keys = key.split('.'); + setDotProp(options, keys, parsed[key]); + setByType(options, transforms); + } + } + + return { + args, + options + }; + } + + runMatchedCommand() { + const { + args, + options, + matchedCommand: command + } = this; + if (!command || !command.commandAction) return; + command.checkUnknownOptions(); + command.checkOptionValue(); + command.checkRequiredArgs(); + const actionArgs: any[] = []; + command.args.forEach((arg, index) => { + if (arg.variadic) { + actionArgs.push(args.slice(index)); + } else { + actionArgs.push(args[index]); + } + }); + actionArgs.push(options); + return command.commandAction.apply(this, actionArgs); + } + +} + +export default CAC; \ No newline at end of file diff --git a/web/node_modules/cac/deno/Command.ts b/web/node_modules/cac/deno/Command.ts new file mode 100644 index 0000000000000000000000000000000000000000..3fd04a058a5d7ef12c941f86dcf087bf8ffc14dc --- /dev/null +++ b/web/node_modules/cac/deno/Command.ts @@ -0,0 +1,269 @@ +import CAC from "./CAC.ts"; +import Option, { OptionConfig } from "./Option.ts"; +import { removeBrackets, findAllBrackets, findLongest, padRight, CACError } from "./utils.ts"; +import { platformInfo } from "./deno.ts"; +interface CommandArg { + required: boolean; + value: string; + variadic: boolean; +} +interface HelpSection { + title?: string; + body: string; +} +interface CommandConfig { + allowUnknownOptions?: boolean; + ignoreOptionDefaultValue?: boolean; +} +type HelpCallback = (sections: HelpSection[]) => void | HelpSection[]; +type CommandExample = ((bin: string) => string) | string; + +class Command { + options: Option[]; + aliasNames: string[]; + /* Parsed command name */ + + name: string; + args: CommandArg[]; + commandAction?: (...args: any[]) => any; + usageText?: string; + versionNumber?: string; + examples: CommandExample[]; + helpCallback?: HelpCallback; + globalCommand?: GlobalCommand; + + constructor(public rawName: string, public description: string, public config: CommandConfig = {}, public cli: CAC) { + this.options = []; + this.aliasNames = []; + this.name = removeBrackets(rawName); + this.args = findAllBrackets(rawName); + this.examples = []; + } + + usage(text: string) { + this.usageText = text; + return this; + } + + allowUnknownOptions() { + this.config.allowUnknownOptions = true; + return this; + } + + ignoreOptionDefaultValue() { + this.config.ignoreOptionDefaultValue = true; + return this; + } + + version(version: string, customFlags = '-v, --version') { + this.versionNumber = version; + this.option(customFlags, 'Display version number'); + return this; + } + + example(example: CommandExample) { + this.examples.push(example); + return this; + } + /** + * Add a option for this command + * @param rawName Raw option name(s) + * @param description Option description + * @param config Option config + */ + + + option(rawName: string, description: string, config?: OptionConfig) { + const option = new Option(rawName, description, config); + this.options.push(option); + return this; + } + + alias(name: string) { + this.aliasNames.push(name); + return this; + } + + action(callback: (...args: any[]) => any) { + this.commandAction = callback; + return this; + } + /** + * Check if a command name is matched by this command + * @param name Command name + */ + + + isMatched(name: string) { + return this.name === name || this.aliasNames.includes(name); + } + + get isDefaultCommand() { + return this.name === '' || this.aliasNames.includes('!'); + } + + get isGlobalCommand(): boolean { + return this instanceof GlobalCommand; + } + /** + * Check if an option is registered in this command + * @param name Option name + */ + + + hasOption(name: string) { + name = name.split('.')[0]; + return this.options.find(option => { + return option.names.includes(name); + }); + } + + outputHelp() { + const { + name, + commands + } = this.cli; + const { + versionNumber, + options: globalOptions, + helpCallback + } = this.cli.globalCommand; + let sections: HelpSection[] = [{ + body: `${name}${versionNumber ? `/${versionNumber}` : ''}` + }]; + sections.push({ + title: 'Usage', + body: ` $ ${name} ${this.usageText || this.rawName}` + }); + const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; + + if (showCommands) { + const longestCommandName = findLongest(commands.map(command => command.rawName)); + sections.push({ + title: 'Commands', + body: commands.map(command => { + return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`; + }).join('\n') + }); + sections.push({ + title: `For more info, run any command with the \`--help\` flag`, + body: commands.map(command => ` $ ${name}${command.name === '' ? '' : ` ${command.name}`} --help`).join('\n') + }); + } + + let options = this.isGlobalCommand ? globalOptions : [...this.options, ...(globalOptions || [])]; + + if (!this.isGlobalCommand && !this.isDefaultCommand) { + options = options.filter(option => option.name !== 'version'); + } + + if (options.length > 0) { + const longestOptionName = findLongest(options.map(option => option.rawName)); + sections.push({ + title: 'Options', + body: options.map(option => { + return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === undefined ? '' : `(default: ${option.config.default})`}`; + }).join('\n') + }); + } + + if (this.examples.length > 0) { + sections.push({ + title: 'Examples', + body: this.examples.map(example => { + if (typeof example === 'function') { + return example(name); + } + + return example; + }).join('\n') + }); + } + + if (helpCallback) { + sections = helpCallback(sections) || sections; + } + + console.log(sections.map(section => { + return section.title ? `${section.title}:\n${section.body}` : section.body; + }).join('\n\n')); + } + + outputVersion() { + const { + name + } = this.cli; + const { + versionNumber + } = this.cli.globalCommand; + + if (versionNumber) { + console.log(`${name}/${versionNumber} ${platformInfo}`); + } + } + + checkRequiredArgs() { + const minimalArgsCount = this.args.filter(arg => arg.required).length; + + if (this.cli.args.length < minimalArgsCount) { + throw new CACError(`missing required args for command \`${this.rawName}\``); + } + } + /** + * Check if the parsed options contain any unknown options + * + * Exit and output error when true + */ + + + checkUnknownOptions() { + const { + options, + globalCommand + } = this.cli; + + if (!this.config.allowUnknownOptions) { + for (const name of Object.keys(options)) { + if (name !== '--' && !this.hasOption(name) && !globalCommand.hasOption(name)) { + throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``); + } + } + } + } + /** + * Check if the required string-type options exist + */ + + + checkOptionValue() { + const { + options: parsedOptions, + globalCommand + } = this.cli; + const options = [...globalCommand.options, ...this.options]; + + for (const option of options) { + const value = parsedOptions[option.name.split('.')[0]]; // Check required option value + + if (option.required) { + const hasNegated = options.some(o => o.negated && o.names.includes(option.name)); + + if (value === true || value === false && !hasNegated) { + throw new CACError(`option \`${option.rawName}\` value is missing`); + } + } + } + } + +} + +class GlobalCommand extends Command { + constructor(cli: CAC) { + super('@@global@@', '', {}, cli); + } + +} + +export type { HelpCallback, CommandExample, CommandConfig }; +export { GlobalCommand }; +export default Command; \ No newline at end of file diff --git a/web/node_modules/cac/deno/Option.ts b/web/node_modules/cac/deno/Option.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee7ed2d834dca8a57144d57d10e0ddd1920cc26d --- /dev/null +++ b/web/node_modules/cac/deno/Option.ts @@ -0,0 +1,52 @@ +import { removeBrackets, camelcaseOptionName } from "./utils.ts"; +interface OptionConfig { + default?: any; + type?: any[]; +} +export default class Option { + /** Option name */ + name: string; + /** Option name and aliases */ + + names: string[]; + isBoolean?: boolean; // `required` will be a boolean for options with brackets + + required?: boolean; + config: OptionConfig; + negated: boolean; + + constructor(public rawName: string, public description: string, config?: OptionConfig) { + this.config = Object.assign({}, config); // You may use cli.option('--env.* [value]', 'desc') to denote a dot-nested option + + rawName = rawName.replace(/\.\*/g, ''); + this.negated = false; + this.names = removeBrackets(rawName).split(',').map((v: string) => { + let name = v.trim().replace(/^-{1,2}/, ''); + + if (name.startsWith('no-')) { + this.negated = true; + name = name.replace(/^no-/, ''); + } + + return camelcaseOptionName(name); + }).sort((a, b) => a.length > b.length ? 1 : -1); // Sort names + // Use the longest name (last one) as actual option name + + this.name = this.names[this.names.length - 1]; + + if (this.negated && this.config.default == null) { + this.config.default = true; + } + + if (rawName.includes('<')) { + this.required = true; + } else if (rawName.includes('[')) { + this.required = false; + } else { + // No arg needed, it's boolean flag + this.isBoolean = true; + } + } + +} +export type { OptionConfig }; \ No newline at end of file diff --git a/web/node_modules/cac/deno/deno.ts b/web/node_modules/cac/deno/deno.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f8e7d9b9af5472fa009cf0482fe49bde83b13fb --- /dev/null +++ b/web/node_modules/cac/deno/deno.ts @@ -0,0 +1,4 @@ +// Ignore the TypeScript errors +// Since this file will only be used in Deno runtime +export const processArgs = ['deno', 'cli'].concat(Deno.args); +export const platformInfo = `${Deno.build.os}-${Deno.build.arch} deno-${Deno.version.deno}`; \ No newline at end of file diff --git a/web/node_modules/cac/deno/index.ts b/web/node_modules/cac/deno/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..55aa29b7db3ed129aca119177bbe3d520d2eabb4 --- /dev/null +++ b/web/node_modules/cac/deno/index.ts @@ -0,0 +1,10 @@ +import CAC from "./CAC.ts"; +import Command from "./Command.ts"; +/** + * @param name The program name to display in help and version message + */ + +const cac = (name = '') => new CAC(name); + +export default cac; +export { cac, CAC, Command }; \ No newline at end of file diff --git a/web/node_modules/cac/deno/utils.ts b/web/node_modules/cac/deno/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..d75847b5aa677dc173692596629932bd7fc3aad4 --- /dev/null +++ b/web/node_modules/cac/deno/utils.ts @@ -0,0 +1,145 @@ +import Option from "./Option.ts"; +export const removeBrackets = (v: string) => v.replace(/[<[].+/, '').trim(); +export const findAllBrackets = (v: string) => { + const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; + const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; + const res = []; + + const parse = (match: string[]) => { + let variadic = false; + let value = match[1]; + + if (value.startsWith('...')) { + value = value.slice(3); + variadic = true; + } + + return { + required: match[0].startsWith('<'), + value, + variadic + }; + }; + + let angledMatch; + + while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(angledMatch)); + } + + let squareMatch; + + while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(squareMatch)); + } + + return res; +}; +interface MriOptions { + alias: { + [k: string]: string[]; + }; + boolean: string[]; +} +export const getMriOptions = (options: Option[]) => { + const result: MriOptions = { + alias: {}, + boolean: [] + }; + + for (const [index, option] of options.entries()) { + // We do not set default values in mri options + // Since its type (typeof) will be used to cast parsed arguments. + // Which mean `--foo foo` will be parsed as `{foo: true}` if we have `{default:{foo: true}}` + // Set alias + if (option.names.length > 1) { + result.alias[option.names[0]] = option.names.slice(1); + } // Set boolean + + + if (option.isBoolean) { + if (option.negated) { + // For negated option + // We only set it to `boolean` type when there's no string-type option with the same name + const hasStringTypeOption = options.some((o, i) => { + return i !== index && o.names.some(name => option.names.includes(name)) && typeof o.required === 'boolean'; + }); + + if (!hasStringTypeOption) { + result.boolean.push(option.names[0]); + } + } else { + result.boolean.push(option.names[0]); + } + } + } + + return result; +}; +export const findLongest = (arr: string[]) => { + return arr.sort((a, b) => { + return a.length > b.length ? -1 : 1; + })[0]; +}; +export const padRight = (str: string, length: number) => { + return str.length >= length ? str : `${str}${' '.repeat(length - str.length)}`; +}; +export const camelcase = (input: string) => { + return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => { + return p1 + p2.toUpperCase(); + }); +}; +export const setDotProp = (obj: { + [k: string]: any; +}, keys: string[], val: any) => { + let i = 0; + let length = keys.length; + let t = obj; + let x; + + for (; i < length; ++i) { + x = t[keys[i]]; + t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf('.') || !(+keys[i + 1] > -1) ? {} : []; + } +}; +export const setByType = (obj: { + [k: string]: any; +}, transforms: { + [k: string]: any; +}) => { + for (const key of Object.keys(transforms)) { + const transform = transforms[key]; + + if (transform.shouldTransform) { + obj[key] = Array.prototype.concat.call([], obj[key]); + + if (typeof transform.transformFunction === 'function') { + obj[key] = obj[key].map(transform.transformFunction); + } + } + } +}; +export const getFileName = (input: string) => { + const m = /([^\\\/]+)$/.exec(input); + return m ? m[1] : ''; +}; +export const camelcaseOptionName = (name: string) => { + // Camelcase the option name + // Don't camelcase anything after the dot `.` + return name.split('.').map((v, i) => { + return i === 0 ? camelcase(v) : v; + }).join('.'); +}; +export class CACError extends Error { + constructor(message: string) { + super(message); + this.name = this.constructor.name; + + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error(message).stack; + } + } + +} \ No newline at end of file diff --git a/web/node_modules/cac/dist/index.d.ts b/web/node_modules/cac/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84dcb6642e6633419d94a81f5764f90d10273cfc --- /dev/null +++ b/web/node_modules/cac/dist/index.d.ts @@ -0,0 +1,191 @@ +import { EventEmitter } from 'events'; + +interface OptionConfig { + default?: any; + type?: any[]; +} +declare class Option { + rawName: string; + description: string; + /** Option name */ + name: string; + /** Option name and aliases */ + names: string[]; + isBoolean?: boolean; + required?: boolean; + config: OptionConfig; + negated: boolean; + constructor(rawName: string, description: string, config?: OptionConfig); +} + +interface CommandArg { + required: boolean; + value: string; + variadic: boolean; +} +interface HelpSection { + title?: string; + body: string; +} +interface CommandConfig { + allowUnknownOptions?: boolean; + ignoreOptionDefaultValue?: boolean; +} +declare type HelpCallback = (sections: HelpSection[]) => void | HelpSection[]; +declare type CommandExample = ((bin: string) => string) | string; +declare class Command { + rawName: string; + description: string; + config: CommandConfig; + cli: CAC; + options: Option[]; + aliasNames: string[]; + name: string; + args: CommandArg[]; + commandAction?: (...args: any[]) => any; + usageText?: string; + versionNumber?: string; + examples: CommandExample[]; + helpCallback?: HelpCallback; + globalCommand?: GlobalCommand; + constructor(rawName: string, description: string, config: CommandConfig, cli: CAC); + usage(text: string): this; + allowUnknownOptions(): this; + ignoreOptionDefaultValue(): this; + version(version: string, customFlags?: string): this; + example(example: CommandExample): this; + /** + * Add a option for this command + * @param rawName Raw option name(s) + * @param description Option description + * @param config Option config + */ + option(rawName: string, description: string, config?: OptionConfig): this; + alias(name: string): this; + action(callback: (...args: any[]) => any): this; + /** + * Check if a command name is matched by this command + * @param name Command name + */ + isMatched(name: string): boolean; + get isDefaultCommand(): boolean; + get isGlobalCommand(): boolean; + /** + * Check if an option is registered in this command + * @param name Option name + */ + hasOption(name: string): Option | undefined; + outputHelp(): void; + outputVersion(): void; + checkRequiredArgs(): void; + /** + * Check if the parsed options contain any unknown options + * + * Exit and output error when true + */ + checkUnknownOptions(): void; + /** + * Check if the required string-type options exist + */ + checkOptionValue(): void; +} +declare class GlobalCommand extends Command { + constructor(cli: CAC); +} + +interface ParsedArgv { + args: ReadonlyArray; + options: { + [k: string]: any; + }; +} +declare class CAC extends EventEmitter { + /** The program name to display in help and version message */ + name: string; + commands: Command[]; + globalCommand: GlobalCommand; + matchedCommand?: Command; + matchedCommandName?: string; + /** + * Raw CLI arguments + */ + rawArgs: string[]; + /** + * Parsed CLI arguments + */ + args: ParsedArgv['args']; + /** + * Parsed CLI options, camelCased + */ + options: ParsedArgv['options']; + showHelpOnExit?: boolean; + showVersionOnExit?: boolean; + /** + * @param name The program name to display in help and version message + */ + constructor(name?: string); + /** + * Add a global usage text. + * + * This is not used by sub-commands. + */ + usage(text: string): this; + /** + * Add a sub-command + */ + command(rawName: string, description?: string, config?: CommandConfig): Command; + /** + * Add a global CLI option. + * + * Which is also applied to sub-commands. + */ + option(rawName: string, description: string, config?: OptionConfig): this; + /** + * Show help message when `-h, --help` flags appear. + * + */ + help(callback?: HelpCallback): this; + /** + * Show version number when `-v, --version` flags appear. + * + */ + version(version: string, customFlags?: string): this; + /** + * Add a global example. + * + * This example added here will not be used by sub-commands. + */ + example(example: CommandExample): this; + /** + * Output the corresponding help message + * When a sub-command is matched, output the help message for the command + * Otherwise output the global one. + * + */ + outputHelp(): void; + /** + * Output the version number. + * + */ + outputVersion(): void; + private setParsedInfo; + unsetMatchedCommand(): void; + /** + * Parse argv + */ + parse(argv?: string[], { + /** Whether to run the action for matched command */ + run, }?: { + run?: boolean | undefined; + }): ParsedArgv; + private mri; + runMatchedCommand(): any; +} + +/** + * @param name The program name to display in help and version message + */ +declare const cac: (name?: string) => CAC; + +export default cac; +export { CAC, Command, cac }; diff --git a/web/node_modules/cac/dist/index.js b/web/node_modules/cac/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8582dbf62dcc4152a4a07a581c1cf19e4e7a4777 --- /dev/null +++ b/web/node_modules/cac/dist/index.js @@ -0,0 +1,623 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var events = require('events'); + +function toArr(any) { + return any == null ? [] : Array.isArray(any) ? any : [any]; +} + +function toVal(out, key, val, opts) { + var x, old=out[key], nxt=( + !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val)) + : typeof val === 'boolean' ? val + : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val)) + : (x = +val,x * 0 === 0) ? x : val + ); + out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]); +} + +function mri2 (args, opts) { + args = args || []; + opts = opts || {}; + + var k, arr, arg, name, val, out={ _:[] }; + var i=0, j=0, idx=0, len=args.length; + + const alibi = opts.alias !== void 0; + const strict = opts.unknown !== void 0; + const defaults = opts.default !== void 0; + + opts.alias = opts.alias || {}; + opts.string = toArr(opts.string); + opts.boolean = toArr(opts.boolean); + + if (alibi) { + for (k in opts.alias) { + arr = opts.alias[k] = toArr(opts.alias[k]); + for (i=0; i < arr.length; i++) { + (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); + } + } + } + + for (i=opts.boolean.length; i-- > 0;) { + arr = opts.alias[opts.boolean[i]] || []; + for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]); + } + + for (i=opts.string.length; i-- > 0;) { + arr = opts.alias[opts.string[i]] || []; + for (j=arr.length; j-- > 0;) opts.string.push(arr[j]); + } + + if (defaults) { + for (k in opts.default) { + name = typeof opts.default[k]; + arr = opts.alias[k] = opts.alias[k] || []; + if (opts[name] !== void 0) { + opts[name].push(k); + for (i=0; i < arr.length; i++) { + opts[name].push(arr[i]); + } + } + } + } + + const keys = strict ? Object.keys(opts.alias) : []; + + for (i=0; i < len; i++) { + arg = args[i]; + + if (arg === '--') { + out._ = out._.concat(args.slice(++i)); + break; + } + + for (j=0; j < arg.length; j++) { + if (arg.charCodeAt(j) !== 45) break; // "-" + } + + if (j === 0) { + out._.push(arg); + } else if (arg.substring(j, j + 3) === 'no-') { + name = arg.substring(j + 3); + if (strict && !~keys.indexOf(name)) { + return opts.unknown(arg); + } + out[name] = false; + } else { + for (idx=j+1; idx < arg.length; idx++) { + if (arg.charCodeAt(idx) === 61) break; // "=" + } + + name = arg.substring(j, idx); + val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]); + arr = (j === 2 ? [name] : name); + + for (idx=0; idx < arr.length; idx++) { + name = arr[idx]; + if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); + toVal(out, name, (idx + 1 < arr.length) || val, opts); + } + } + } + + if (defaults) { + for (k in opts.default) { + if (out[k] === void 0) { + out[k] = opts.default[k]; + } + } + } + + if (alibi) { + for (k in out) { + arr = opts.alias[k] || []; + while (arr.length > 0) { + out[arr.shift()] = out[k]; + } + } + } + + return out; +} + +const removeBrackets = (v) => v.replace(/[<[].+/, "").trim(); +const findAllBrackets = (v) => { + const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; + const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; + const res = []; + const parse = (match) => { + let variadic = false; + let value = match[1]; + if (value.startsWith("...")) { + value = value.slice(3); + variadic = true; + } + return { + required: match[0].startsWith("<"), + value, + variadic + }; + }; + let angledMatch; + while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(angledMatch)); + } + let squareMatch; + while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(squareMatch)); + } + return res; +}; +const getMriOptions = (options) => { + const result = {alias: {}, boolean: []}; + for (const [index, option] of options.entries()) { + if (option.names.length > 1) { + result.alias[option.names[0]] = option.names.slice(1); + } + if (option.isBoolean) { + if (option.negated) { + const hasStringTypeOption = options.some((o, i) => { + return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean"; + }); + if (!hasStringTypeOption) { + result.boolean.push(option.names[0]); + } + } else { + result.boolean.push(option.names[0]); + } + } + } + return result; +}; +const findLongest = (arr) => { + return arr.sort((a, b) => { + return a.length > b.length ? -1 : 1; + })[0]; +}; +const padRight = (str, length) => { + return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; +}; +const camelcase = (input) => { + return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => { + return p1 + p2.toUpperCase(); + }); +}; +const setDotProp = (obj, keys, val) => { + let i = 0; + let length = keys.length; + let t = obj; + let x; + for (; i < length; ++i) { + x = t[keys[i]]; + t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : []; + } +}; +const setByType = (obj, transforms) => { + for (const key of Object.keys(transforms)) { + const transform = transforms[key]; + if (transform.shouldTransform) { + obj[key] = Array.prototype.concat.call([], obj[key]); + if (typeof transform.transformFunction === "function") { + obj[key] = obj[key].map(transform.transformFunction); + } + } + } +}; +const getFileName = (input) => { + const m = /([^\\\/]+)$/.exec(input); + return m ? m[1] : ""; +}; +const camelcaseOptionName = (name) => { + return name.split(".").map((v, i) => { + return i === 0 ? camelcase(v) : v; + }).join("."); +}; +class CACError extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error(message).stack; + } + } +} + +class Option { + constructor(rawName, description, config) { + this.rawName = rawName; + this.description = description; + this.config = Object.assign({}, config); + rawName = rawName.replace(/\.\*/g, ""); + this.negated = false; + this.names = removeBrackets(rawName).split(",").map((v) => { + let name = v.trim().replace(/^-{1,2}/, ""); + if (name.startsWith("no-")) { + this.negated = true; + name = name.replace(/^no-/, ""); + } + return camelcaseOptionName(name); + }).sort((a, b) => a.length > b.length ? 1 : -1); + this.name = this.names[this.names.length - 1]; + if (this.negated && this.config.default == null) { + this.config.default = true; + } + if (rawName.includes("<")) { + this.required = true; + } else if (rawName.includes("[")) { + this.required = false; + } else { + this.isBoolean = true; + } + } +} + +const processArgs = process.argv; +const platformInfo = `${process.platform}-${process.arch} node-${process.version}`; + +class Command { + constructor(rawName, description, config = {}, cli) { + this.rawName = rawName; + this.description = description; + this.config = config; + this.cli = cli; + this.options = []; + this.aliasNames = []; + this.name = removeBrackets(rawName); + this.args = findAllBrackets(rawName); + this.examples = []; + } + usage(text) { + this.usageText = text; + return this; + } + allowUnknownOptions() { + this.config.allowUnknownOptions = true; + return this; + } + ignoreOptionDefaultValue() { + this.config.ignoreOptionDefaultValue = true; + return this; + } + version(version, customFlags = "-v, --version") { + this.versionNumber = version; + this.option(customFlags, "Display version number"); + return this; + } + example(example) { + this.examples.push(example); + return this; + } + option(rawName, description, config) { + const option = new Option(rawName, description, config); + this.options.push(option); + return this; + } + alias(name) { + this.aliasNames.push(name); + return this; + } + action(callback) { + this.commandAction = callback; + return this; + } + isMatched(name) { + return this.name === name || this.aliasNames.includes(name); + } + get isDefaultCommand() { + return this.name === "" || this.aliasNames.includes("!"); + } + get isGlobalCommand() { + return this instanceof GlobalCommand; + } + hasOption(name) { + name = name.split(".")[0]; + return this.options.find((option) => { + return option.names.includes(name); + }); + } + outputHelp() { + const {name, commands} = this.cli; + const { + versionNumber, + options: globalOptions, + helpCallback + } = this.cli.globalCommand; + let sections = [ + { + body: `${name}${versionNumber ? `/${versionNumber}` : ""}` + } + ]; + sections.push({ + title: "Usage", + body: ` $ ${name} ${this.usageText || this.rawName}` + }); + const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; + if (showCommands) { + const longestCommandName = findLongest(commands.map((command) => command.rawName)); + sections.push({ + title: "Commands", + body: commands.map((command) => { + return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`; + }).join("\n") + }); + sections.push({ + title: `For more info, run any command with the \`--help\` flag`, + body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n") + }); + } + let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []]; + if (!this.isGlobalCommand && !this.isDefaultCommand) { + options = options.filter((option) => option.name !== "version"); + } + if (options.length > 0) { + const longestOptionName = findLongest(options.map((option) => option.rawName)); + sections.push({ + title: "Options", + body: options.map((option) => { + return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`; + }).join("\n") + }); + } + if (this.examples.length > 0) { + sections.push({ + title: "Examples", + body: this.examples.map((example) => { + if (typeof example === "function") { + return example(name); + } + return example; + }).join("\n") + }); + } + if (helpCallback) { + sections = helpCallback(sections) || sections; + } + console.log(sections.map((section) => { + return section.title ? `${section.title}: +${section.body}` : section.body; + }).join("\n\n")); + } + outputVersion() { + const {name} = this.cli; + const {versionNumber} = this.cli.globalCommand; + if (versionNumber) { + console.log(`${name}/${versionNumber} ${platformInfo}`); + } + } + checkRequiredArgs() { + const minimalArgsCount = this.args.filter((arg) => arg.required).length; + if (this.cli.args.length < minimalArgsCount) { + throw new CACError(`missing required args for command \`${this.rawName}\``); + } + } + checkUnknownOptions() { + const {options, globalCommand} = this.cli; + if (!this.config.allowUnknownOptions) { + for (const name of Object.keys(options)) { + if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) { + throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``); + } + } + } + } + checkOptionValue() { + const {options: parsedOptions, globalCommand} = this.cli; + const options = [...globalCommand.options, ...this.options]; + for (const option of options) { + const value = parsedOptions[option.name.split(".")[0]]; + if (option.required) { + const hasNegated = options.some((o) => o.negated && o.names.includes(option.name)); + if (value === true || value === false && !hasNegated) { + throw new CACError(`option \`${option.rawName}\` value is missing`); + } + } + } + } +} +class GlobalCommand extends Command { + constructor(cli) { + super("@@global@@", "", {}, cli); + } +} + +var __assign = Object.assign; +class CAC extends events.EventEmitter { + constructor(name = "") { + super(); + this.name = name; + this.commands = []; + this.rawArgs = []; + this.args = []; + this.options = {}; + this.globalCommand = new GlobalCommand(this); + this.globalCommand.usage(" [options]"); + } + usage(text) { + this.globalCommand.usage(text); + return this; + } + command(rawName, description, config) { + const command = new Command(rawName, description || "", config, this); + command.globalCommand = this.globalCommand; + this.commands.push(command); + return command; + } + option(rawName, description, config) { + this.globalCommand.option(rawName, description, config); + return this; + } + help(callback) { + this.globalCommand.option("-h, --help", "Display this message"); + this.globalCommand.helpCallback = callback; + this.showHelpOnExit = true; + return this; + } + version(version, customFlags = "-v, --version") { + this.globalCommand.version(version, customFlags); + this.showVersionOnExit = true; + return this; + } + example(example) { + this.globalCommand.example(example); + return this; + } + outputHelp() { + if (this.matchedCommand) { + this.matchedCommand.outputHelp(); + } else { + this.globalCommand.outputHelp(); + } + } + outputVersion() { + this.globalCommand.outputVersion(); + } + setParsedInfo({args, options}, matchedCommand, matchedCommandName) { + this.args = args; + this.options = options; + if (matchedCommand) { + this.matchedCommand = matchedCommand; + } + if (matchedCommandName) { + this.matchedCommandName = matchedCommandName; + } + return this; + } + unsetMatchedCommand() { + this.matchedCommand = void 0; + this.matchedCommandName = void 0; + } + parse(argv = processArgs, { + run = true + } = {}) { + this.rawArgs = argv; + if (!this.name) { + this.name = argv[1] ? getFileName(argv[1]) : "cli"; + } + let shouldParse = true; + for (const command of this.commands) { + const parsed = this.mri(argv.slice(2), command); + const commandName = parsed.args[0]; + if (command.isMatched(commandName)) { + shouldParse = false; + const parsedInfo = __assign(__assign({}, parsed), { + args: parsed.args.slice(1) + }); + this.setParsedInfo(parsedInfo, command, commandName); + this.emit(`command:${commandName}`, command); + } + } + if (shouldParse) { + for (const command of this.commands) { + if (command.name === "") { + shouldParse = false; + const parsed = this.mri(argv.slice(2), command); + this.setParsedInfo(parsed, command); + this.emit(`command:!`, command); + } + } + } + if (shouldParse) { + const parsed = this.mri(argv.slice(2)); + this.setParsedInfo(parsed); + } + if (this.options.help && this.showHelpOnExit) { + this.outputHelp(); + run = false; + this.unsetMatchedCommand(); + } + if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) { + this.outputVersion(); + run = false; + this.unsetMatchedCommand(); + } + const parsedArgv = {args: this.args, options: this.options}; + if (run) { + this.runMatchedCommand(); + } + if (!this.matchedCommand && this.args[0]) { + this.emit("command:*"); + } + return parsedArgv; + } + mri(argv, command) { + const cliOptions = [ + ...this.globalCommand.options, + ...command ? command.options : [] + ]; + const mriOptions = getMriOptions(cliOptions); + let argsAfterDoubleDashes = []; + const doubleDashesIndex = argv.indexOf("--"); + if (doubleDashesIndex > -1) { + argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); + argv = argv.slice(0, doubleDashesIndex); + } + let parsed = mri2(argv, mriOptions); + parsed = Object.keys(parsed).reduce((res, name) => { + return __assign(__assign({}, res), { + [camelcaseOptionName(name)]: parsed[name] + }); + }, {_: []}); + const args = parsed._; + const options = { + "--": argsAfterDoubleDashes + }; + const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; + let transforms = Object.create(null); + for (const cliOption of cliOptions) { + if (!ignoreDefault && cliOption.config.default !== void 0) { + for (const name of cliOption.names) { + options[name] = cliOption.config.default; + } + } + if (Array.isArray(cliOption.config.type)) { + if (transforms[cliOption.name] === void 0) { + transforms[cliOption.name] = Object.create(null); + transforms[cliOption.name]["shouldTransform"] = true; + transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; + } + } + } + for (const key of Object.keys(parsed)) { + if (key !== "_") { + const keys = key.split("."); + setDotProp(options, keys, parsed[key]); + setByType(options, transforms); + } + } + return { + args, + options + }; + } + runMatchedCommand() { + const {args, options, matchedCommand: command} = this; + if (!command || !command.commandAction) + return; + command.checkUnknownOptions(); + command.checkOptionValue(); + command.checkRequiredArgs(); + const actionArgs = []; + command.args.forEach((arg, index) => { + if (arg.variadic) { + actionArgs.push(args.slice(index)); + } else { + actionArgs.push(args[index]); + } + }); + actionArgs.push(options); + return command.commandAction.apply(this, actionArgs); + } +} + +const cac = (name = "") => new CAC(name); + +exports.CAC = CAC; +exports.Command = Command; +exports.cac = cac; +exports.default = cac; diff --git a/web/node_modules/cac/dist/index.mjs b/web/node_modules/cac/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7c1c4440c6ed22a3829f828364b06669c56b31c9 --- /dev/null +++ b/web/node_modules/cac/dist/index.mjs @@ -0,0 +1,617 @@ +import { EventEmitter } from 'events'; + +function toArr(any) { + return any == null ? [] : Array.isArray(any) ? any : [any]; +} + +function toVal(out, key, val, opts) { + var x, old=out[key], nxt=( + !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val)) + : typeof val === 'boolean' ? val + : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val)) + : (x = +val,x * 0 === 0) ? x : val + ); + out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]); +} + +function mri2 (args, opts) { + args = args || []; + opts = opts || {}; + + var k, arr, arg, name, val, out={ _:[] }; + var i=0, j=0, idx=0, len=args.length; + + const alibi = opts.alias !== void 0; + const strict = opts.unknown !== void 0; + const defaults = opts.default !== void 0; + + opts.alias = opts.alias || {}; + opts.string = toArr(opts.string); + opts.boolean = toArr(opts.boolean); + + if (alibi) { + for (k in opts.alias) { + arr = opts.alias[k] = toArr(opts.alias[k]); + for (i=0; i < arr.length; i++) { + (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); + } + } + } + + for (i=opts.boolean.length; i-- > 0;) { + arr = opts.alias[opts.boolean[i]] || []; + for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]); + } + + for (i=opts.string.length; i-- > 0;) { + arr = opts.alias[opts.string[i]] || []; + for (j=arr.length; j-- > 0;) opts.string.push(arr[j]); + } + + if (defaults) { + for (k in opts.default) { + name = typeof opts.default[k]; + arr = opts.alias[k] = opts.alias[k] || []; + if (opts[name] !== void 0) { + opts[name].push(k); + for (i=0; i < arr.length; i++) { + opts[name].push(arr[i]); + } + } + } + } + + const keys = strict ? Object.keys(opts.alias) : []; + + for (i=0; i < len; i++) { + arg = args[i]; + + if (arg === '--') { + out._ = out._.concat(args.slice(++i)); + break; + } + + for (j=0; j < arg.length; j++) { + if (arg.charCodeAt(j) !== 45) break; // "-" + } + + if (j === 0) { + out._.push(arg); + } else if (arg.substring(j, j + 3) === 'no-') { + name = arg.substring(j + 3); + if (strict && !~keys.indexOf(name)) { + return opts.unknown(arg); + } + out[name] = false; + } else { + for (idx=j+1; idx < arg.length; idx++) { + if (arg.charCodeAt(idx) === 61) break; // "=" + } + + name = arg.substring(j, idx); + val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]); + arr = (j === 2 ? [name] : name); + + for (idx=0; idx < arr.length; idx++) { + name = arr[idx]; + if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); + toVal(out, name, (idx + 1 < arr.length) || val, opts); + } + } + } + + if (defaults) { + for (k in opts.default) { + if (out[k] === void 0) { + out[k] = opts.default[k]; + } + } + } + + if (alibi) { + for (k in out) { + arr = opts.alias[k] || []; + while (arr.length > 0) { + out[arr.shift()] = out[k]; + } + } + } + + return out; +} + +const removeBrackets = (v) => v.replace(/[<[].+/, "").trim(); +const findAllBrackets = (v) => { + const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; + const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; + const res = []; + const parse = (match) => { + let variadic = false; + let value = match[1]; + if (value.startsWith("...")) { + value = value.slice(3); + variadic = true; + } + return { + required: match[0].startsWith("<"), + value, + variadic + }; + }; + let angledMatch; + while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(angledMatch)); + } + let squareMatch; + while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(squareMatch)); + } + return res; +}; +const getMriOptions = (options) => { + const result = {alias: {}, boolean: []}; + for (const [index, option] of options.entries()) { + if (option.names.length > 1) { + result.alias[option.names[0]] = option.names.slice(1); + } + if (option.isBoolean) { + if (option.negated) { + const hasStringTypeOption = options.some((o, i) => { + return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean"; + }); + if (!hasStringTypeOption) { + result.boolean.push(option.names[0]); + } + } else { + result.boolean.push(option.names[0]); + } + } + } + return result; +}; +const findLongest = (arr) => { + return arr.sort((a, b) => { + return a.length > b.length ? -1 : 1; + })[0]; +}; +const padRight = (str, length) => { + return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; +}; +const camelcase = (input) => { + return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => { + return p1 + p2.toUpperCase(); + }); +}; +const setDotProp = (obj, keys, val) => { + let i = 0; + let length = keys.length; + let t = obj; + let x; + for (; i < length; ++i) { + x = t[keys[i]]; + t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : []; + } +}; +const setByType = (obj, transforms) => { + for (const key of Object.keys(transforms)) { + const transform = transforms[key]; + if (transform.shouldTransform) { + obj[key] = Array.prototype.concat.call([], obj[key]); + if (typeof transform.transformFunction === "function") { + obj[key] = obj[key].map(transform.transformFunction); + } + } + } +}; +const getFileName = (input) => { + const m = /([^\\\/]+)$/.exec(input); + return m ? m[1] : ""; +}; +const camelcaseOptionName = (name) => { + return name.split(".").map((v, i) => { + return i === 0 ? camelcase(v) : v; + }).join("."); +}; +class CACError extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error(message).stack; + } + } +} + +class Option { + constructor(rawName, description, config) { + this.rawName = rawName; + this.description = description; + this.config = Object.assign({}, config); + rawName = rawName.replace(/\.\*/g, ""); + this.negated = false; + this.names = removeBrackets(rawName).split(",").map((v) => { + let name = v.trim().replace(/^-{1,2}/, ""); + if (name.startsWith("no-")) { + this.negated = true; + name = name.replace(/^no-/, ""); + } + return camelcaseOptionName(name); + }).sort((a, b) => a.length > b.length ? 1 : -1); + this.name = this.names[this.names.length - 1]; + if (this.negated && this.config.default == null) { + this.config.default = true; + } + if (rawName.includes("<")) { + this.required = true; + } else if (rawName.includes("[")) { + this.required = false; + } else { + this.isBoolean = true; + } + } +} + +const processArgs = process.argv; +const platformInfo = `${process.platform}-${process.arch} node-${process.version}`; + +class Command { + constructor(rawName, description, config = {}, cli) { + this.rawName = rawName; + this.description = description; + this.config = config; + this.cli = cli; + this.options = []; + this.aliasNames = []; + this.name = removeBrackets(rawName); + this.args = findAllBrackets(rawName); + this.examples = []; + } + usage(text) { + this.usageText = text; + return this; + } + allowUnknownOptions() { + this.config.allowUnknownOptions = true; + return this; + } + ignoreOptionDefaultValue() { + this.config.ignoreOptionDefaultValue = true; + return this; + } + version(version, customFlags = "-v, --version") { + this.versionNumber = version; + this.option(customFlags, "Display version number"); + return this; + } + example(example) { + this.examples.push(example); + return this; + } + option(rawName, description, config) { + const option = new Option(rawName, description, config); + this.options.push(option); + return this; + } + alias(name) { + this.aliasNames.push(name); + return this; + } + action(callback) { + this.commandAction = callback; + return this; + } + isMatched(name) { + return this.name === name || this.aliasNames.includes(name); + } + get isDefaultCommand() { + return this.name === "" || this.aliasNames.includes("!"); + } + get isGlobalCommand() { + return this instanceof GlobalCommand; + } + hasOption(name) { + name = name.split(".")[0]; + return this.options.find((option) => { + return option.names.includes(name); + }); + } + outputHelp() { + const {name, commands} = this.cli; + const { + versionNumber, + options: globalOptions, + helpCallback + } = this.cli.globalCommand; + let sections = [ + { + body: `${name}${versionNumber ? `/${versionNumber}` : ""}` + } + ]; + sections.push({ + title: "Usage", + body: ` $ ${name} ${this.usageText || this.rawName}` + }); + const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; + if (showCommands) { + const longestCommandName = findLongest(commands.map((command) => command.rawName)); + sections.push({ + title: "Commands", + body: commands.map((command) => { + return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`; + }).join("\n") + }); + sections.push({ + title: `For more info, run any command with the \`--help\` flag`, + body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n") + }); + } + let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []]; + if (!this.isGlobalCommand && !this.isDefaultCommand) { + options = options.filter((option) => option.name !== "version"); + } + if (options.length > 0) { + const longestOptionName = findLongest(options.map((option) => option.rawName)); + sections.push({ + title: "Options", + body: options.map((option) => { + return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`; + }).join("\n") + }); + } + if (this.examples.length > 0) { + sections.push({ + title: "Examples", + body: this.examples.map((example) => { + if (typeof example === "function") { + return example(name); + } + return example; + }).join("\n") + }); + } + if (helpCallback) { + sections = helpCallback(sections) || sections; + } + console.log(sections.map((section) => { + return section.title ? `${section.title}: +${section.body}` : section.body; + }).join("\n\n")); + } + outputVersion() { + const {name} = this.cli; + const {versionNumber} = this.cli.globalCommand; + if (versionNumber) { + console.log(`${name}/${versionNumber} ${platformInfo}`); + } + } + checkRequiredArgs() { + const minimalArgsCount = this.args.filter((arg) => arg.required).length; + if (this.cli.args.length < minimalArgsCount) { + throw new CACError(`missing required args for command \`${this.rawName}\``); + } + } + checkUnknownOptions() { + const {options, globalCommand} = this.cli; + if (!this.config.allowUnknownOptions) { + for (const name of Object.keys(options)) { + if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) { + throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``); + } + } + } + } + checkOptionValue() { + const {options: parsedOptions, globalCommand} = this.cli; + const options = [...globalCommand.options, ...this.options]; + for (const option of options) { + const value = parsedOptions[option.name.split(".")[0]]; + if (option.required) { + const hasNegated = options.some((o) => o.negated && o.names.includes(option.name)); + if (value === true || value === false && !hasNegated) { + throw new CACError(`option \`${option.rawName}\` value is missing`); + } + } + } + } +} +class GlobalCommand extends Command { + constructor(cli) { + super("@@global@@", "", {}, cli); + } +} + +var __assign = Object.assign; +class CAC extends EventEmitter { + constructor(name = "") { + super(); + this.name = name; + this.commands = []; + this.rawArgs = []; + this.args = []; + this.options = {}; + this.globalCommand = new GlobalCommand(this); + this.globalCommand.usage(" [options]"); + } + usage(text) { + this.globalCommand.usage(text); + return this; + } + command(rawName, description, config) { + const command = new Command(rawName, description || "", config, this); + command.globalCommand = this.globalCommand; + this.commands.push(command); + return command; + } + option(rawName, description, config) { + this.globalCommand.option(rawName, description, config); + return this; + } + help(callback) { + this.globalCommand.option("-h, --help", "Display this message"); + this.globalCommand.helpCallback = callback; + this.showHelpOnExit = true; + return this; + } + version(version, customFlags = "-v, --version") { + this.globalCommand.version(version, customFlags); + this.showVersionOnExit = true; + return this; + } + example(example) { + this.globalCommand.example(example); + return this; + } + outputHelp() { + if (this.matchedCommand) { + this.matchedCommand.outputHelp(); + } else { + this.globalCommand.outputHelp(); + } + } + outputVersion() { + this.globalCommand.outputVersion(); + } + setParsedInfo({args, options}, matchedCommand, matchedCommandName) { + this.args = args; + this.options = options; + if (matchedCommand) { + this.matchedCommand = matchedCommand; + } + if (matchedCommandName) { + this.matchedCommandName = matchedCommandName; + } + return this; + } + unsetMatchedCommand() { + this.matchedCommand = void 0; + this.matchedCommandName = void 0; + } + parse(argv = processArgs, { + run = true + } = {}) { + this.rawArgs = argv; + if (!this.name) { + this.name = argv[1] ? getFileName(argv[1]) : "cli"; + } + let shouldParse = true; + for (const command of this.commands) { + const parsed = this.mri(argv.slice(2), command); + const commandName = parsed.args[0]; + if (command.isMatched(commandName)) { + shouldParse = false; + const parsedInfo = __assign(__assign({}, parsed), { + args: parsed.args.slice(1) + }); + this.setParsedInfo(parsedInfo, command, commandName); + this.emit(`command:${commandName}`, command); + } + } + if (shouldParse) { + for (const command of this.commands) { + if (command.name === "") { + shouldParse = false; + const parsed = this.mri(argv.slice(2), command); + this.setParsedInfo(parsed, command); + this.emit(`command:!`, command); + } + } + } + if (shouldParse) { + const parsed = this.mri(argv.slice(2)); + this.setParsedInfo(parsed); + } + if (this.options.help && this.showHelpOnExit) { + this.outputHelp(); + run = false; + this.unsetMatchedCommand(); + } + if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) { + this.outputVersion(); + run = false; + this.unsetMatchedCommand(); + } + const parsedArgv = {args: this.args, options: this.options}; + if (run) { + this.runMatchedCommand(); + } + if (!this.matchedCommand && this.args[0]) { + this.emit("command:*"); + } + return parsedArgv; + } + mri(argv, command) { + const cliOptions = [ + ...this.globalCommand.options, + ...command ? command.options : [] + ]; + const mriOptions = getMriOptions(cliOptions); + let argsAfterDoubleDashes = []; + const doubleDashesIndex = argv.indexOf("--"); + if (doubleDashesIndex > -1) { + argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); + argv = argv.slice(0, doubleDashesIndex); + } + let parsed = mri2(argv, mriOptions); + parsed = Object.keys(parsed).reduce((res, name) => { + return __assign(__assign({}, res), { + [camelcaseOptionName(name)]: parsed[name] + }); + }, {_: []}); + const args = parsed._; + const options = { + "--": argsAfterDoubleDashes + }; + const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; + let transforms = Object.create(null); + for (const cliOption of cliOptions) { + if (!ignoreDefault && cliOption.config.default !== void 0) { + for (const name of cliOption.names) { + options[name] = cliOption.config.default; + } + } + if (Array.isArray(cliOption.config.type)) { + if (transforms[cliOption.name] === void 0) { + transforms[cliOption.name] = Object.create(null); + transforms[cliOption.name]["shouldTransform"] = true; + transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; + } + } + } + for (const key of Object.keys(parsed)) { + if (key !== "_") { + const keys = key.split("."); + setDotProp(options, keys, parsed[key]); + setByType(options, transforms); + } + } + return { + args, + options + }; + } + runMatchedCommand() { + const {args, options, matchedCommand: command} = this; + if (!command || !command.commandAction) + return; + command.checkUnknownOptions(); + command.checkOptionValue(); + command.checkRequiredArgs(); + const actionArgs = []; + command.args.forEach((arg, index) => { + if (arg.variadic) { + actionArgs.push(args.slice(index)); + } else { + actionArgs.push(args[index]); + } + }); + actionArgs.push(options); + return command.commandAction.apply(this, actionArgs); + } +} + +const cac = (name = "") => new CAC(name); + +export default cac; +export { CAC, Command, cac }; diff --git a/web/node_modules/cac/index-compat.js b/web/node_modules/cac/index-compat.js new file mode 100644 index 0000000000000000000000000000000000000000..6b8a78d3a5764e06c4082842ce0aa65f5b290d1d --- /dev/null +++ b/web/node_modules/cac/index-compat.js @@ -0,0 +1,11 @@ +const { cac, CAC, Command } = require('./dist/index') + +// For backwards compatibility +module.exports = cac + +Object.assign(module.exports, { + default: cac, + cac, + CAC, + Command, +}) diff --git a/web/node_modules/cac/mod.js b/web/node_modules/cac/mod.js new file mode 100644 index 0000000000000000000000000000000000000000..9d0e8943d5a3ec8d475469be5718e7567703ffff --- /dev/null +++ b/web/node_modules/cac/mod.js @@ -0,0 +1,2 @@ +// Deno users should use mod.ts instead +export * from './deno/index.ts' \ No newline at end of file diff --git a/web/node_modules/cac/mod.ts b/web/node_modules/cac/mod.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fac7d9f0539fa8fa85be89f4f673834bb0a38af --- /dev/null +++ b/web/node_modules/cac/mod.ts @@ -0,0 +1,2 @@ +// For Deno +export * from './deno/index.ts' diff --git a/web/node_modules/cac/package.json b/web/node_modules/cac/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2306bf35bbe5d451bf03d48ad77af475a5d9f747 --- /dev/null +++ b/web/node_modules/cac/package.json @@ -0,0 +1,104 @@ +{ + "name": "cac", + "version": "6.7.14", + "description": "Simple yet powerful framework for building command-line apps.", + "repository": { + "url": "egoist/cac", + "type": "git" + }, + "main": "index-compat.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./index-compat.js" + }, + "./package.json": "./package.json", + "./*": "./*" + }, + "files": [ + "dist", + "!**/__test__/**", + "/mod.js", + "/mod.ts", + "/deno", + "/index-compat.js" + ], + "scripts": { + "test": "jest", + "test:cov": "jest --coverage", + "build:deno": "node -r sucrase/register scripts/build-deno.ts", + "build:node": "rollup -c", + "build": "yarn build:deno && yarn build:node", + "toc": "markdown-toc -i README.md", + "prepublishOnly": "npm run build && cp mod.js mod.mjs", + "docs:api": "typedoc --out api-doc --readme none --exclude \"**/__test__/**\" --theme minimal" + }, + "author": "egoist <0x142857@gmail.com>", + "license": "MIT", + "devDependencies": { + "@babel/core": "^7.12.10", + "@babel/plugin-syntax-typescript": "^7.12.1", + "@rollup/plugin-commonjs": "^17.0.0", + "@rollup/plugin-node-resolve": "^11.0.0", + "@types/fs-extra": "^9.0.5", + "@types/jest": "^26.0.19", + "@types/mri": "^1.1.0", + "cz-conventional-changelog": "^2.1.0", + "esbuild": "^0.8.21", + "eslint-config-rem": "^3.0.0", + "execa": "^5.0.0", + "fs-extra": "^9.0.1", + "globby": "^11.0.1", + "husky": "^1.2.0", + "jest": "^24.9.0", + "lint-staged": "^8.1.0", + "markdown-toc": "^1.2.0", + "mri": "^1.1.6", + "prettier": "^2.2.1", + "rollup": "^2.34.2", + "rollup-plugin-dts": "^2.0.1", + "rollup-plugin-esbuild": "^2.6.1", + "semantic-release": "^17.3.0", + "sucrase": "^3.16.0", + "ts-jest": "^26.4.4", + "ts-node": "^9.1.1", + "typedoc": "^0.19.2", + "typescript": "^4.1.2" + }, + "engines": { + "node": ">=8" + }, + "release": { + "branch": "master" + }, + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + } + }, + "lint-staged": { + "linters": { + "*.{js,json,ts}": [ + "prettier --write", + "git add" + ], + "*.md": [ + "markdown-toc -i", + "prettier --write", + "git add" + ] + }, + "ignore": [ + "dist/**", + "mod.js" + ] + }, + "husky": { + "hooks": { + "pre-commit": "npm t && lint-staged" + } + } +} diff --git a/web/node_modules/chai/CODEOWNERS b/web/node_modules/chai/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..ea74b66ed5fdd99056149ed0ecfbbc409625ce15 --- /dev/null +++ b/web/node_modules/chai/CODEOWNERS @@ -0,0 +1 @@ +* @chaijs/chai diff --git a/web/node_modules/chai/CODE_OF_CONDUCT.md b/web/node_modules/chai/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..074addcc213bba8826190f78229542469384d57c --- /dev/null +++ b/web/node_modules/chai/CODE_OF_CONDUCT.md @@ -0,0 +1,58 @@ +# Contributor Code of Conduct + +> Read in: [Español](http://contributor-covenant.org/version/1/3/0/es/) | +[Français](http://contributor-covenant.org/version/1/3/0/fr/) | +[Italiano](http://contributor-covenant.org/version/1/3/0/it/) | +[Magyar](http://contributor-covenant.org/version/1/3/0/hu/) | +[Polskie](http://contributor-covenant.org/version/1/3/0/pl/) | +[Português](http://contributor-covenant.org/version/1/3/0/pt/) | +[Português do Brasil](http://contributor-covenant.org/version/1/3/0/pt_br/) + +As contributors and maintainers of this project, and in the interest of +fostering an open and welcoming community, we pledge to respect all people who +contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic + addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to +fairly and consistently applying these principles to every aspect of managing +this project. Project maintainers who do not follow or enforce the Code of +Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting a project maintainer at chaijs@keithcirkel.co.uk. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. Maintainers are +obligated to maintain confidentiality with regard to the reporter of an +incident. + + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.3.0, available at +[http://contributor-covenant.org/version/1/3/0/][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/3/0/ diff --git a/web/node_modules/chai/CONTRIBUTING.md b/web/node_modules/chai/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..258766eac38d23e8c872727f02c54e171bf61859 --- /dev/null +++ b/web/node_modules/chai/CONTRIBUTING.md @@ -0,0 +1,212 @@ +# Chai Contribution Guidelines + +We like to encourage you to contribute to the Chai.js repository. This should be as easy as possible for you but there are a few things to consider when contributing. The following guidelines for contribution should be followed if you want to submit a pull request or open an issue. + +Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features. + +#### Table of Contents + +- [TLDR;](#tldr) +- [Contributing](#contributing) + - [Bug Reports](#bugs) + - [Feature Requests](#features) + - [Pull Requests](#pull-requests) +- [Releasing](#releasing) +- [Support](#support) + - [Resources](#resources) + - [Core Contributors](#contributors) + + +## TLDR; + +- Creating an Issue or Pull Request requires a [GitHub](http://github.com) account. +- Issue reports should be **clear**, **concise** and **reproducible**. Check to see if your issue has already been resolved in the [master]() branch or already reported in Chai's [GitHub Issue Tracker](https://github.com/chaijs/chai/issues). +- In general, avoid submitting PRs for new Assertions without asking core contributors first. More than likely it would be better implemented as a plugin. +- Additional support is available via the [Google Group](http://groups.google.com/group/chaijs) or on irc.freenode.net#chaijs. +- **IMPORTANT**: By submitting a patch, you agree to allow the project owner to license your work under the same license as that used by the project. + + + + +## Contributing + +The issue tracker is the preferred channel for [bug reports](#bugs), +[feature requests](#features) and [submitting pull +requests](#pull-requests), but please respect the following restrictions: + +* Please **do not** use the issue tracker for personal support requests (use + [Google Group](https://groups.google.com/forum/#!forum/chaijs) or IRC). +* Please **do not** derail or troll issues. Keep the discussion on topic and + respect the opinions of others + + +### Bug Reports + +A bug is a **demonstrable problem** that is caused by the code in the repository. + +Guidelines for bug reports: + +1. **Use the GitHub issue search** — check if the issue has already been reported. +2. **Check if the issue has been fixed** — try to reproduce it using the latest `master` or development branch in the repository. +3. **Isolate the problem** — create a test case to demonstrate your issue. Provide either a repo, gist, or code sample to demonstrate you problem. + +A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What browser(s) and/or Node.js versions experience the problem? What would you expect to be the outcome? All these details will help people to fix any potential bugs. + +Example: + +> Short and descriptive example bug report title +> +> A summary of the issue and the browser/OS environment in which it occurs. If suitable, include the steps required to reproduce the bug. +> +> 1. This is the first step +> 2. This is the second step +> 3. Further steps, etc. +> +> `` - a link to the reduced test case OR +> ```js +> expect(a).to.equal('a'); +> // code sample +> ``` +> +> Any other information you want to share that is relevant to the issue being reported. This might include the lines of code that you have identified as causing the bug, and potential solutions (and your opinions on their merits). + + +### Feature Requests + +Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible. + +Furthermore, since Chai.js has a [robust plugin API](http://chaijs.com/guide/plugins/), we encourage you to publish **new Assertions** as plugins. If your feature is an enhancement to an **existing Assertion**, please propose your changes as an issue prior to opening a pull request. If the core Chai.js contributors feel your plugin would be better suited as a core assertion, they will invite you to open a PR in [chaijs/chai](https://github.com/chaijs/chai). + + +### Pull Requests + +- PRs for new core-assertions are advised against. +- PRs for core-assertion bug fixes are always welcome. +- PRs for enhancing the interfaces are always welcome. +- PRs that increase test coverage are always welcome. +- PRs are scrutinized for coding-style. + +Good pull requests - patches, improvements, new features - are a fantastic help. They should remain focused in scope and avoid containing unrelated commits. + +**Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project. + +Please adhere to the coding conventions used throughout a project (indentation, accurate comments, etc.) and any other requirements (such as test coverage). + +Follow this process if you'd like your work considered for inclusion in the project: + +1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork, and configure the remotes: + +```bash +# Clone your fork of the repo into the current directory +git clone https://github.com// +# Navigate to the newly cloned directory +cd +# Assign the original repo to a remote called "upstream" +git remote add upstream https://github.com// +``` + +2. If you cloned a while ago, get the latest changes from upstream: + +```bash +git checkout +git pull upstream +``` + +3. Create a new topic branch (off the main project development branch) to contain your feature, change, or fix: + +```bash +git checkout -b +``` + +4. Commit your changes in logical chunks. Use Git's [interactive rebase](https://help.github.com/articles/interactive-rebase) feature to tidy up your commits before making them public. + +5. Run you code to make sure it works. If you're still having problems please try to run `make clean` and then test your code again. + +```bash +npm test +# when finished running tests... +git checkout chai.js +``` + +6. Locally merge (or rebase) the upstream development branch into your topic branch: + +```bash +git pull [--rebase] upstream +``` + +7. Push your topic branch up to your fork: + +```bash +git push origin +``` + +8. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) with a clear title and description. + +**IMPORTANT**: By submitting a patch, you agree to allow the project owner to license your work under the same license as that used by the project. + + +## Releasing + +Releases can be **prepared** by anyone with access to the code. + +Simply run `make release-major`, `make release-minor`, or `make-release-patch` +and it will automatically do the following: + + - Build chai.js + - Bump the version numbers across the project + - Make a commit within git + +All you need to do is push the commit up and make a pull request, one of the core contributors will merge it and publish a release. + +### Publishing a Release + +Anyone who is a core contributor (see the [Core Contributors Heading in the Readme](https://github.com/chaijs/chai#core-contributors)) can publish a release: + +1. Go to the [Releases page on Github](https://github.com/chaijs/chai/releases) +2. Hit "Draft a new release" (if you can't see this, you're not a core contributor!) +3. Write human-friendly Release Notes based on changelog. + - The release title is "x.x.x / YYYY-MM-DD" (where x.x.x is the version number) + - If breaking changes, write migration tutorial(s) and reasoning. + - Callouts for community contributions (PRs) with links to PR and contributing user. + - Callouts for other fixes made by core contributors with links to issue. +4. Hit "Save Draft" and get other core contributors to check your work, or alternatively hit "Publish release" +5. That's it! + + +## Support + + +### Resources + +For most of the documentation you are going to want to visit [ChaiJS.com](http://chaijs.com). + +- [Getting Started Guide](http://chaijs.com/guide/) +- [API Reference](http://chaijs.com/api/) +- [Plugins](http://chaijs.com/plugins/) + +Or finally, you may find a core-contributor or like-minded developer in any of our support channels. + +- IRC: irc.freenode.org #chaijs +- [Mailing List / Google Group](https://groups.google.com/forum/#!forum/chaijs) + + +### Core Contributors + +Feel free to reach out to any of the core-contributors with you questions or concerns. We will do our best to respond in a timely manner. + +- Jake Luer + - GH: [@logicalparadox](https://github.com/logicalparadox) + - TW: [@jakeluer](http://twitter.com/jakeluer) + - IRC: logicalparadox +- Veselin Todorov + - GH: [@vesln](https://github.com/vesln/) + - TW: [@vesln](http://twitter.com/vesln) + - IRC: vesln +- Keith Cirkel + - GH: [@keithamus](https://github.com/keithamus) + - TW: [@keithamus](http://twitter.com/keithamus) + - IRC: keithamus +- Lucas Fernandes da Costa + - GH: [@lucasfcosta](https://github.com/lucasfcosta) + - TW: [@lfernandescosta](https://twitter.com/lfernandescosta) + - IRC: lucasfcosta diff --git a/web/node_modules/chai/History.md b/web/node_modules/chai/History.md new file mode 100644 index 0000000000000000000000000000000000000000..5b5ae7b02948c5b5f4664151447f0f7b67ac30c7 --- /dev/null +++ b/web/node_modules/chai/History.md @@ -0,0 +1,1059 @@ +### Note + +As of 3.0.0, the History.md file has been deprecated. [Please refer to the full +commit logs available on GitHub](https://github.com/chaijs/chai/commits). + +--- + +2.3.0 / 2015-04-26 +================== + + * Merge pull request #423 from ehntoo/patch-1 + * Merge pull request #422 from ljharb/fix_descriptor_tests + * Fix a small bug in the .null assertion docs + * Use a regex to account for property ordering issues across engines. + * Add `make test-firefox` + * Merge pull request #417 from astorije/astorije/minimalist-typo + * Remove trailing whitespaces + * Fix super minor typo in an example + * Merge pull request #408 from ljharb/enumerableProperty + * Add `ownPropertyDescriptor` assertion. + +2.2.0 / 2015-03-26 +================== + + * Merge pull request #405 from chaijs/deep-escape-doc-tweaks + * Tweak documentation on `.deep` flag. + * Merge pull request #402 from umireon/escaping-dot-should-be-taken + * Documentation of escaping in `.deep` flag. + * take regular expression apart + * Feature: backslash-escaping in `.deep.property` + * Escaping dot should be taken in deep property + +2.1.2 / 2015-03-15 +================== + + * Merge pull request #396 from chaijs/add-keith-cirkel-contributing-md + * Add Keith Cirkel to CONTRIBUTING.md + * Merge pull request #395 from cjqed/386-assert-operator-no-eval + * No longer using eval on assert operator #386 + * Merge pull request #389 from chaijs/update-git-summary + * Update `git summary` in README + +2.1.1 / 2015-03-04 +================== + + * Merge pull request #385 from eldritch-fossicker/master + * updates to reflect code style preference from @keithamus + * fix indexing into array with deep propery + * Merge pull request #382 from astorije/patch-2 + * Merge pull request #383 from gurdiga/config-doc-wording-improvement + * config.truncateThreshold docs: simpler wording + * Add missing docstring for showDiff argument of assert + * Merge pull request #381 from astorije/patch-1 + * Add a minor precision that empty asserts on strings too. + * Merge pull request #379 from dcneiner/should-primitive-fix + * Primitives now use valueOf in shouldGetter + +2.1.0 / 2015-02-23 +================== + + * Merge pull request #374 from jmm/v2.0.1 + * Increment version to 2.0.1. + * Merge pull request #365 from chaijs/fix-travis + * Fix travis.yml deploy + * Merge pull request #356 from Soviut/master + * documented fail methods for expect and should interfaces + * fail method added directly to expect + +2.0.0 / 2015-02-09 +================== + + * Merge pull request #361 from gregglind/b265-keys-object + * fix #359. Add `.keys(object)` + * Merge pull request #359 from gregglind/b359-unexpected-keys-sort + * Fix #359 keys() sorts input unexpectedly + * contrib: publish release strategy and travis npm creds #337 + * Merge pull request #357 from danilovaz/master + * Update copyright date + * Merge pull request #349 from toastynerd/add-which-chain-method + * add the which chain method as per issue #347 + * Merge pull request #333 from cmpolis/change-assertions + * more `by` cleanup + * cleaned out `.by` for #333 + * Merge pull request #335 from DingoEatingFuzz/expose-util + * Expose chai util through the chai object + * cleanup (per notes on pr #333) + * updated `change` to work w/ non-number values + tests + * Merge pull request #334 from hurrymaplelad/patch-1 + * Typo, the flag is called 'contains' with an 's' + * updated assertion interface with `change` (#330) + * added `change`,`increase`,`decrease` assertions (#330) + * assert tests for `change`,`increase`,`decrease` + * expect/should tests for `change`,`increase`,`decrease` + * Merge pull request #328 from lo1tuma/issue-327 + * Add includes and contains alias (fixes #327) + * Merge pull request #325 from chasenlehara/overwriteChainableMethodDocs + * Fix docs for overwriteChainableMethod parameters + * Merge pull request #317 from jasonkarns/patch-2 + * Merge pull request #318 from jasonkarns/patch-3 + * Merge pull request #316 from jasonkarns/patch-1 + * typos in docs + * minor docs typo + * update docs: getAllFlags -> transferFlags + * Merge pull request #313 from cjqed/254-expect-any-all + * Added the all and any flags for keys assertion, with all being the default behavior + * Merge pull request #312 from cjqed/291-assert-same-deep-members + * Changed public comment of sameDeepMemebers to be more clear + * Fixes issue #291, adds assert.sameDeepMembers + * Merge pull request #311 from cjqed/305-above-below-on-assert + * Merge pull request #308 from prodatakey/hasproperty + * Issue #305 fixed, added assert.isAbove and assert.isBelow + * Fix typo + * More unit tests for new utility functions + * Refactor common functionality, document, test + * Refactor if statement out + * Small unit test fix + * Handle array indexing terminating paths + * Merge pull request #309 from ericdouglas/iterableEqual-couting-once + * couting variables just once + * Fix properties with `undefined` value pass property assertion + * Merge pull request #306 from chaijs/revert-297-noopchainfunc + * Revert "Allows writing lint-friendly tests" + +1.10.0 / 2014-11-10 +================== + + * Merge pull request #297 from prodatakey/noopchainfunc + * Merge pull request #300 from julienw/299-fix-getMessage-test + * Fix #299: the test is defining global variables + * Add a couple more unit tests + * Add unit tests for chained terminating property asserts + * Revise documentation wording + * Add docs for function style NOOP asserts + * Make the NOOP function a shared constant + * Merge pull request #298 from dasilvacontin/negativeZeroLogging + * why not more assertions + * added test for inspecting `-0` + * a more readable/simple condition statement, as pointed out by @keithamus + * added check for logging negative zero + * Change test to not trigger argument bug + * Allows writing lint-friendly tests + * readme: update contributors for 1.9.2 + +1.9.2 / 2014-09-29 +================== + + * Merge pull request #268 from charlierudolph/cr-lazyMessages + * Merge pull request #269 from charlierudolph/cr-codeCleanup + * Merge pull request #277 from charlierudolph/fix-doc + * Merge pull request #279 from mohayonao/fix-closeTo + * Merge pull request #292 from boneskull/mocha + * resolves #255: upgrade mocha + * Merge pull request #289 from charlierudolph/cr-dryUpCode + * Dry up code + * Merge pull request #275 from DrRataplan/master + * assert: .closeTo() verify value's type before assertion + * Rewrite pretty-printing HTML elements to prevent throwing internal errors Fixes errors occuring when using a non-native DOM implementation + * Fix assert documentation + * Remove unused argument + * Allow messages to be functions + * Merge pull request #267 from shinnn/master + * Use SVG badge + * Merge pull request #264 from cjthompson/keys_diff + * Show diff for keys assertion + +1.9.1 / 2014-03-19 +================== + + * deps update + * util: [getActual] select actual logic now allows undefined for actual. Closes #183 + * docs: [config] make public, express param type + * Merge pull request #251 from romario333/threshold3 + * Fix issue #166 - configurable threshold in objDisplay. + * Move configuration options to config.js. + * Merge pull request #233 from Empeeric/master + * Merge pull request #244 from leider/fix_for_contains + * Merge pull request #247 from didoarellano/typo-fixes + * Fix typos + * Merge pull request #245 from lfac-pt/patch-1 + * Update `exports.version` to 1.9.0 + * aborting loop on finding + * declaring variable only once + * additional test finds incomplete implementation + * simplified code + * fixing #239 (without changing chai.js) + * ssfi as it should be + * Merge pull request #228 from duncanbeevers/deep_members + * Deep equality check for collection membership + +1.9.0 / 2014-01-29 +================== + + * docs: add contributing.md #238 + * assert: .throws() returns thrown error. Closes #185 + * Merge pull request #232 from laconbass/assert-throws + * assert: .fail() parameter mismatch. Closes #206 + * Merge branch 'karma-fixes' + * Add karma phantomjs launcher + * Use latest karma and sauce launcher + * Karma tweaks + * Merge pull request #230 from jkroso/include + * Merge pull request #237 from chaijs/coverage + * Add coverage to npmignore + * Remove lib-cov from test-travisci dependents + * Remove the not longer needed lcov reporter + * Test coverage with istanbul + * Remove jscoverage + * Remove coveralls + * Merge pull request #226 from duncanbeevers/add_has + * Avoid error instantiation if possible on assert.throws + * Merge pull request #231 from duncanbeevers/update_copyright_year + * Update Copyright notices to 2014 + * handle negation correctly + * add failing test case + * support `{a:1,b:2}.should.include({a:1})` + * Merge pull request #224 from vbardales/master + * Add `has` to language chains + * Merge pull request #219 from demands/overwrite_chainable + * return error on throw method to chain on error properties, possibly different from message + * util: store chainable behavior in a __methods object on ctx + * util: code style fix + * util: add overwriteChainableMethod utility (for #215) + * Merge pull request #217 from demands/test_cleanup + * test: make it possible to run utilities tests with --watch + * makefile: change location of karma-runner bin script + * Merge pull request #202 from andreineculau/patch-2 + * test: add tests for throwing custom errors + * Merge pull request #201 from andreineculau/patch-1 + * test: updated for the new assertion errors + * core: improve message for assertion errors (throw assertion) + +1.8.1 / 2013-10-10 +================== + + * pkg: update deep-eql version + +1.8.0 / 2013-09-18 +================== + + * test: [sauce] add a few more browsers + * Merge branch 'refactor/deep-equal' + * util: remove embedded deep equal utility + * util: replace embedded deep equal with external module + * Merge branch 'feature/karma' + * docs: add sauce badge to readme [ci skip] + * test: [sauce] use karma@canary to prevent timeouts + * travis: only run on node 0.10 + * test: [karma] use karma phantomjs runner + * Merge pull request #181 from tricknotes/fix-highlight + * Fix highlight for example code + +1.7.2 / 2013-06-27 +================== + + * coverage: add coveralls badge + * test: [coveralls] add coveralls api integration. testing travis-ci integration + * Merge branch 'master' of github.com:chaijs/chai + * Merge branch 'feature/bower' + * Merge pull request #180 from tricknotes/modify-method-title + * Merge pull request #179 from tricknotes/highlight-code-example + * Modify method title to include argument name + * Fix to highlight code example + * bower: granular ignores + +1.7.1 / 2013-06-24 +================== + + * Merge branch 'feature/bower'. #175 + * bower: add json file + * build: browser + +1.7.0 / 2013-06-17 +================== + + * error: remove internal assertion error constructor + * core: [assertion-error] replace internal assertion error with dep + * deps: add chaijs/assertion-error@1.0.0 + * docs: fix typo in source file. #174 + * Merge pull request #174 from piecioshka/master + * typo + * Merge branch 'master' of github.com:chaijs/chai + * pkg: lock mocha/mocha-phantomjs versions (for now) + * Merge pull request #173 from chaijs/inspect-fix + * Fix `utils.inspect` with custom object-returning inspect()s. + * Merge pull request #171 from Bartvds/master + * replaced tabs with 2 spaces + * added assert.notOk() + * Merge pull request #169 from katsgeorgeek/topics/master + * Fix comparison objects. + +1.6.1 / 2013-06-05 +================== + + * Merge pull request #168 from katsgeorgeek/topics/master + * Add test for different RegExp flags. + * Add test for regexp comparison. + * Downgrade mocha version for fix running Phantom tests. + * Fix comparison equality of two regexps. + * Merge pull request #161 from brandonpayton/master + * Fix documented name for assert interfaces isDefined method + +1.6.0 / 2013-04-29 +================== + + * build: browser + * assert: [(not)include] throw on incompatible haystack. Closes #142 + * assert: [notInclude] add assert.notInclude. Closes #158 + * browser build + * makefile: force browser build on browser-test + * makefile: use component for browser build + * core: [assertions] remove extraneous comments + * Merge branch 'master' of github.com:chaijs/chai + * test: [assert] deep equal ordering + * Merge pull request #153 from NickHeiner/array-assertions + * giving members a no-flag assertion + * Code review comments - changing syntax + * Code review comments + * Adding members and memberEquals assertions for checking for subsets and set equality. Implements chaijs/chai#148. + * Merge pull request #140 from RubenVerborgh/function-prototype + * Restore the `call` and `apply` methods of Function when adding a chainable method. + * readme: 2013 + * notes: migration notes for deep equal changes + * test: for ever err() there must be a passing version + +1.5.0 / 2013-02-03 +================== + + * docs: add Release Notes for non-gitlog summary of changes. + * lib: update copyright to 2013 + * Merge branch 'refactor/travis' + * makefile: remove test-component for full test run + * pkg: script test now runs make test so travis will test browser + * browser: build + * tests: refactor some tests to support new objDisplay output + * test: [bootstrap] normalize boostrap across all test scenarios + * assertions: refactor some assertions to use objDisplay instead of inspect + * util: [objDisplay] normalize output of functions + * makefile: refactor for full build scenarios + * component: fix build bug where missing util:type file + * assertions: [throw] code cleanup + * Merge branch 'refactor/typeDetection' + * browser: build + * makefile: chai.js is .PHONY so it builds every time + * test: [expect] add arguments type detection test + * core/assertions: [type] (a/an) refactor to use type detection utility + * util: add cross-browser type detection utility + * Merge branch 'feature/component' + * browser: build + * component: add component.json file + * makefile: refactor for fine grain control of testing scenarios + * test: add mochaPhantomJS support and component test file + * deps: add component and mocha-phantomjs for browser testing + * ignore: update ignore files for component support + * travis: run for all branches + * Merge branch 'feature/showDiff' + * test: [Assertion] configruable showDiff flag. Closes #132 + * lib: [Assertion] add configurable showDiff flag. #132 + * Merge branch 'feature/saucelabs' + * Merge branch 'master' into feature/saucelabs + * browser: build + * support: add mocha cloud runner, client, and html test page + * test: [saucelabs] add auth placeholder + * deps: add mocha-cloud + * Merge pull request #136 from whatthejeff/message_fix + * Merge pull request #138 from timnew/master + * Fix issue #137, test message existence by using message!=null rather than using message + * Fixed backwards negation messages. + * Merge pull request #133 from RubenVerborgh/throw + * Functions throwing strings can reliably be tested. + * Merge pull request #131 from RubenVerborgh/proto + * Cache whether __proto__ is supported. + * Use __proto__ if available. + * Determine the property names to exclude beforehand. + * Merge pull request #126 from RubenVerborgh/eqls + * Add alias eqls for eql. + * Use inherited enumerable properties in deep equality comparison. + * Show inherited properties when inspecting an object. + * Add new getProperties and getEnumerableProperties utils. + * showDiff: force true for equal and eql + +1.4.2 / 2012-12-21 +================== + + * browser build: (object diff support when used with mocha) #106 + * test: [display] array test for mocha object diff + * browser: no longer need different AssertionError constructor + +1.4.1 / 2012-12-21 +================== + + * showDiff: force diff for equal and eql. #106 + * test: [expect] type null. #122 + * Merge pull request #115 from eshao/fix-assert-Throw + * FIX: assert.Throw checks error type/message + * TST: assert.Throw should check error type/message + +1.4.0 / 2012-11-29 +================== + + * pre-release browser build + * clean up index.js to not check for cov, revert package.json to use index.js + * convert tests to use new bootstrap + * refactor testing bootstrap + * use spaces (not tabs). Clean up #114 + * Merge pull request #114 from trantorLiu/master + * Add most() (alias: lte) and least() (alias: gte) to the API with new chainers "at" and "of". + * Change `main` to ./lib/chai. Fixes #28. + * Merge pull request #104 from connec/deep_equals_circular_references_ + * Merge pull request #109 from nnarhinen/patch-1 + * Check for 'actual' type + * Added support for circular references when checking deep (in)equality. + +1.3.0 / 2012-10-01 +================== + + * browser build w/ folio >= 0.3.4. Closes #99 + * add back buffer test for deep equal + * do not write flags to assertion.prototype + * remove buffer test from expect + * browser build + * improve documentation of custom error messages + * Merge branch 'master' of git://github.com/Liffft/chai into Liffft-master + * browser build + * improved buffer deep equal checking + * mocha is npm test command + * Cleaning up the js style… + * expect tests now include message pass-through + * packaging up browser-side changes… + * Increasing Throws error message verbosity + * Should syntax: piping message through + * Make globalShould test work in browser too. + * Add a setter for `Object.prototype.should`. Closes #86. + +1.2.0 / 2012-08-07 +================== + + * Merge branch 'feature/errmsg' + * browser build + * comment updates for utilities + * tweak objDislay to only kick in if object inspection is too long + * Merge branch 'master' into feature/errmsg + * add display sample for error message refactor + * first draft of error message refactor. #93 + * add `closeTo` assertion to `assert` interface. Closes #89. + * update folio build for better require.js handling. Closes #85 + * Merge pull request #92 from paulmillr/topics/add-dom-checks + * Add check for DOM objects. + * browser build + * Merge branch 'master' of github.com:chaijs/chai + * bug - getActual not defaulting to assertion subject + * Merge pull request #88 from pwnall/master + * Don't inspect() assertion arguments if the assertion passes. + +1.1.1 / 2012-07-09 +================== + + * improve commonjs support on browser build + * Merge pull request #83 from tkazec/equals + * Document .equals + * Add .equals as an alias of .equal + * remove unused browser prefix/suffix + * Merge branch 'feature/folio-build' + * browser build + * using folio to compile + * clean up makefile + * early folio 0.3.x support + +1.1.0 / 2012-06-26 +================== + + * browser build + * Disable "Assertion.includeStack is false" test in IE. + * Use `utils.getName` for all function inspections. + * Merge pull request #80 from kilianc/closeTo + * fixes #79 + * browser build + * expand docs to indicate change of subject for chaining. Closes #78 + * add `that` chain noop + * Merge branch 'bug/74' + * comments on how to property use `length` as chain. Closes #74 + * tests for length as chainable property. #74 + * add support for `length` as chainable prop/method. + * Merge branch 'bug/77' + * tests for getPathValue when working with nested arrays. Closes #77 + * add getPathValue support for nested arrays + * browser build + * fix bug for missing browser utils + * compile tool aware of new folder layout + * Merge branch 'refactor/1dot1' + * move core assertions to own file and refactor all using utils + * rearrange folder structure + +1.0.4 / 2012-06-03 +================== + + * Merge pull request #68 from fizker/itself + * Added itself chain. + * simplify error inspections for cross browser compatibility + * fix safari `addChainableMethod` errors. Closes #69 + +1.0.3 / 2012-05-27 +================== + + * Point Travis badge to the right place. + * Make error message for eql/deep.equal more clear. + * Fix .not.deep.equal. + * contributors list + +1.0.2 / 2012-05-26 +================== + + * Merge pull request #67 from chaijs/chaining-and-flags + * Browser build. + * Use `addChainableMethod` to get away from `__proto__` manipulation. + * New `addChainableMethod` utility. + * Replace `getAllFlags` with `transferFlags` utility. + * browser build + * test - get all flags + * utility - get all flags + * Add .mailmap to .npmignore. + * Add a .mailmap file to fix my name in shortlogs. + +1.0.1 / 2012-05-18 +================== + + * browser build + * Fixing "an" vs. "a" grammar in type assertions. + * Uniformize `assert` interface inline docs. + * Don't use `instanceof` for `assert.isArray`. + * Add `deep` flag for equality and property value. + * Merge pull request #64 from chaijs/assertion-docs + * Uniformize assertion inline docs. + * Add npm-debug.log to .gitignore. + * no reserved words as actuals. #62 + +1.0.0 / 2012-05-15 +================== + + * readme cleanup + * browser build + * utility comments + * removed docs + * update to package.json + * docs build + * comments / docs updates + * plugins app cleanup + * Merge pull request #61 from joliss/doc + * Fix and improve documentation of assert.equal and friends + * browser build + * doc checkpoint - texture + * Update chai-jquery link + * Use defined return value of Assertion extension functions + * Update utility docs + +1.0.0-rc3 / 2012-05-09 +================== + + * Merge branch 'feature/rc3' + * docs update + * browser build + * assert test conformity for minor refactor api + * assert minor refactor + * update util tests for new add/overwrite prop/method format + * added chai.Assertion.add/overwrite prop/method for plugin toolbox + * add/overwrite prop/method don't make assumptions about context + * doc test suite + * docs don't need coverage + * refactor all simple chains into one forEach loop, for clean documentation + * updated npm ignore + * remove old docs + * docs checkpoint - guide styled + * Merge pull request #59 from joliss/doc + * Document how to run the test suite + * don't need to rebuild docs to view + * dep update + * docs checkpoint - api section + * comment updates for docs + * new doc site checkpoint - plugin directory! + * Merge pull request #57 from kossnocorp/patch-1 + * Fix typo: devDependancies → devDependencies + * Using message flag in `getMessage` util instead of old `msg` property. + * Adding self to package.json contributors. + * `getMessage` shouldn't choke on null/omitted messages. + * `return this` not necessary in example. + * `return this` not necessary in example. + * Sinon–Chai has a dash + * updated plugins list for docs + +1.0.0-rc2 / 2012-05-06 +================== + + * Merge branch 'feature/test-cov' + * browser build + * missing assert tests for ownProperty + * appropriate assert equivalent for expect.to.have.property(key, val) + * reset AssertionError to include full stack + * test for plugin utilities + * overwrite Property and Method now ensure chain + * version notes in readme + +1.0.0-rc1 / 2012-05-04 +================== + + * browser build (rc1) + * assert match/notMatch tests + * assert interface - notMatch, ownProperty, notOwnProperty, ownPropertyVal, ownPropertyNotVal + * cleaner should interface export. + * added chai.Assertion.prototype._obj (getter) for quick access to object flag + * moved almostEqual / almostDeepEqual to stats plugin + * added mocha.opts + * Add test for `utils.addMethod` + * Fix a typo + * Add test for `utils.overwriteMethod` + * Fix a typo + * Browser build + * Add undefined assertion + * Add null assertion + * Fix an issue with `mocha --watch` + * travis no longer tests on node 0.4.x + * removing unnecissary carbon dep + * Merge branch 'feature/plugins-app' + * docs build + * templates for docs express app for plugin directory + * express app for plugin and static serving + * added web server deps + * Merge pull request #54 from josher19/master + * Remove old test.assert code + * Use util.inspect instead of inspect for deepAlmostEqual and almostEqual + * browser build + * Added almostEqual and deepAlmostEqual to assert test suite. + * bug - context determinants for utils + * dec=0 means rounding, so assert.deepAlmostEqual({pi: 3.1416}, {pi: 3}, 0) is true + * wrong travis link + * readme updates for version information + * travis tests 0.5.x branch as well + * [bug] util `addProperty` not correctly exporting + * read me version notes + * browser build 1.0.0alpha1 + * not using reserved words in internal assertions. #52 + * version tick + * clean up redundant tests + * Merge branch 'refs/heads/0.6.x' + * update version tag in package 1.0.0alpha1 + * browser build + * added utility tests to browser specs + * beginning utility testing + * updated utility comments + * utility - overwriteMethod + * utility - overwriteProperty + * utility - addMethod + * utility - addProperty + * missing ; + * contributors list update + * Merge branch 'refs/heads/0.6.x-docs' into 0.6.x + * Added guide link to docs. WIP + * Include/contain are now both properties and methods + * Add an alias annotation + * Remove usless function wrapper + * Fix a typo + * A/an are now both properties and methods + * [docs] new site homepage layout / color checkpoint + * Ignore IE-specific error properties. + * Fixing order of error message test. + * New cross-browser `getName` util. + * Fixing up `AssertionError` inheritance. + * backup docs + * Add doctypes + * [bug] was still using `constructor.name` in `throw` assertion + * [bug] flag Object.create(null) instead of new Object + * [test] browser build + * [refactor] all usage of Assertion.prototype.assert now uses template tags and flags + * [refactor] remove Assertion.prototype.inspect for testable object inspection + * [refactor] object to test is now stored in flag, with ssfi and custom message + * [bug] flag util - don't return on `set` + * [docs] comments for getMessage utility + * [feature] getMessage + * [feature] testing utilities + * [refactor] flag doesn't require `call` + * Make order of source files well-defined + * Added support for throw(errorInstance). + * Use a foolproof method of grabbing an error's name. + * Removed constructor.name check from throw. + * disabled stackTrack configuration tests until api is stable again + * first version of line displayed error for node js (unstable) + * refactor core Assertion to use flag utility for negation + * added flag utility + * tests for assert interface negatives. Closed #42 + * added assertion negatives that were missing. #42 + * Support for expected and actual parameters in assert-style error object + * chai as promised - readme + * Added assert.fail. Closes #40 + * better error message for assert.operator. Closes #39 + * [refactor] Assertion#property to use getPathValue property + * added getPathValue utility helper + * removed todo about browser build + * version notes + * version bumb 0.6.0 + * browser build + * [refactor] browser compile function to replace with `require('./error')' with 'require('./browser/error')' + * [feature] browser uses different error.js + * [refactor] error without chai.fail + * Assertion & interfaces use new utils helper export + * [refactor] primary export for new plugin util usage + * added util index.js helper + * added 2012 to copyright headers + * Added DeepEqual assertions + +0.5.3 / 2012-04-21 +================== + + * Merge branch 'refs/heads/jgonera-oldbrowsers' + * browser build + * fixed reserved names for old browsers in interface/assert + * fixed reserved names for old browsers in interface/should + * fixed: chai.js no longer contains fail() + * fixed reserved names for old browsers in Assertion + * Merge pull request #49 from joliss/build-order + * Make order of source files well-defined + * Merge pull request #43 from zzen/patch-1 + * Support for expected and actual parameters in assert-style error object + * chai as promised - readme + +0.5.2 / 2012-03-21 +================== + + * browser build + * Merge branch 'feature/assert-fail' + * Added assert.fail. Closes #40 + * Merge branch 'bug/operator-msg' + * better error message for assert.operator. Closes #39 + * version notes + +0.5.1 / 2012-03-14 +================== + + * chai.fail no longer exists + * Merge branch 'feature/assertdefined' + * Added asset#isDefined. Closes #37. + * dev docs update for Assertion#assert + +0.5.0 / 2012-03-07 +================== + + * [bug] on inspect of reg on n 0.4.12 + * Merge branch 'bug/33-throws' + * Merge pull request #35 from logicalparadox/empty-object + * browser build + * updated #throw docs + * Assertion#throw `should` tests updated + * Assertion#throw `expect` tests + * Should interface supports multiple throw parameters + * Update Assertion#throw to support strings and type checks. + * Add more tests for `empty` in `should`. + * Add more tests for `empty` in `expect`. + * Merge branch 'master' into empty-object + * don't switch act/exp + * Merge pull request #34 from logicalparadox/assert-operator + * Update the compiled verison. + * Add `assert.operator`. + * Notes on messages. #22 + * browser build + * have been test + * below tests + * Merge branch 'feature/actexp' + * browser build + * remove unnecessary fail export + * full support for actual/expected where relevant + * Assertion.assert support expected value + * clean up error + * Update the compiled version. + * Add object & sane arguments support to `Assertion#empty`. + +0.4.2 / 2012-02-28 +================== + + * fix for `process` not available in browser when used via browserify. Closes #28 + * Merge pull request #31 from joliss/doc + * Document that "should" works in browsers other than IE + * Merge pull request #30 from logicalparadox/assert-tests + * Update the browser version of chai. + * Update `assert.doesNotThrow` test in order to check the use case when type is a string. + * Add test for `assert.ifError`. + * Falsey -> falsy. + * Full coverage for `assert.throws` and `assert.doesNotThrow`. + * Add test for `assert.doesNotThrow`. + * Add test for `assert.throws`. + * Add test for `assert.length`. + * Add test for `assert.include`. + * Add test for `assert.isBoolean`. + * Fix the implementation of `assert.isNumber`. + * Add test for `assert.isNumber`. + * Add test for `assert.isString`. + * Add test for `assert.isArray`. + * Add test for `assert.isUndefined`. + * Add test for `assert.isNotNull`. + * Fix `assert.isNotNull` implementation. + * Fix `assert.isNull` implementation. + * Add test for `assert.isNull`. + * Add test for `assert.notDeepEqual`. + * Add test for `assert.deepEqual`. + * Add test for `assert.notStrictEqual`. + * Add test for `assert.strictEqual`. + * Add test for `assert.notEqual`. + +0.4.1 / 2012-02-26 +================== + + * Merge pull request #27 from logicalparadox/type-fix + * Update the browser version. + * Add should tests for type checks. + * Add function type check test. + * Add more type checks tests. + * Add test for `new Number` type check. + * Fix type of actual checks. + +0.4.0 / 2012-02-25 +================== + + * docs and readme for upcoming 0.4.0 + * docs generated + * putting coverage and tests for docs in docs/out/support + * make docs + * makefile copy necessary resources for tests in docs + * rename configuration test + * Merge pull request #21 from logicalparadox/close-to + * Update the browser version. + * Update `closeTo()` docs. + * Add `Assertion.closeTo()` method. + * Add `.closeTo()` should test. + * Add `.closeTo()` expect test. + * Merge pull request #20 from logicalparadox/satisfy + * Update the browser version. + * `..` -> `()` in `.satisfy()` should test. + * Update example for `.satisfy()`. + * Update the compiled browser version. + * Add `Assertion.satisfy()` method. + * Add `.satisfy()` should test. + * Add `.satisfy()` expect test. + * Merge pull request #19 from logicalparadox/respond-to + * Update the compiled browser version. + * Add `respondTo` Assertion. + * Add `respondTo` should test. + * Add `respondTo` expect test. + * Merge branch 'feature/coverage' + * mocha coverage support + * doc contributors + * README contributors + +0.3.4 / 2012-02-23 +================== + + * inline comment typos for #15 + * Merge branch 'refs/heads/jeffbski-configErrorStackCompat' + * includeStack documentation for all interfaces + * suite name more generic + * Update test to be compatible with browsers that do not support err.stack + * udpated compiled chai.js and added to browser tests + * Allow inclusion of stack trace for Assert error messages to be configurable + * docs sharing buttons + * sinon-chai link + * doc updates + * read me updates include plugins + +0.3.3 / 2012-02-12 +================== + + * Merge pull request #14 from jfirebaugh/configurable_properties + * Make Assertion.prototype properties configurable + +0.3.2 / 2012-02-10 +================== + + * codex version + * docs + * docs cleanup + +0.3.1 / 2012-02-07 +================== + + * node 0.4.x compat + +0.3.0 / 2012-02-07 +================== + + * Merge branch 'feature/03x' + * browser build + * remove html/json/headers testign + * regex error.message testing + * tests for using plugins + * Merge pull request #11 from domenic/master + * Make `chai.use` a no-op if the function has already been used. + +0.2.4 / 2012-02-02 +================== + + * added in past tense switch for `been` + +0.2.3 / 2012-02-01 +================== + + * try that again + +0.2.2 / 2012-02-01 +================== + + * added `been` (past of `be`) alias + +0.2.1 / 2012-01-29 +================== + + * added Throw, with a capital T, as an alias to `throw` (#7) + +0.2.0 / 2012-01-26 +================== + + * update gitignore for vim *.swp + * Merge branch 'feature/plugins' + * browser build + * interfaces now work with use + * simple .use function. See #9. + * readme notice on browser compat + +0.1.7 / 2012-01-25 +================== + + * added assert tests to browser test runner + * browser update + * `should` interface patch for primitives support in FF + * fix isObject() Thanks @milewise + * travis only on branch `master` + * add instanceof alias `instanceOf`. #6 + * some tests for assert module + +0.1.6 / 2012-01-02 +================== + + * commenting for assert interface + * updated codex dep + +0.1.5 / 2012-01-02 +================== + + * browser tests pass + * type in should.not.equal + * test for should (not) exist + * added should.exist and should.not.exist + * browser uses tdd + * convert tests to tdd + +0.1.4 / 2011-12-26 +================== + + * browser lib update for new assert interface compatiblitiy + * inspect typos + * added strict equal + negatives and ifError + * interface assert had doesNotThrow + * added should tests to browser + * new expect empty tests + * should test browser compat + * Fix typo for instanceof docs. Closes #3 [ci skip] + +0.1.3 / 2011-12-18 +================== + + * much cleaner reporting string on error. + +0.1.2 / 2011-12-18 +================== + + * [docs] for upcoming 0.1.2 + * browser version built with pre/suffix … all tests passing + * make / compile now use prefix/suffix correctly + * code clean + * prefix/suffix to wrap browser output to prevent conflicts with other `require` methods. + * Merge branch 'feature/should4xcompatibility' + * compile for browser tests.. all pass + * added header/status/html/json + * throw tests + * should.throw & should.not.throw shortcuts + * improved `throw` type detection and messaging + * contain is now `include` … keys modifier is now `contain` + * removed object() test + * removed #respondTo + * Merge branch 'bug/2' + * replaced __defineGetter__ with defineProperty for all uses + * [docs] change mp tracking code + * docs site updated with assert (TDD) interface + * updated doc comments for assert interface + +0.1.1 / 2011-12-16 +================== + + * docs ready for upcoming 0.1.1 + * readme image fixed [ci skip] + * more readme tweaks [ci skip] + * réadmet image fixed [ci skip] + * documentation + * codex locked in version 0.0.5 + * more comments to assertions for docs + * assertions fully commented, browser library updated + * adding codex as doc dependancy + * prepping for docs + * assertion component completely commented for documentation + * added exist test + * var expect outside of browser if check + * added keywords to package.json + +0.1.0 / 2011-12-15 +================== + + * failing on purpose successful .. back to normal + * testing travis failure + * assert#arguments getter + * readme typo + * updated README + * added travis and npmignore + * copyright notices … think i got them all + * moved expect interface to own file for consistency + * assert ui deepEqual + * browser tests expect (all working) + * browser version built + * chai.fail (should ui) + * expect tests browser compatible + * tests for should and expect (all pass) + * moved fail to primary export + * should compatibility testing + * within, greaterThan, object, keys, + * Aliases + * Assertion#property now correctly works with negate and undefined values + * error message language matches should + * Assertion#respondTo + * Assertion now uses inspect util + * git ignore node modules + * should is exported + * AssertionError __proto__ from Error.prototype + * add should interface for should.js compatibility + * moved eql to until folder and added inspect from (joyent/node) + * added mocha for testing + * browser build for current api + * multiple .property assertions + * added deep equal from node + +0.0.2 / 2011-12-07 +================== + + * cleaner output on error + * improved exists detection + * package remnant artifact + * empty deep equal + * test browser build + * assertion cleanup + * client compile script + * makefile + * most of the basic assertions + * allow no parameters to assertion error + * name change + * assertion error instance + * main exports: assert() & expect() + * initialize diff --git a/web/node_modules/chai/LICENSE b/web/node_modules/chai/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eedbe238acac663530523895e2e202d8fb172def --- /dev/null +++ b/web/node_modules/chai/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Chai.js Assertion Library + +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/web/node_modules/chai/README.md b/web/node_modules/chai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78e4d2dead13bf56ca6a8ce50ee6e842dc34c334 --- /dev/null +++ b/web/node_modules/chai/README.md @@ -0,0 +1,212 @@ +

+ + ChaiJS + +
+ chai +

+ +

+ Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework. +

+ +

+ + license:mit + + + tag:? + + + node:? + +
+ + Selenium Test Status + +
+ + downloads:? + + + build:? + + + coverage:? + + + devDependencies:? + +
+ + Join the Slack chat + + + Join the Gitter chat + + + OpenCollective Backers + +

+ +For more information or to download plugins, view the [documentation](http://chaijs.com). + +## What is Chai? + +Chai is an _assertion library_, similar to Node's built-in `assert`. It makes testing much easier by giving you lots of assertions you can run against your code. + +## Installation + +### Node.js + +`chai` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install --save-dev chai + +### Browsers + +You can also use it within the browser; install via npm and use the `chai.js` file found within the download. For example: + +```html + +``` + +## Usage + +Import the library in your code, and then pick one of the styles you'd like to use - either `assert`, `expect` or `should`: + +```js +var chai = require('chai'); +var assert = chai.assert; // Using Assert style +var expect = chai.expect; // Using Expect style +var should = chai.should(); // Using Should style +``` + +### Pre-Native Modules Usage (_registers the chai testing style globally_) + +```js +require('chai/register-assert'); // Using Assert style +require('chai/register-expect'); // Using Expect style +require('chai/register-should'); // Using Should style +``` + +### Pre-Native Modules Usage (_as local variables_) + +```js +const { assert } = require('chai'); // Using Assert style +const { expect } = require('chai'); // Using Expect style +const { should } = require('chai'); // Using Should style +should(); // Modifies `Object.prototype` + +const { expect, use } = require('chai'); // Creates local variables `expect` and `use`; useful for plugin use +``` + +### Native Modules Usage (_registers the chai testing style globally_) + +```js +import 'chai/register-assert'; // Using Assert style +import 'chai/register-expect'; // Using Expect style +import 'chai/register-should'; // Using Should style +``` + +### Native Modules Usage (_local import only_) + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +should(); // Modifies `Object.prototype` +``` + +### Usage with Mocha + +```bash +mocha spec.js -r chai/register-assert # Using Assert style +mocha spec.js -r chai/register-expect # Using Expect style +mocha spec.js -r chai/register-should # Using Should style +``` + +[Read more about these styles in our docs](http://chaijs.com/guide/styles/). + +## Plugins + +Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces. + +- Need a plugin? View the [official plugin list](http://chaijs.com/plugins). +- Want to build a plugin? Read the [plugin api documentation](http://chaijs.com/guide/plugins/). +- Have a plugin and want it listed? Simply add the following keywords to your package.json: + - `chai-plugin` + - `browser` if your plugin works in the browser as well as Node.js + - `browser-only` if your plugin does not work with Node.js + +### Related Projects + +- [chaijs / chai-docs](https://github.com/chaijs/chai-docs): The chaijs.com website source code. +- [chaijs / assertion-error](https://github.com/chaijs/assertion-error): Custom `Error` constructor thrown upon an assertion failing. +- [chaijs / deep-eql](https://github.com/chaijs/deep-eql): Improved deep equality testing for Node.js and the browser. +- [chaijs / type-detect](https://github.com/chaijs/type-detect): Improved typeof detection for Node.js and the browser. +- [chaijs / check-error](https://github.com/chaijs/check-error): Error comparison and information related utility for Node.js and the browser. +- [chaijs / loupe](https://github.com/chaijs/loupe): Inspect utility for Node.js and browsers. +- [chaijs / pathval](https://github.com/chaijs/pathval): Object value retrieval given a string path. +- [chaijs / get-func-name](https://github.com/chaijs/get-func-name): Utility for getting a function's name for node and the browser. + +### Contributing + +Thank you very much for considering to contribute! + +Please make sure you follow our [Code Of Conduct](https://github.com/chaijs/chai/blob/master/CODE_OF_CONDUCT.md) and we also strongly recommend reading our [Contributing Guide](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md). + +Here are a few issues other contributors frequently ran into when opening pull requests: + +- Please do not commit changes to the `chai.js` build. We do it once per release. +- Before pushing your commits, please make sure you [rebase](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md#pull-requests) them. + +### Contributors + +Please see the full +[Contributors Graph](https://github.com/chaijs/chai/graphs/contributors) for our +list of contributors. + +### Core Contributors + +Feel free to reach out to any of the core contributors with your questions or +concerns. We will do our best to respond in a timely manner. + +[![Jake Luer](https://avatars3.githubusercontent.com/u/58988?v=3&s=50)](https://github.com/logicalparadox) +[![Veselin Todorov](https://avatars3.githubusercontent.com/u/330048?v=3&s=50)](https://github.com/vesln) +[![Keith Cirkel](https://avatars3.githubusercontent.com/u/118266?v=3&s=50)](https://github.com/keithamus) +[![Lucas Fernandes da Costa](https://avatars3.githubusercontent.com/u/6868147?v=3&s=50)](https://github.com/lucasfcosta) +[![Grant Snodgrass](https://avatars3.githubusercontent.com/u/17260989?v=3&s=50)](https://github.com/meeber) diff --git a/web/node_modules/chai/ReleaseNotes.md b/web/node_modules/chai/ReleaseNotes.md new file mode 100644 index 0000000000000000000000000000000000000000..2a80d5cec1ac6fb4d048d9348d5c2c1f6391628f --- /dev/null +++ b/web/node_modules/chai/ReleaseNotes.md @@ -0,0 +1,737 @@ +# Release Notes + +## Note + +As of 3.0.0, the ReleaseNotes.md file has been deprecated. [Please refer to the release notes available on Github](https://github.com/chaijs/chai/releases). Or +[the release notes on the chaijs.com website](https://chaijs.com/releases). + +--- + +## 2.3.0 / 2015-04-26 + +Added `ownPropertyDescriptor` assertion: + +```js +expect('test').to.have.ownPropertyDescriptor('length'); +expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 }); +expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 }); +expect('test').ownPropertyDescriptor('length').to.have.property('enumerable', false); +expect('test').ownPropertyDescriptor('length').to.have.keys('value'); +``` + +### Community Contributions + +#### Code Features & Fixes + + * [#408](https://github.com/chaijs/chai/pull/408) Add `ownPropertyDescriptor` + assertion. + By [@ljharb](https://github.com/ljharb) + * [#422](https://github.com/chaijs/chai/pull/422) Improve ownPropertyDescriptor + tests. + By [@ljharb](https://github.com/ljharb) + +#### Documentation fixes + + * [#417](https://github.com/chaijs/chai/pull/417) Fix documentation typo + By [@astorije](https://github.com/astorije) + * [#423](https://github.com/chaijs/chai/pull/423) Fix inconsistency in docs. + By [@ehntoo](https://github.com/ehntoo) + + +## 2.2.0 / 2015-03-26 + +Deep property strings can now be escaped using `\\` - for example: + +```js +var deepCss = { '.link': { '[target]': 42 }}; +expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42) +``` + +### Community Contributions + +#### Code Features & Fixes + + * [#402](https://github.com/chaijs/chai/pull/402) Allow escaping of deep + property keys. + By [@umireon](https://github.com/umireon) + +#### Documentation fixes + + * [#405](https://github.com/chaijs/chai/pull/405) Tweak documentation around + deep property escaping. + By [@keithamus](https://github.com/keithamus) + + +## 2.1.2 / 2015-03-15 + +A minor bug fix. No new features. + +### Community Contributions + +#### Code Features & Fixes + + * [#395](https://github.com/chaijs/chai/pull/395) Fix eval-related bugs with + assert.operator ([#386](https://github.com/chaijs/chai/pull/386)). + By [@cjqed](https://github.com/cjqed) + +## 2.1.1 / 2015-03-04 + +Two minor bugfixes. No new features. + +### Community Contributions + +#### Code Features & Fixes + + * [#385](https://github.com/chaijs/chai/pull/385) Fix a bug (also described in + [#387](https://github.com/chaijs/chai/pull/385)) where `deep.property` would not work with single + key names. By [@eldritch-fossicker](https://github.com/eldritch-fossicker) + * [#379](https://github.com/chaijs/chai/pull/379) Fix bug where tools which overwrite + primitive prototypes, such as Babel or core-js would fail. + By [@dcneiner](https://github.com/dcneiner) + +#### Documentation fixes + + * [#382](https://github.com/chaijs/chai/pull/382) Add doc for showDiff argument in assert. + By [@astorije](https://github.com/astorije) + * [#383](https://github.com/chaijs/chai/pull/383) Improve wording for truncateTreshold docs + By [@gurdiga](https://github.com/gurdiga) + * [#381](https://github.com/chaijs/chai/pull/381) Improve wording for assert.empty docs + By [@astorije](https://github.com/astorije) + +## 2.1.0 / 2015-02-23 + +Small release; fixes an issue where the Chai lib was incorrectly reporting the +version number. + +Adds new `should.fail()` and `expect.fail()` methods, which are convinience +methods to throw Assertion Errors. + +### Community Contributions + +#### Code Features & Fixes + + * [#356](https://github.com/chaijs/chai/pull/356) Add should.fail(), expect.fail(). By [@Soviut](https://github.com/Soviut) + * [#374](https://github.com/chaijs/chai/pull/374) Increment version. By [@jmm](https://github.com/jmm) + +## 2.0.0 / 2015-02-09 + +Unfortunately with 1.10.0 - compatibility broke with older versions because of +the `addChainableNoop`. This change has been reverted. + +Any plugins using `addChainableNoop` should cease to do so. + +Any developers wishing for this behaviour can use [dirty-chai](https://www.npmjs.com/package/dirty-chai) +by [@joshperry](https://github.com/joshperry) + +### Community Contributions + +#### Code Features & Fixes + + * [#361](https://github.com/chaijs/chai/pull/361) `.keys()` now accepts Objects, extracting keys from them. By [@gregglind](https://github.com/gregglind) + * [#359](https://github.com/chaijs/chai/pull/359) `.keys()` no longer mutates passed arrays. By [@gregglind](https://github.com/gregglind) + * [#349](https://github.com/chaijs/chai/pull/349) Add a new chainable keyword - `.which`. By [@toastynerd](https://github.com/toastynerd) + * [#333](https://github.com/chaijs/chai/pull/333) Add `.change`, `.increase` and `.decrease` assertions. By [@cmpolis](https://github.com/cmpolis) + * [#335](https://github.com/chaijs/chai/pull/335) `chai.util` is now exposed [@DingoEatingFuzz](https://github.com/DingoEatingFuzz) + * [#328](https://github.com/chaijs/chai/pull/328) Add `.includes` and `.contains` aliases (for `.include` and `.contain`). By [@lo1tuma](https://github.com/lo1tuma) + * [#313](https://github.com/chaijs/chai/pull/313) Add `.any.keys()` and `.all.keys()` qualifiers. By [@cjqed](https://github.com/cjqed) + * [#312](https://github.com/chaijs/chai/pull/312) Add `assert.sameDeepMembers()`. By [@cjqed](https://github.com/cjqed) + * [#311](https://github.com/chaijs/chai/pull/311) Add `assert.isAbove()` and `assert.isBelow()`. By [@cjqed](https://github.com/cjqed) + * [#308](https://github.com/chaijs/chai/pull/308) `property` and `deep.property` now pass if a value is set to `undefined`. By [@prodatakey](https://github.com/prodatakey) + * [#309](https://github.com/chaijs/chai/pull/309) optimize deep equal in Arrays. By [@ericdouglas](https://github.com/ericdouglas) + * [#306](https://github.com/chaijs/chai/pull/306) revert #297 - allowing lint-friendly tests. By [@keithamus](https://github.com/keithamus) + +#### Documentation fixes + + * [#357](https://github.com/chaijs/chai/pull/357) Copyright year updated in docs. By [@danilovaz](https://github.com/danilovaz) + * [#325](https://github.com/chaijs/chai/pull/325) Fix documentation for overwriteChainableMethod. By [@chasenlehara](https://github.com/chasenlehara) + * [#334](https://github.com/chaijs/chai/pull/334) Typo fix. By [@hurrymaplelad](https://github.com/hurrymaplelad) + * [#317](https://github.com/chaijs/chai/pull/317) Typo fix. By [@jasonkarns](https://github.com/jasonkarns) + * [#318](https://github.com/chaijs/chai/pull/318) Typo fix. By [@jasonkarns](https://github.com/jasonkarns) + * [#316](https://github.com/chaijs/chai/pull/316) Typo fix. By [@jasonkarns](https://github.com/jasonkarns) + + +## 1.10.0 / 2014-11-10 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required +- **Plugin Developers:** + - Review `addChainableNoop` notes below. +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Noop Function for Terminating Assertion Properties + +The following assertions can now also be used in the function-call form: + +* ok +* true +* false +* null +* undefined +* exist +* empty +* arguments +* Arguments + +The above list of assertions are property getters that assert immediately on +access. Because of that, they were written to be used by terminating the assertion +chain with a property access. + +```js +expect(true).to.be.true; +foo.should.be.ok; +``` + +This syntax is definitely aesthetically pleasing but, if you are linting your +test code, your linter will complain with an error something like "Expected an +assignment or function call and instead saw an expression." Since the linter +doesn't know about the property getter it assumes this line has no side-effects, +and throws a warning in case you made a mistake. + +Squelching these errors is not a good solution as test code is getting to be +just as important as, if not more than, production code. Catching syntactical +errors in tests using static analysis is a great tool to help make sure that your +tests are well-defined and free of typos. + +A better option was to provide a function-call form for these assertions so that +the code's intent is more clear and the linters stop complaining about something +looking off. This form is added in addition to the existing property access form +and does not impact existing test code. + +```js +expect(true).to.be.true(); +foo.should.be.ok(); +``` + +These forms can also be mixed in any way, these are all functionally identical: + +```js +expect(true).to.be.true.and.not.false(); +expect(true).to.be.true().and.not.false; +expect(true).to.be.true.and.not.false; +``` + +#### Plugin Authors + +If you would like to provide this function-call form for your terminating assertion +properties, there is a new function to register these types of asserts. Instead +of using `addProperty` to register terminating assertions, simply use `addChainableNoop` +instead; the arguments to both are identical. The latter will make the assertion +available in both the attribute and function-call forms and should have no impact +on existing users of your plugin. + +### Community Contributions + +- [#297](https://github.com/chaijs/chai/pull/297) Allow writing lint-friendly tests. [@joshperry](https://github.com/joshperry) +- [#298](https://github.com/chaijs/chai/pull/298) Add check for logging `-0`. [@dasilvacontin](https://github.com/dasilvacontin) +- [#300](https://github.com/chaijs/chai/pull/300) Fix #299: the test is defining global variables [@julienw](https://github.com/julienw) + +Thank you to all who took time to contribute! + +## 1.9.2 / 2014-09-29 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Community Contributions + +- [#264](https://github.com/chaijs/chai/pull/264) Show diff for keys assertions [@cjthompson](https://github.com/cjthompson) +- [#267](https://github.com/chaijs/chai/pull/267) Use SVG badges [@shinnn](https://github.com/shinnn) +- [#268](https://github.com/chaijs/chai/pull/268) Allow messages to be functions (sinon-compat) [@charlierudolph](https://github.com/charlierudolph) +- [#269](https://github.com/chaijs/chai/pull/269) Remove unused argument for #lengthOf [@charlierudolph](https://github.com/charlierudolph) +- [#275](https://github.com/chaijs/chai/pull/275) Rewrite pretty-printing HTML elements to prevent throwing internal errors [@DrRataplan](https://github.com/DrRataplan) +- [#277](https://github.com/chaijs/chai/pull/277) Fix assert documentation for #sameMembers [@charlierudolph](https://github.com/charlierudolph) +- [#279](https://github.com/chaijs/chai/pull/279) closeTo should check value's type before assertion [@mohayonao](https://github.com/mohayonao) +- [#289](https://github.com/chaijs/chai/pull/289) satisfy is called twice [@charlierudolph](https://github.com/charlierudolph) +- [#292](https://github.com/chaijs/chai/pull/292) resolve conflicts with node-webkit and global usage [@boneskull](https://github.com/boneskull) + +Thank you to all who took time to contribute! + +## 1.9.1 / 2014-03-19 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - Migrate configuration options to new interface. (see notes) +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Configuration + +There have been requests for changes and additions to the configuration mechanisms +and their impact in the Chai architecture. As such, we have decoupled the +configuration from the `Assertion` constructor. This not only allows for centralized +configuration, but will allow us to shift the responsibility from the `Assertion` +constructor to the `assert` interface in future releases. + +These changes have been implemented in a non-breaking way, but a depretiation +warning will be presented to users until they migrate. The old config method will +be removed in either `v1.11.0` or `v2.0.0`, whichever comes first. + +#### Quick Migration + +```js +// change this: +chai.Assertion.includeStack = true; +chai.Assertion.showDiff = false; + +// ... to this: +chai.config.includeStack = true; +chai.config.showDiff = false; +``` + +#### All Config Options + +##### config.includeStack + +- **@param** _{Boolean}_ +- **@default** `false` + +User configurable property, influences whether stack trace is included in +Assertion error message. Default of `false` suppresses stack trace in the error +message. + +##### config.showDiff + +- **@param** _{Boolean}_ +- **@default** `true` + +User configurable property, influences whether or not the `showDiff` flag +should be included in the thrown AssertionErrors. `false` will always be `false`; +`true` will be true when the assertion has requested a diff be shown. + +##### config.truncateThreshold **(NEW)** + +- **@param** _{Number}_ +- **@default** `40` + +User configurable property, sets length threshold for actual and expected values +in assertion errors. If this threshold is exceeded, the value is truncated. + +Set it to zero if you want to disable truncating altogether. + +```js +chai.config.truncateThreshold = 0; // disable truncating +``` + +### Community Contributions + +- [#228](https://github.com/chaijs/chai/pull/228) Deep equality check for memebers. [@duncanbeevers](https://github.com/duncanbeevers) +- [#247](https://github.com/chaijs/chai/pull/247) Proofreading. [@didorellano](https://github.com/didoarellano) +- [#244](https://github.com/chaijs/chai/pull/244) Fix `contain`/`include` 1.9.0 regression. [@leider](https://github.com/leider) +- [#233](https://github.com/chaijs/chai/pull/233) Improvements to `ssfi` for `assert` interface. [@refack](https://github.com/refack) +- [#251](https://github.com/chaijs/chai/pull/251) New config option: object display threshold. [@romario333](https://github.com/romario333) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- [#183](https://github.com/chaijs/chai/issues/183) Allow `undefined` for actual. (internal api) +- Update Karam(+plugins)/Istanbul to most recent versions. + +## 1.9.0 / 2014-01-29 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required +- **Plugin Developers:** + - Review [#219](https://github.com/chaijs/chai/pull/219). +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Community Contributions + +- [#202](https://github.com/chaijs/chai/pull/201) Improve error message for .throw(). [@andreineculau](https://github.com/andreineculau) +- [#217](https://github.com/chaijs/chai/pull/217) Chai tests can be run with `--watch`. [@demands](https://github.com/demands) +- [#219](https://github.com/chaijs/chai/pull/219) Add overwriteChainableMethod utility. [@demands](https://github.com/demands) +- [#224](https://github.com/chaijs/chai/pull/224) Return error on throw method to chain on error properties. [@vbardales](https://github.com/vbardales) +- [#226](https://github.com/chaijs/chai/pull/226) Add `has` to language chains. [@duncanbeevers](https://github.com/duncanbeevers) +- [#230](https://github.com/chaijs/chai/pull/230) Support `{a:1,b:2}.should.include({a:1})` [@jkroso](https://github.com/jkroso) +- [#231](https://github.com/chaijs/chai/pull/231) Update Copyright notices to 2014 [@duncanbeevers](https://github.com/duncanbeevers) +- [#232](https://github.com/chaijs/chai/pull/232) Avoid error instantiation if possible on assert.throws. [@laconbass](https://github.com/laconbass) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- [#225](https://github.com/chaijs/chai/pull/225) Improved AMD wrapper provided by upstream `component(1)`. +- [#185](https://github.com/chaijs/chai/issues/185) `assert.throws()` returns thrown error for further assertions. +- [#237](https://github.com/chaijs/chai/pull/237) Remove coveralls/jscoverage, include istanbul coverage report in travis test. +- Update Karma and Sauce runner versions for consistent CI results. No more karma@canary. + +## 1.8.1 / 2013-10-10 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - Refresh `node_modules` folder for updated dependencies. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Browserify + +This is a small patch that updates the dependency tree so browserify users can install +chai. (Remove conditional requires) + +## 1.8.0 / 2013-09-18 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - See `deep.equal` notes. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Deep Equals + +This version of Chai focused on a overhaul to the deep equal utility. The code for this +tool has been removed from the core lib and can now be found at: +[chai / deep-eql](https://github.com/chaijs/deep-eql). As stated in previous releases, +this is part of a larger initiative to provide transparency, independent testing, and coverage for +some of the more complicated internal tools. + +For the most part `.deep.equal` will behave the same as it has. However, in order to provide a +consistent ruleset across all types being tested, the following changes have been made and _might_ +require changes to your tests. + +**1.** Strict equality for non-traversable nodes according to [egal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + +_Previously:_ Non-traversable equal via `===`. + +```js +expect(NaN).to.deep.equal(NaN); +expect(-0).to.not.deep.equal(+0); +``` + +**2.** Arguments are not Arrays (and all types must be equal): + +_Previously:_ Some crazy nonsense that led to empty arrays deep equaling empty objects deep equaling dates. + +```js +expect(arguments).to.not.deep.equal([]); +expect(Array.prototype.slice.call(arguments)).to.deep.equal([]); +``` + +- [#156](https://github.com/chaijs/chai/issues/156) Empty object is eql to empty array +- [#192](https://github.com/chaijs/chai/issues/192) empty object is eql to a Date object +- [#194](https://github.com/chaijs/chai/issues/194) refactor deep-equal utility + +### CI and Browser Testing + +Chai now runs the browser CI suite using [Karma](http://karma-runner.github.io/) directed at +[SauceLabs](https://saucelabs.com/). This means we get to know where our browser support stands... +and we get a cool badge: + +[![Selenium Test Status](https://saucelabs.com/browser-matrix/logicalparadox.svg)](https://saucelabs.com/u/logicalparadox) + +Look for the list of browsers/versions to expand over the coming releases. + +- [#195](https://github.com/chaijs/chai/issues/195) karma test framework + +## 1.7.2 / 2013-06-27 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Coverage Reporting + +Coverage reporting has always been available for core-developers but the data has never been published +for our end users. In our ongoing effort to improve accountability this data will now be published via +the [coveralls.io](https://coveralls.io/) service. A badge has been added to the README and the full report +can be viewed online at the [chai coveralls project](https://coveralls.io/r/chaijs/chai). Furthermore, PRs +will receive automated messages indicating how their PR impacts test coverage. This service is tied to TravisCI. + +### Other Fixes + +- [#175](https://github.com/chaijs/chai/issues/175) Add `bower.json`. (Fix ignore all) + +## 1.7.1 / 2013-06-24 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Official Bower Support + +Support has been added for the Bower Package Manager ([bower.io])(http://bower.io/). Though +Chai could be installed via Bower in the past, this update adds official support via the `bower.json` +specification file. + +- [#175](https://github.com/chaijs/chai/issues/175) Add `bower.json`. + +## 1.7.0 / 2013-06-17 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - Review AssertionError update notice. +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### AssertionError Update Notice + +Chai now uses [chaijs/assertion-error](https://github.com/chaijs/assertion-error) instead an internal +constructor. This will allow for further iteration/experimentation of the AssertionError constructor +independant of Chai. Future plans include stack parsing for callsite support. + +This update constructor has a different constructor param signature that conforms more with the standard +`Error` object. If your plugin throws and `AssertionError` directly you will need to update your plugin +with the new signature. + +```js +var AssertionError = require('chai').AssertionError; + +/** + * previous + * + * @param {Object} options + */ + +throw new AssertionError({ + message: 'An assertion error occurred' + , actual: actual + , expect: expect + , startStackFunction: arguments.callee + , showStack: true +}); + +/** + * new + * + * @param {String} message + * @param {Object} options + * @param {Function} start stack function + */ + +throw new AssertionError('An assertion error occurred', { + actual: actual + , expect: expect + , showStack: true +}, arguments.callee); + +// other signatures +throw new AssertionError('An assertion error occurred'); +throw new AssertionError('An assertion error occurred', null, arguments.callee); +``` + +#### External Dependencies + +This is the first non-developement dependency for Chai. As Chai continues to evolve we will begin adding +more; the next will likely be improved type detection and deep equality. With Chai's userbase continually growing +there is an higher need for accountability and documentation. External dependencies will allow us to iterate and +test on features independent from our interfaces. + +Note: The browser packaged version `chai.js` will ALWAYS contain all dependencies needed to run Chai. + +### Community Contributions + +- [#169](https://github.com/chaijs/chai/pull/169) Fix deep equal comparison for Date/Regexp types. [@katsgeorgeek](https://github.com/katsgeorgeek) +- [#171](https://github.com/chaijs/chai/pull/171) Add `assert.notOk()`. [@Bartvds](https://github.com/Bartvds) +- [#173](https://github.com/chaijs/chai/pull/173) Fix `inspect` utility. [@domenic](https://github.com/domenic) + +Thank you to all who took the time to contribute! + +## 1.6.1 / 2013-06-05 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required. +- **Core Contributors:** + - Refresh `node_modules` folder for updated developement dependencies. + +### Deep Equality + +Regular Expressions are now tested as part of all deep equality assertions. In previous versions +they silently passed for all scenarios. Thanks to [@katsgeorgeek](https://github.com/katsgeorgeek) for the contribution. + +### Community Contributions + +- [#161](https://github.com/chaijs/chai/pull/161) Fix documented name for assert interface's isDefined method. [@brandonpayton](https://github.com/brandonpayton) +- [#168](https://github.com/chaijs/chai/pull/168) Fix comparison equality of two regexps for when using deep equality. [@katsgeorgeek](https://github.com/katsgeorgeek) + +Thank you to all who took the time to contribute! + +### Additional Notes + +- Mocha has been locked at version `1.8.x` to ensure `mocha-phantomjs` compatibility. + +## 1.6.0 / 2013-04-29 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required. +- **Core Contributors:** + - Refresh `node_modules` folder for updated developement dependencies. + +### New Assertions + +#### Array Members Inclusion + +Asserts that the target is a superset of `set`, or that the target and `set` have the same members. +Order is not taken into account. Thanks to [@NickHeiner](https://github.com/NickHeiner) for the contribution. + +```js +// (expect/should) full set +expect([4, 2]).to.have.members([2, 4]); +expect([5, 2]).to.not.have.members([5, 2, 1]); + +// (expect/should) inclusion +expect([1, 2, 3]).to.include.members([3, 2]); +expect([1, 2, 3]).to.not.include.members([3, 2, 8]); + +// (assert) full set +assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + +// (assert) inclusion +assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members'); + +``` + +#### Non-inclusion for Assert Interface + +Most `assert` functions have a negative version, like `instanceOf()` has a corresponding `notInstaceOf()`. +However `include()` did not have a corresponding `notInclude()`. This has been added. + +```js +assert.notInclude([ 1, 2, 3 ], 8); +assert.notInclude('foobar', 'baz'); +``` + +### Community Contributions + +- [#140](https://github.com/chaijs/chai/pull/140) Restore `call`/`apply` methods for plugin interface. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#148](https://github.com/chaijs/chai/issues/148)/[#153](https://github.com/chaijs/chai/pull/153) Add `members` and `include.members` assertions. [#NickHeiner](https://github.com/NickHeiner) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- [#142](https://github.com/chaijs/chai/issues/142) `assert#include` will no longer silently pass on wrong-type haystack. +- [#158](https://github.com/chaijs/chai/issues/158) `assert#notInclude` has been added. +- Travis-CI now tests Node.js `v0.10.x`. Support for `v0.6.x` has been removed. `v0.8.x` is still tested as before. + +## 1.5.0 / 2013-02-03 + +### Migration Requirements + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - _Update [2013-02-04]:_ Some users may notice a small subset of deep equality assertions will no longer pass. This is the result of + [#120](https://github.com/chaijs/chai/issues/120), an improvement to our deep equality algorithm. Users will need to revise their assertions + to be more granular should this occur. Further information: [#139](https://github.com/chaijs/chai/issues/139). +- **Plugin Developers:** + - No changes required. +- **Core Contributors:** + - Refresh `node_modules` folder for updated developement dependencies. + +### Community Contributions + +- [#126](https://github.com/chaijs/chai/pull/126): Add `eqls` alias for `eql`. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#127](https://github.com/chaijs/chai/issues/127): Performance refactor for chainable methods. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#133](https://github.com/chaijs/chai/pull/133): Assertion `.throw` support for primitives. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#137](https://github.com/chaijs/chai/issues/137): Assertion `.throw` support for empty messages. [@timnew](https://github.com/timnew) +- [#136](https://github.com/chaijs/chai/pull/136): Fix backward negation messages when using `.above()` and `.below()`. [@whatthejeff](https://github.com/whatthejeff) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- Improve type detection of `.a()`/`.an()` to work in cross-browser scenarios. +- [#116](https://github.com/chaijs/chai/issues/116): `.throw()` has cleaner display of errors when WebKit browsers. +- [#120](https://github.com/chaijs/chai/issues/120): `.eql()` now works to compare dom nodes in browsers. + + +### Usage Updates + +#### For Users + +**1. Component Support:** Chai now included the proper configuration to be installed as a +[component](https://github.com/component/component). Component users are encouraged to consult +[chaijs.com](http://chaijs.com) for the latest version number as using the master branch +does not gaurantee stability. + +```js +// relevant component.json + devDependencies: { + "chaijs/chai": "1.5.0" + } +``` + +Alternatively, bleeding-edge is available: + + $ component install chaijs/chai + +**2. Configurable showDiff:** Some test runners (such as [mocha](http://visionmedia.github.com/mocha/)) +include support for showing the diff of strings and objects when an equality error occurs. Chai has +already included support for this, however some users may not prefer this display behavior. To revert to +no diff display, the following configuration is available: + +```js +chai.Assertion.showDiff = false; // diff output disabled +chai.Assertion.showDiff = true; // default, diff output enabled +``` + +#### For Plugin Developers + +**1. New Utility - type**: The new utility `.type()` is available as a better implementation of `typeof` +that can be used cross-browser. It handles the inconsistencies of Array, `null`, and `undefined` detection. + +- **@param** _{Mixed}_ object to detect type of +- **@return** _{String}_ object type + +```js +chai.use(function (c, utils) { + // some examples + utils.type({}); // 'object' + utils.type(null); // `null' + utils.type(undefined); // `undefined` + utils.type([]); // `array` +}); +``` + +#### For Core Contributors + +**1. Browser Testing**: Browser testing of the `./chai.js` file is now available in the command line +via PhantomJS. `make test` and Travis-CI will now also rebuild and test `./chai.js`. Consequently, all +pull requests will now be browser tested in this way. + +_Note: Contributors opening pull requests should still NOT include the browser build._ + +**2. SauceLabs Testing**: Early SauceLab support has been enabled with the file `./support/mocha-cloud.js`. +Those interested in trying it out should create a free [Open Sauce](https://saucelabs.com/signup/plan) account +and include their credentials in `./test/auth/sauce.json`. diff --git a/web/node_modules/chai/bower.json b/web/node_modules/chai/bower.json new file mode 100644 index 0000000000000000000000000000000000000000..af2ee029b735697d1aaf0dea45ae8a6962b44412 --- /dev/null +++ b/web/node_modules/chai/bower.json @@ -0,0 +1,26 @@ +{ + "name": "chai", + "description": "BDD/TDD assertion library for node.js and the browser. Test framework agnostic.", + "license": "MIT", + "keywords": [ + "test", + "assertion", + "assert", + "testing", + "chai" + ], + "main": "chai.js", + "ignore": [ + "build", + "components", + "lib", + "node_modules", + "support", + "test", + "index.js", + "Makefile", + ".*" + ], + "dependencies": {}, + "devDependencies": {} +} diff --git a/web/node_modules/chai/chai.js b/web/node_modules/chai/chai.js new file mode 100644 index 0000000000000000000000000000000000000000..1859d88f478c2415adaa5e7fdd6fe9820d387e1e --- /dev/null +++ b/web/node_modules/chai/chai.js @@ -0,0 +1,11549 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.chai = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * MIT Licensed + */ + +var used = []; + +/*! + * Chai version + */ + +exports.version = '4.3.8'; + +/*! + * Assertion Error + */ + +exports.AssertionError = require('assertion-error'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('./chai/utils'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai. + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(exports, util); + used.push(fn); + } + + return exports; +}; + +/*! + * Utility Functions + */ + +exports.util = util; + +/*! + * Configuration + */ + +var config = require('./chai/config'); +exports.config = config; + +/*! + * Primary `Assertion` prototype + */ + +var assertion = require('./chai/assertion'); +exports.use(assertion); + +/*! + * Core Assertions + */ + +var core = require('./chai/core/assertions'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('./chai/interface/expect'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('./chai/interface/should'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('./chai/interface/assert'); +exports.use(assert); + +},{"./chai/assertion":3,"./chai/config":4,"./chai/core/assertions":5,"./chai/interface/assert":6,"./chai/interface/expect":7,"./chai/interface/should":8,"./chai/utils":22,"assertion-error":33}],3:[function(require,module,exports){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var config = require('./config'); + +module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * - `eql`: This flag contains the deepEqual function to be used by the assertion. + * + * @param {Mixed} obj target of the assertion + * @param {String} msg (optional) custom error message + * @param {Function} ssfi (optional) starting point for removing stack frames + * @param {Boolean} lockSsfi (optional) whether or not the ssfi flag is locked + * @api private + */ + + function Assertion (obj, msg, ssfi, lockSsfi) { + flag(this, 'ssfi', ssfi || Assertion); + flag(this, 'lockSsfi', lockSsfi); + flag(this, 'object', obj); + flag(this, 'message', msg); + flag(this, 'eql', config.deepEqual || util.eql); + + return util.proxify(this); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String|Function} message or function that returns message to display if expression fails + * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (false !== showDiff) showDiff = true; + if (undefined === expected && undefined === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + msg = util.getMessage(this, arguments); + var actual = util.getActual(this, arguments); + var assertionErrorObjectProperties = { + actual: actual + , expected: expected + , showDiff: showDiff + }; + + var operator = util.getOperator(this, arguments); + if (operator) { + assertionErrorObjectProperties.operator = operator; + } + + throw new AssertionError( + msg, + assertionErrorObjectProperties, + (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); +}; + +},{"./config":4}],4:[function(require,module,exports){ +module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40, + + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {Boolean} + * @api public + */ + + useProxy: true, + + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @api public + */ + + proxyExcludedKeys: ['then', 'catch', 'inspect', 'toJSON'], + + /** + * ### config.deepEqual + * + * User configurable property, defines which a custom function to use for deepEqual + * comparisons. + * By default, the function used is the one from the `deep-eql` package without custom comparator. + * + * // use a custom comparator + * chai.config.deepEqual = (expected, actual) => { + * return chai.util.eql(expected, actual, { + * comparator: (expected, actual) => { + * // for non number comparison, use the default behavior + * if(typeof expected !== 'number') return null; + * // allow a difference of 10 between compared numbers + * return typeof actual === 'number' && Math.abs(actual - expected) < 10 + * } + * }) + * }; + * + * @param {Function} + * @api public + */ + + deepEqual: null + +}; + +},{}],5:[function(require,module,exports){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, _) { + var Assertion = chai.Assertion + , AssertionError = chai.AssertionError + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to improve the readability + * of your assertions. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * - but + * - does + * - still + * - also + * + * @name language chains + * @namespace BDD + * @api public + */ + + [ 'to', 'be', 'been', 'is' + , 'and', 'has', 'have', 'with' + , 'that', 'which', 'at', 'of' + , 'same', 'but', 'does', 'still', "also" ].forEach(function (chain) { + Assertion.addProperty(chain); + }); + + /** + * ### .not + * + * Negates all assertions that follow in the chain. + * + * expect(function () {}).to.not.throw(); + * expect({a: 1}).to.not.have.property('b'); + * expect([1, 2]).to.be.an('array').that.does.not.include(3); + * + * Just because you can negate any assertion with `.not` doesn't mean you + * should. With great power comes great responsibility. It's often best to + * assert that the one expected output was produced, rather than asserting + * that one of countless unexpected outputs wasn't produced. See individual + * assertions for specific guidance. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.equal(1); // Not recommended + * + * @name not + * @namespace BDD + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` + * assertions that follow in the chain to use deep equality instead of strict + * (`===`) equality. See the `deep-eql` project page for info on the deep + * equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * @name deep + * @namespace BDD + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .nested + * + * Enables dot- and bracket-notation in all `.property` and `.include` + * assertions that follow in the chain. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); + * + * `.nested` cannot be combined with `.own`. + * + * @name nested + * @namespace BDD + * @api public + */ + + Assertion.addProperty('nested', function () { + flag(this, 'nested', true); + }); + + /** + * ### .own + * + * Causes all `.property` and `.include` assertions that follow in the chain + * to ignore inherited properties. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * `.own` cannot be combined with `.nested`. + * + * @name own + * @namespace BDD + * @api public + */ + + Assertion.addProperty('own', function () { + flag(this, 'own', true); + }); + + /** + * ### .ordered + * + * Causes all `.members` assertions that follow in the chain to require that + * members be in the same order. + * + * expect([1, 2]).to.have.ordered.members([1, 2]) + * .but.not.have.ordered.members([2, 1]); + * + * When `.include` and `.ordered` are combined, the ordering begins at the + * start of both arrays. + * + * expect([1, 2, 3]).to.include.ordered.members([1, 2]) + * .but.not.include.ordered.members([2, 3]); + * + * @name ordered + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ordered', function () { + flag(this, 'ordered', true); + }); + + /** + * ### .any + * + * Causes all `.keys` assertions that follow in the chain to only require that + * the target have at least one of the given keys. This is the opposite of + * `.all`, which requires that the target have all of the given keys. + * + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name any + * @namespace BDD + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false); + }); + + /** + * ### .all + * + * Causes all `.keys` assertions that follow in the chain to require that the + * target have all of the given keys. This is the opposite of `.any`, which + * only requires that the target have at least one of the given keys. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` are + * added earlier in the chain. However, it's often best to add `.all` anyway + * because it improves readability. + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name all + * @namespace BDD + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type[, msg]) + * + * Asserts that the target's type is equal to the given string `type`. Types + * are case insensitive. See the `type-detect` project page for info on the + * type detection algorithm: https://github.com/chaijs/type-detect. + * + * expect('foo').to.be.a('string'); + * expect({a: 1}).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * expect(new Error).to.be.an('error'); + * expect(Promise.resolve()).to.be.a('promise'); + * expect(new Float32Array).to.be.a('float32array'); + * expect(Symbol()).to.be.a('symbol'); + * + * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. + * + * var myObj = { + * [Symbol.toStringTag]: 'myCustomType' + * }; + * + * expect(myObj).to.be.a('myCustomType').but.not.an('object'); + * + * It's often best to use `.a` to check a target's type before making more + * assertions on the same target. That way, you avoid unexpected behavior from + * any assertion that does different things based on the target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.a`. However, it's often best to + * assert that the target is the expected type, rather than asserting that it + * isn't one of many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.an('array'); // Not recommended + * + * `.a` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * expect(1).to.be.a('string', 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.a('string'); + * + * `.a` can also be used as a language chain to improve the readability of + * your assertions. + * + * expect({b: 2}).to.have.a.property('b'); + * + * The alias `.an` can be used interchangeably with `.a`. + * + * @name a + * @alias an + * @param {String} type + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj).toLowerCase() + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(val[, msg]) + * + * When the target is a string, `.include` asserts that the given string `val` + * is a substring of the target. + * + * expect('foobar').to.include('foo'); + * + * When the target is an array, `.include` asserts that the given `val` is a + * member of the target. + * + * expect([1, 2, 3]).to.include(2); + * + * When the target is an object, `.include` asserts that the given object + * `val`'s properties are a subset of the target's properties. + * + * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); + * + * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a + * member of the target. SameValueZero equality algorithm is used. + * + * expect(new Set([1, 2])).to.include(2); + * + * When the target is a Map, `.include` asserts that the given `val` is one of + * the values of the target. SameValueZero equality algorithm is used. + * + * expect(new Map([['a', 1], ['b', 2]])).to.include(2); + * + * Because `.include` does different things based on the target's type, it's + * important to check the target's type before using `.include`. See the `.a` + * doc for info on testing a target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * + * By default, strict (`===`) equality is used to compare array members and + * object properties. Add `.deep` earlier in the chain to use deep equality + * instead (WeakSet targets are not supported). See the `deep-eql` project + * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * By default, all of the target's properties are searched when working with + * objects. This includes properties that are inherited and/or non-enumerable. + * Add `.own` earlier in the chain to exclude the target's inherited + * properties from the search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * Note that a target object is always only searched for `val`'s own + * enumerable properties. + * + * `.deep` and `.own` can be combined. + * + * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.include`. + * + * expect('foobar').to.not.include('taco'); + * expect([1, 2, 3]).to.not.include(4); + * + * However, it's dangerous to negate `.include` when the target is an object. + * The problem is that it creates uncertain expectations by asserting that the + * target object doesn't have all of `val`'s key/value pairs but may or may + * not have some of them. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target object isn't even expected to have `val`'s keys, it's + * often best to assert exactly that. + * + * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended + * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended + * + * When the target object is expected to have `val`'s keys, it's often best to + * assert that each of the properties has its expected value, rather than + * asserting that each property doesn't have one of many unexpected values. + * + * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended + * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended + * + * `.include` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.include(4); + * + * `.include` can also be used as a language chain, causing all `.members` and + * `.keys` assertions that follow in the chain to require the target to be a + * superset of the expected set, rather than an identical set. Note that + * `.members` ignores duplicates in the subset when `.include` is added. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * Note that adding `.any` earlier in the chain causes the `.keys` assertion + * to ignore `.include`. + * + * // Both assertions are identical + * expect({a: 1}).to.include.any.keys('a', 'b'); + * expect({a: 1}).to.have.any.keys('a', 'b'); + * + * The aliases `.includes`, `.contain`, and `.contains` can be used + * interchangeably with `.include`. + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function SameValueZero(a, b) { + return (_.isNaN(a) && _.isNaN(b)) || a === b; + } + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + if (msg) flag(this, 'message', msg); + + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , descriptor = isDeep ? 'deep ' : '' + , isEql = isDeep ? flag(this, 'eql') : SameValueZero; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + var included = false; + + switch (objType) { + case 'string': + included = obj.indexOf(val) !== -1; + break; + + case 'weakset': + if (isDeep) { + throw new AssertionError( + flagMsg + 'unable to use .deep.include with WeakSet', + undefined, + ssfi + ); + } + + included = obj.has(val); + break; + + case 'map': + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + break; + + case 'set': + if (isDeep) { + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + } else { + included = obj.has(val); + } + break; + + case 'array': + if (isDeep) { + included = obj.some(function (item) { + return isEql(item, val); + }) + } else { + included = obj.indexOf(val) !== -1; + } + break; + + default: + // This block is for asserting a subset of properties in an object. + // `_.expectTypes` isn't used here because `.include` should work with + // objects with a custom `@@toStringTag`. + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + 'the given combination of arguments (' + + objType + ' and ' + + _.type(val).toLowerCase() + ')' + + ' is invalid for this assertion. ' + + 'You can use an array, a map, an object, a set, a string, ' + + 'or a weakset instead of a ' + + _.type(val).toLowerCase(), + undefined, + ssfi + ); + } + + var props = Object.keys(val) + , firstErr = null + , numErrs = 0; + + props.forEach(function (prop) { + var propAssertion = new Assertion(obj); + _.transferFlags(this, propAssertion, true); + flag(propAssertion, 'lockSsfi', true); + + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!_.checkError.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + + // When validating .not.include with multiple properties, we only want + // to throw an assertion error if all of the properties are included, + // in which case we throw the first property assertion error that we + // encountered. + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + + // Assert inclusion in collection or substring in a string. + this.assert( + included + , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) + , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is a truthy value (considered `true` in boolean context). + * However, it's often best to assert that the target is strictly (`===`) or + * deeply equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.ok; // Not recommended + * + * expect(true).to.be.true; // Recommended + * expect(true).to.be.ok; // Not recommended + * + * Add `.not` earlier in the chain to negate `.ok`. + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.not.be.ok; // Not recommended + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.ok; // Not recommended + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.be.ok; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.be.ok; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.ok; + * + * @name ok + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is strictly (`===`) equal to `true`. + * + * expect(true).to.be.true; + * + * Add `.not` earlier in the chain to negate `.true`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `true`. + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.true; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.true; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.true; + * + * @name true + * @namespace BDD + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , flag(this, 'negate') ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is strictly (`===`) equal to `false`. + * + * expect(false).to.be.false; + * + * Add `.not` earlier in the chain to negate `.false`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `false`. + * + * expect(true).to.be.true; // Recommended + * expect(true).to.not.be.false; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.false; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(true, 'nooo why fail??').to.be.false; + * + * @name false + * @namespace BDD + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , flag(this, 'negate') ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is strictly (`===`) equal to `null`. + * + * expect(null).to.be.null; + * + * Add `.not` earlier in the chain to negate `.null`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `null`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.null; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.null; + * + * @name null + * @namespace BDD + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is strictly (`===`) equal to `undefined`. + * + * expect(undefined).to.be.undefined; + * + * Add `.not` earlier in the chain to negate `.undefined`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `undefined`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.undefined; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.undefined; + * + * @name undefined + * @namespace BDD + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .NaN + * + * Asserts that the target is exactly `NaN`. + * + * expect(NaN).to.be.NaN; + * + * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `NaN`. + * + * expect('foo').to.equal('foo'); // Recommended + * expect('foo').to.not.be.NaN; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.NaN; + * + * @name NaN + * @namespace BDD + * @api public + */ + + Assertion.addProperty('NaN', function () { + this.assert( + _.isNaN(flag(this, 'object')) + , 'expected #{this} to be NaN' + , 'expected #{this} not to be NaN' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is not strictly (`===`) equal to either `null` or + * `undefined`. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.exist; // Not recommended + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.exist; // Not recommended + * + * Add `.not` earlier in the chain to negate `.exist`. + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.exist; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.exist; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(null, 'nooo why fail??').to.exist; + * + * The alias `.exists` can be used interchangeably with `.exist`. + * + * @name exist + * @alias exists + * @namespace BDD + * @api public + */ + + function assertExist () { + var val = flag(this, 'object'); + this.assert( + val !== null && val !== undefined + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + } + + Assertion.addProperty('exist', assertExist); + Assertion.addProperty('exists', assertExist); + + /** + * ### .empty + * + * When the target is a string or array, `.empty` asserts that the target's + * `length` property is strictly (`===`) equal to `0`. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * + * When the target is a map or set, `.empty` asserts that the target's `size` + * property is strictly equal to `0`. + * + * expect(new Set()).to.be.empty; + * expect(new Map()).to.be.empty; + * + * When the target is a non-function object, `.empty` asserts that the target + * doesn't have any own enumerable properties. Properties with Symbol-based + * keys are excluded from the count. + * + * expect({}).to.be.empty; + * + * Because `.empty` does different things based on the target's type, it's + * important to check the target's type before using `.empty`. See the `.a` + * doc for info on testing a target's type. + * + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.empty`. However, it's often + * best to assert that the target contains its expected number of values, + * rather than asserting that it's not empty. + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.not.be.empty; // Not recommended + * + * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended + * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended + * + * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended + * expect({a: 1}).to.not.be.empty; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect([1, 2, 3], 'nooo why fail??').to.be.empty; + * + * @name empty + * @namespace BDD + * @api public + */ + + Assertion.addProperty('empty', function () { + var val = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , itemsCount; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + switch (_.type(val).toLowerCase()) { + case 'array': + case 'string': + itemsCount = val.length; + break; + case 'map': + case 'set': + itemsCount = val.size; + break; + case 'weakmap': + case 'weakset': + throw new AssertionError( + flagMsg + '.empty was passed a weak collection', + undefined, + ssfi + ); + case 'function': + var msg = flagMsg + '.empty was passed a function ' + _.getName(val); + throw new AssertionError(msg.trim(), undefined, ssfi); + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), + undefined, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + + this.assert( + 0 === itemsCount + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an `arguments` object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * test(); + * + * Add `.not` earlier in the chain to negate `.arguments`. However, it's often + * best to assert which type the target is expected to be, rather than + * asserting that it’s not an `arguments` object. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.arguments; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({}, 'nooo why fail??').to.be.arguments; + * + * The alias `.Arguments` can be used interchangeably with `.arguments`. + * + * @name arguments + * @alias Arguments + * @namespace BDD + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = _.type(obj); + this.assert( + 'Arguments' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(val[, msg]) + * + * Asserts that the target is strictly (`===`) equal to the given `val`. + * + * expect(1).to.equal(1); + * expect('foo').to.equal('foo'); + * + * Add `.deep` earlier in the chain to use deep equality instead. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) equals `[1, 2]` + * expect([1, 2]).to.deep.equal([1, 2]); + * expect([1, 2]).to.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.equal`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to one of countless unexpected values. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.equal(2); // Not recommended + * + * `.equal` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.equal(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.equal(2); + * + * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. + * + * @name equal + * @alias equals + * @alias eq + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + var prevLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + this.eql(val); + flag(this, 'lockSsfi', prevLockSsfi); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(obj[, msg]) + * + * Asserts that the target is deeply equal to the given `obj`. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object is deeply (but not strictly) equal to {a: 1} + * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); + * + * // Target array is deeply (but not strictly) equal to [1, 2] + * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.eql`. However, it's often best + * to assert that the target is deeply equal to its expected value, rather + * than not deeply equal to one of countless unexpected values. + * + * expect({a: 1}).to.eql({a: 1}); // Recommended + * expect({a: 1}).to.not.eql({b: 2}); // Not recommended + * + * `.eql` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); + * + * The alias `.eqls` can be used interchangeably with `.eql`. + * + * The `.deep.equal` assertion is almost identical to `.eql` but with one + * difference: `.deep.equal` causes deep equality comparisons to also be used + * for any other assertions that follow in the chain. + * + * @name eql + * @alias eqls + * @param {Mixed} obj + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + var eql = flag(this, 'eql'); + this.assert( + eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(n[, msg]) + * + * Asserts that the target is a number or a date greater than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.above(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.above(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.above`. + * + * expect(2).to.equal(2); // Recommended + * expect(1).to.not.be.above(2); // Not recommended + * + * `.above` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.above(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.above(2); + * + * The aliases `.gt` and `.greaterThan` can be used interchangeably with + * `.above`. + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to above must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to above must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n + , 'expected #{this} to have a ' + descriptor + ' above #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above #{exp}' + , 'expected #{this} to be at most #{exp}' + , n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(n[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `n` respectively. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.at.least(1); // Not recommended + * expect(2).to.be.at.least(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.least(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.least`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.at.least(2); // Not recommended + * + * `.least` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.at.least(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.at.least(2); + * + * The aliases `.gte` and `.greaterThanOrEqual` can be used interchangeably with + * `.least`. + * + * @name least + * @alias gte + * @alias greaterThanOrEqual + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to least must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to least must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n + , 'expected #{this} to have a ' + descriptor + ' at least #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least #{exp}' + , 'expected #{this} to be below #{exp}' + , n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + Assertion.addMethod('greaterThanOrEqual', assertLeast); + + /** + * ### .below(n[, msg]) + * + * Asserts that the target is a number or a date less than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.below(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.below(4); // Not recommended + * + * expect([1, 2, 3]).to.have.length(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.below`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.below(1); // Not recommended + * + * `.below` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.below(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.below(1); + * + * The aliases `.lt` and `.lessThan` can be used interchangeably with + * `.below`. + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to below must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to below must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n + , 'expected #{this} to have a ' + descriptor + ' below #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below #{exp}' + , 'expected #{this} to be at least #{exp}' + , n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(n[, msg]) + * + * Asserts that the target is a number or a date less than or equal to the given number + * or date `n` respectively. However, it's often best to assert that the target is equal to its + * expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.at.most(2); // Not recommended + * expect(1).to.be.at.most(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.most(4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.most`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.at.most(1); // Not recommended + * + * `.most` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.at.most(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.at.most(1); + * + * The aliases `.lte` and `.lessThanOrEqual` can be used interchangeably with + * `.most`. + * + * @name most + * @alias lte + * @alias lessThanOrEqual + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to most must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to most must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n + , 'expected #{this} to have a ' + descriptor + ' at most #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most #{exp}' + , 'expected #{this} to be above #{exp}' + , n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + Assertion.addMethod('lessThanOrEqual', assertMost); + + /** + * ### .within(start, finish[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `start`, and less than or equal to the given number or date `finish` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.within(1, 3); // Not recommended + * expect(2).to.be.within(2, 3); // Not recommended + * expect(2).to.be.within(1, 2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `start`, and less + * than or equal to the given number `finish`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.within`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.within(2, 4); // Not recommended + * + * `.within` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(4).to.be.within(1, 3, 'nooo why fail??'); + * expect(4, 'nooo why fail??').to.be.within(1, 3); + * + * @name within + * @param {Number} start lower bound inclusive + * @param {Number} finish upper bound inclusive + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , startType = _.type(start).toLowerCase() + , finishType = _.type(finish).toLowerCase() + , errorMessage + , shouldThrow = true + , range = (startType === 'date' && finishType === 'date') + ? start.toISOString() + '..' + finish.toISOString() + : start + '..' + finish; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { + errorMessage = msgPrefix + 'the arguments to within must be dates'; + } else if ((startType !== 'number' || finishType !== 'number') && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the arguments to within must be numbers'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish + , 'expected #{this} to have a ' + descriptor + ' within ' + range + , 'expected #{this} to not have a ' + descriptor + ' within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor[, msg]) + * + * Asserts that the target is an instance of the given `constructor`. + * + * function Cat () { } + * + * expect(new Cat()).to.be.an.instanceof(Cat); + * expect([1, 2]).to.be.an.instanceof(Array); + * + * Add `.not` earlier in the chain to negate `.instanceof`. + * + * expect({a: 1}).to.not.be.an.instanceof(Array); + * + * `.instanceof` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); + * + * Due to limitations in ES5, `.instanceof` may not always work as expected + * when using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing built-in object such as + * `Array`, `Error`, and `Map`. See your transpiler's docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * The alias `.instanceOf` can be used interchangeably with `.instanceof`. + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} msg _optional_ + * @alias instanceOf + * @namespace BDD + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + + var target = flag(this, 'object') + var ssfi = flag(this, 'ssfi'); + var flagMsg = flag(this, 'message'); + + try { + var isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'The instanceof assertion needs a constructor but ' + + _.type(constructor) + ' was given.', + undefined, + ssfi + ); + } + throw err; + } + + var name = _.getName(constructor); + if (name === null) { + name = 'an unnamed constructor'; + } + + this.assert( + isInstanceOf + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name[, val[, msg]]) + * + * Asserts that the target has a property with the given key `name`. + * + * expect({a: 1}).to.have.property('a'); + * + * When `val` is provided, `.property` also asserts that the property's value + * is equal to the given `val`. + * + * expect({a: 1}).to.have.property('a', 1); + * + * By default, strict (`===`) equality is used. Add `.deep` earlier in the + * chain to use deep equality instead. See the `deep-eql` project page for + * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * The target's enumerable and non-enumerable properties are always included + * in the search. By default, both own and inherited properties are included. + * Add `.own` earlier in the chain to exclude inherited properties from the + * search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.own.property('a', 1); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * `.deep` and `.own` can be combined. + * + * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}) + * .to.have.deep.nested.property('a.b[0]', {c: 3}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.property`. + * + * expect({a: 1}).to.not.have.property('b'); + * + * However, it's dangerous to negate `.property` when providing `val`. The + * problem is that it creates uncertain expectations by asserting that the + * target either doesn't have a property with the given key `name`, or that it + * does have a property with the given key `name` but its value isn't equal to + * the given `val`. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target isn't expected to have a property with the given key + * `name`, it's often best to assert exactly that. + * + * expect({b: 2}).to.not.have.property('a'); // Recommended + * expect({b: 2}).to.not.have.property('a', 1); // Not recommended + * + * When the target is expected to have a property with the given key `name`, + * it's often best to assert that the property has its expected value, rather + * than asserting that it doesn't have one of many unexpected values. + * + * expect({a: 3}).to.have.property('a', 3); // Recommended + * expect({a: 3}).to.not.have.property('a', 1); // Not recommended + * + * `.property` changes the target of any assertions that follow in the chain + * to be the value of the property from the original target object. + * + * expect({a: 1}).to.have.property('a').that.is.a('number'); + * + * `.property` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing `val`, only use the + * second form. + * + * // Recommended + * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); + * expect({a: 1}, 'nooo why fail??').to.have.property('b'); + * + * // Not recommended + * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `val`. Instead, + * it's asserting that the target object has a `b` property that's equal to + * `undefined`. + * + * The assertions `.ownProperty` and `.haveOwnProperty` can be used + * interchangeably with `.own.property`. + * + * @name property + * @param {String} name + * @param {Mixed} val (optional) + * @param {String} msg _optional_ + * @returns value of property for chaining + * @namespace BDD + * @api public + */ + + function assertProperty (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isNested = flag(this, 'nested') + , isOwn = flag(this, 'own') + , flagMsg = flag(this, 'message') + , obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , nameType = typeof name; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + if (isNested) { + if (nameType !== 'string') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string when using nested syntax', + undefined, + ssfi + ); + } + } else { + if (nameType !== 'string' && nameType !== 'number' && nameType !== 'symbol') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string, number, or symbol', + undefined, + ssfi + ); + } + } + + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + undefined, + ssfi + ); + } + + if (obj === null || obj === undefined) { + throw new AssertionError( + flagMsg + 'Target cannot be null or undefined.', + undefined, + ssfi + ); + } + + var isDeep = flag(this, 'deep') + , negate = flag(this, 'negate') + , pathInfo = isNested ? _.getPathInfo(obj, name) : null + , value = isNested ? pathInfo.value : obj[name] + , isEql = isDeep ? flag(this, 'eql') : (val1, val2) => val1 === val2;; + + var descriptor = ''; + if (isDeep) descriptor += 'deep '; + if (isOwn) descriptor += 'own '; + if (isNested) descriptor += 'nested '; + descriptor += 'property '; + + var hasProperty; + if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty = pathInfo.exists; + else hasProperty = _.hasProperty(obj, name); + + // When performing a negated assertion for both name and val, merely having + // a property with the given name isn't enough to cause the assertion to + // fail. It must both have a property with the given name, and the value of + // that property must equal the given val. Therefore, skip this assertion in + // favor of the next. + if (!negate || arguments.length === 1) { + this.assert( + hasProperty + , 'expected #{this} to have ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (arguments.length > 1) { + this.assert( + hasProperty && isEql(val, value) + , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + } + + Assertion.addMethod('property', assertProperty); + + function assertOwnProperty (name, value, msg) { + flag(this, 'own', true); + assertProperty.apply(this, arguments); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) + * + * Asserts that the target has its own property descriptor with the given key + * `name`. Enumerable and non-enumerable properties are included in the + * search. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a'); + * + * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that + * the property's descriptor is deeply equal to the given `descriptor`. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. + * + * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); + * + * However, it's dangerous to negate `.ownPropertyDescriptor` when providing + * a `descriptor`. The problem is that it creates uncertain expectations by + * asserting that the target either doesn't have a property descriptor with + * the given key `name`, or that it does have a property descriptor with the + * given key `name` but it’s not deeply equal to the given `descriptor`. It's + * often best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to have a property descriptor with the given + * key `name`, it's often best to assert exactly that. + * + * // Recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); + * + * // Not recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * When the target is expected to have a property descriptor with the given + * key `name`, it's often best to assert that the property has its expected + * descriptor, rather than asserting that it doesn't have one of many + * unexpected descriptors. + * + * // Recommended + * expect({a: 3}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 3, + * }); + * + * // Not recommended + * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * `.ownPropertyDescriptor` changes the target of any assertions that follow + * in the chain to be the value of the property descriptor from the original + * target object. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a') + * .that.has.property('enumerable', true); + * + * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a + * custom error message to show when the assertion fails. The message can also + * be given as the second argument to `expect`. When not providing + * `descriptor`, only use the second form. + * + * // Recommended + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }, 'nooo why fail??'); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); + * + * // Not recommended + * expect({a: 1}) + * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `descriptor`. + * Instead, it's asserting that the target object has a `b` property + * descriptor that's deeply equal to `undefined`. + * + * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with + * `.ownPropertyDescriptor`. + * + * @name ownPropertyDescriptor + * @alias haveOwnPropertyDescriptor + * @param {String} name + * @param {Object} descriptor _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertOwnPropertyDescriptor (name, descriptor, msg) { + if (typeof descriptor === 'string') { + msg = descriptor; + descriptor = null; + } + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + var eql = flag(this, 'eql'); + if (actualDescriptor && descriptor) { + this.assert( + eql(descriptor, actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) + , descriptor + , actualDescriptor + , true + ); + } else { + this.assert( + actualDescriptor + , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) + , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) + ); + } + flag(this, 'object', actualDescriptor); + } + + Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); + Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); + + /** + * ### .lengthOf(n[, msg]) + * + * Asserts that the target's `length` or `size` is equal to the given number + * `n`. + * + * expect([1, 2, 3]).to.have.lengthOf(3); + * expect('foo').to.have.lengthOf(3); + * expect(new Set([1, 2, 3])).to.have.lengthOf(3); + * expect(new Map([['a', 1], ['b', 2], ['c', 3]])).to.have.lengthOf(3); + * + * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often + * best to assert that the target's `length` property is equal to its expected + * value, rather than not equal to one of many unexpected values. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.not.have.lengthOf(4); // Not recommended + * + * `.lengthOf` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); + * + * `.lengthOf` can also be used as a language chain, causing all `.above`, + * `.below`, `.least`, `.most`, and `.within` assertions that follow in the + * chain to use the target's `length` property as the target. However, it's + * often best to assert that the target's `length` property is equal to its + * expected length, rather than asserting that its `length` property falls + * within some range of values. + * + * // Recommended + * expect([1, 2, 3]).to.have.lengthOf(3); + * + * // Not recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); + * expect([1, 2, 3]).to.have.lengthOf.below(4); + * expect([1, 2, 3]).to.have.lengthOf.at.least(3); + * expect([1, 2, 3]).to.have.lengthOf.at.most(3); + * expect([1, 2, 3]).to.have.lengthOf.within(2,4); + * + * Due to a compatibility issue, the alias `.length` can't be chained directly + * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used + * interchangeably with `.lengthOf` in every situation. It's recommended to + * always use `.lengthOf` instead of `.length`. + * + * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error + * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected + * + * @name lengthOf + * @alias length + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , descriptor = 'length' + , itemsCount; + + switch (objType) { + case 'map': + case 'set': + descriptor = 'size'; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + itemsCount = obj.length; + } + + this.assert( + itemsCount == n + , 'expected #{this} to have a ' + descriptor + ' of #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' of #{act}' + , n + , itemsCount + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); + + /** + * ### .match(re[, msg]) + * + * Asserts that the target matches the given regular expression `re`. + * + * expect('foobar').to.match(/^foo/); + * + * Add `.not` earlier in the chain to negate `.match`. + * + * expect('foobar').to.not.match(/taco/); + * + * `.match` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect('foobar').to.match(/taco/, 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.match(/taco/); + * + * The alias `.matches` can be used interchangeably with `.match`. + * + * @name match + * @alias matches + * @param {RegExp} re + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + function assertMatch(re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + } + + Assertion.addMethod('match', assertMatch); + Assertion.addMethod('matches', assertMatch); + + /** + * ### .string(str[, msg]) + * + * Asserts that the target string contains the given substring `str`. + * + * expect('foobar').to.have.string('bar'); + * + * Add `.not` earlier in the chain to negate `.string`. + * + * expect('foobar').to.not.have.string('taco'); + * + * `.string` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect('foobar').to.have.string('taco', 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.have.string('taco'); + * + * @name string + * @param {String} str + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(obj, flagMsg, ssfi, true).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + /** + * ### .keys(key1[, key2[, ...]]) + * + * Asserts that the target object, array, map, or set has the given keys. Only + * the target's own inherited properties are included in the search. + * + * When the target is an object or array, keys can be provided as one or more + * string arguments, a single array argument, or a single object argument. In + * the latter case, only the keys in the given object matter; the values are + * ignored. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * expect(['x', 'y']).to.have.all.keys(0, 1); + * + * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); + * expect(['x', 'y']).to.have.all.keys([0, 1]); + * + * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 + * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 + * + * When the target is a map or set, each key must be provided as a separate + * argument. + * + * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); + * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); + * + * Because `.keys` does different things based on the target's type, it's + * important to check the target's type before using `.keys`. See the `.a` doc + * for info on testing a target's type. + * + * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); + * + * By default, strict (`===`) equality is used to compare keys of maps and + * sets. Add `.deep` earlier in the chain to use deep equality instead. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); + * + * By default, the target must have all of the given keys and no more. Add + * `.any` earlier in the chain to only require that the target have at least + * one of the given keys. Also, add `.not` earlier in the chain to negate + * `.keys`. It's often best to add `.any` when negating `.keys`, and to use + * `.all` when asserting `.keys` without negation. + * + * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts + * exactly what's expected of the output, whereas `.not.all.keys` creates + * uncertain expectations. + * + * // Recommended; asserts that target doesn't have any of the given keys + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * // Not recommended; asserts that target doesn't have all of the given + * // keys but may or may not have some of them + * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); + * + * When asserting `.keys` without negation, `.all` is preferred because + * `.all.keys` asserts exactly what's expected of the output, whereas + * `.any.keys` creates uncertain expectations. + * + * // Recommended; asserts that target has all the given keys + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * // Not recommended; asserts that target has at least one of the given + * // keys but may or may not have more of them + * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` appear + * earlier in the chain. However, it's often best to add `.all` anyway because + * it improves readability. + * + * // Both assertions are identical + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended + * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended + * + * Add `.include` earlier in the chain to require that the target's keys be a + * superset of the expected keys, rather than identical sets. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * However, if `.any` and `.include` are combined, only the `.any` takes + * effect. The `.include` is ignored in this case. + * + * // Both assertions are identical + * expect({a: 1}).to.have.any.keys('a', 'b'); + * expect({a: 1}).to.include.any.keys('a', 'b'); + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.have.key('b'); + * + * The alias `.key` can be used interchangeably with `.keys`. + * + * @name keys + * @alias key + * @param {...String|Array|Object} keys + * @namespace BDD + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , objType = _.type(obj) + , keysType = _.type(keys) + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , str + , deepStr = '' + , actual + , ok = true + , flagMsg = flag(this, 'message'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; + + if (objType === 'Map' || objType === 'Set') { + deepStr = isDeep ? 'deeply ' : ''; + actual = []; + + // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. + obj.forEach(function (val, key) { actual.push(key) }); + + if (keysType !== 'Array') { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = _.getOwnEnumerableProperties(obj); + + switch (keysType) { + case 'Array': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + break; + case 'Object': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + + // Only stringify non-Symbols because Symbols would become "Symbol()" + keys = keys.map(function (val) { + return typeof val === 'symbol' ? val : String(val); + }); + } + + if (!keys.length) { + throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); + } + + var len = keys.length + , any = flag(this, 'any') + , all = flag(this, 'all') + , expected = keys + , isEql = isDeep ? flag(this, 'eql') : (val1, val2) => val1 === val2; + + if (!any && !all) { + all = true; + } + + // Has any + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + } + + // Has all + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + + if (!flag(this, 'contains')) { + ok = ok && keys.length == actual.length; + } + } + + // Key string + if (len > 1) { + keys = keys.map(function(key) { + return _.inspect(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(', ') + ', and ' + last; + } + if (any) { + str = keys.join(', ') + ', or ' + last; + } + } else { + str = _.inspect(keys[0]); + } + + // Form + str = (len > 1 ? 'keys ' : 'key ') + str; + + // Have / include + str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + + // Assertion + this.assert( + ok + , 'expected #{this} to ' + deepStr + str + , 'expected #{this} to not ' + deepStr + str + , expected.slice(0).sort(_.compareByInspect) + , actual.sort(_.compareByInspect) + , true + ); + } + + Assertion.addMethod('keys', assertKeys); + Assertion.addMethod('key', assertKeys); + + /** + * ### .throw([errorLike], [errMsgMatcher], [msg]) + * + * When no arguments are provided, `.throw` invokes the target function and + * asserts that an error is thrown. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(); + * + * When one argument is provided, and it's an error constructor, `.throw` + * invokes the target function and asserts that an error is thrown that's an + * instance of that error constructor. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError); + * + * When one argument is provided, and it's an error instance, `.throw` invokes + * the target function and asserts that an error is thrown that's strictly + * (`===`) equal to that error instance. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(err); + * + * When one argument is provided, and it's a string, `.throw` invokes the + * target function and asserts that an error is thrown with a message that + * contains that string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw('salmon'); + * + * When one argument is provided, and it's a regular expression, `.throw` + * invokes the target function and asserts that an error is thrown with a + * message that matches that regular expression. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(/salmon/); + * + * When two arguments are provided, and the first is an error instance or + * constructor, and the second is a string or regular expression, `.throw` + * invokes the function and asserts that an error is thrown that fulfills both + * conditions as described above. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); + * expect(badFn).to.throw(TypeError, /salmon/); + * expect(badFn).to.throw(err, 'salmon'); + * expect(badFn).to.throw(err, /salmon/); + * + * Add `.not` earlier in the chain to negate `.throw`. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); + * + * However, it's dangerous to negate `.throw` when providing any arguments. + * The problem is that it creates uncertain expectations by asserting that the + * target either doesn't throw an error, or that it throws an error but of a + * different type than the given type, or that it throws an error of the given + * type but with a message that doesn't include the given string. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to throw an error, it's often best to assert + * exactly that. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); // Recommended + * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * When the target is expected to throw an error, it's often best to assert + * that the error is of its expected type, and has a message that includes an + * expected string, rather than asserting that it doesn't have one of many + * unexpected types, and doesn't have a message that includes some string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended + * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * `.throw` changes the target of any assertions that follow in the chain to + * be the error object that's thrown. + * + * var err = new TypeError('Illegal salmon!'); + * err.code = 42; + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError).with.property('code', 42); + * + * `.throw` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. When not providing two arguments, always use + * the second form. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); + * expect(goodFn, 'nooo why fail??').to.throw(); + * + * Due to limitations in ES5, `.throw` may not always work as expected when + * using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing the built-in `Error` object and + * then passing the subclassed constructor to `.throw`. See your transpiler's + * docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * Beware of some common mistakes when using the `throw` assertion. One common + * mistake is to accidentally invoke the function yourself instead of letting + * the `throw` assertion invoke the function for you. For example, when + * testing if a function named `fn` throws, provide `fn` instead of `fn()` as + * the target for the assertion. + * + * expect(fn).to.throw(); // Good! Tests `fn` as desired + * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` + * + * If you need to assert that your function `fn` throws when passed certain + * arguments, then wrap a call to `fn` inside of another function. + * + * expect(function () { fn(42); }).to.throw(); // Function expression + * expect(() => fn(42)).to.throw(); // ES6 arrow function + * + * Another common mistake is to provide an object method (or any stand-alone + * function that relies on `this`) as the target of the assertion. Doing so is + * problematic because the `this` context will be lost when the function is + * invoked by `.throw`; there's no way for it to know what `this` is supposed + * to be. There are two ways around this problem. One solution is to wrap the + * method or function call inside of another function. Another solution is to + * use `bind`. + * + * expect(function () { cat.meow(); }).to.throw(); // Function expression + * expect(() => cat.meow()).to.throw(); // ES6 arrow function + * expect(cat.meow.bind(cat)).to.throw(); // Bind + * + * Finally, it's worth mentioning that it's a best practice in JavaScript to + * only throw `Error` and derivatives of `Error` such as `ReferenceError`, + * `TypeError`, and user-defined objects that extend `Error`. No other type of + * value will generate a stack trace when initialized. With that said, the + * `throw` assertion does technically support any type of value being thrown, + * not just `Error` and its derivatives. + * + * The aliases `.throws` and `.Throw` can be used interchangeably with + * `.throw`. + * + * @name throw + * @alias throws + * @alias Throw + * @param {Error|ErrorConstructor} errorLike + * @param {String|RegExp} errMsgMatcher error message + * @param {String} msg _optional_ + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @returns error for chaining (null if no error) + * @namespace BDD + * @api public + */ + + function assertThrows (errorLike, errMsgMatcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') || false; + new Assertion(obj, flagMsg, ssfi, true).is.a('function'); + + if (errorLike instanceof RegExp || typeof errorLike === 'string') { + errMsgMatcher = errorLike; + errorLike = null; + } + + var caughtErr; + try { + obj(); + } catch (err) { + caughtErr = err; + } + + // If we have the negate flag enabled and at least one valid argument it means we do expect an error + // but we want it to match a given set of criteria + var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; + + // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible + // See Issue #551 and PR #683@GitHub + var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + var errorLikeFail = false; + var errMsgMatcherFail = false; + + // Checking if error was thrown + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + // We need this to display results correctly according to their types + var errorLikeString = 'an error'; + if (errorLike instanceof Error) { + errorLikeString = '#{exp}'; + } else if (errorLike) { + errorLikeString = _.checkError.getConstructorName(errorLike); + } + + this.assert( + caughtErr + , 'expected #{this} to throw ' + errorLikeString + , 'expected #{this} to not throw an error but #{act} was thrown' + , errorLike && errorLike.toString() + , (caughtErr instanceof Error ? + caughtErr.toString() : (typeof caughtErr === 'string' ? caughtErr : caughtErr && + _.checkError.getConstructorName(caughtErr))) + ); + } + + if (errorLike && caughtErr) { + // We should compare instances only if `errorLike` is an instance of `Error` + if (errorLike instanceof Error) { + var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); + + if (isCompatibleInstance === negate) { + // These checks were created to ensure we won't fail too soon when we've got both args and a negate + // See Issue #551 and PR #683@GitHub + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') + , errorLike.toString() + , caughtErr.toString() + ); + } + } + } + + var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + } + } + + if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { + // Here we check compatible messages + var placeholder = 'including'; + if (errMsgMatcher instanceof RegExp) { + placeholder = 'matching' + } + + var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' + , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' + , errMsgMatcher + , _.checkError.getMessage(caughtErr) + ); + } + } + } + + // If both assertions failed and both should've matched we throw an error + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + + flag(this, 'object', caughtErr); + }; + + Assertion.addMethod('throw', assertThrows); + Assertion.addMethod('throws', assertThrows); + Assertion.addMethod('Throw', assertThrows); + + /** + * ### .respondTo(method[, msg]) + * + * When the target is a non-function object, `.respondTo` asserts that the + * target has a method with the given name `method`. The method can be own or + * inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.respondTo('meow'); + * + * When the target is a function, `.respondTo` asserts that the target's + * `prototype` property has a method with the given name `method`. Again, the + * method can be own or inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(Cat).to.respondTo('meow'); + * + * Add `.itself` earlier in the chain to force `.respondTo` to treat the + * target as a non-function object, even if it's a function. Thus, it asserts + * that the target has a method with the given name `method`, rather than + * asserting that the target's `prototype` property has a method with the + * given name `method`. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * When not adding `.itself`, it's important to check the target's type before + * using `.respondTo`. See the `.a` doc for info on checking a target's type. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); + * + * Add `.not` earlier in the chain to negate `.respondTo`. + * + * function Dog () {} + * Dog.prototype.bark = function () {}; + * + * expect(new Dog()).to.not.respondTo('meow'); + * + * `.respondTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect({}).to.respondTo('meow', 'nooo why fail??'); + * expect({}, 'nooo why fail??').to.respondTo('meow'); + * + * The alias `.respondsTo` can be used interchangeably with `.respondTo`. + * + * @name respondTo + * @alias respondsTo + * @param {String} method + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function respondTo (method, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , itself = flag(this, 'itself') + , context = ('function' === typeof obj && !itself) + ? obj.prototype[method] + : obj[method]; + + this.assert( + 'function' === typeof context + , 'expected #{this} to respond to ' + _.inspect(method) + , 'expected #{this} to not respond to ' + _.inspect(method) + ); + } + + Assertion.addMethod('respondTo', respondTo); + Assertion.addMethod('respondsTo', respondTo); + + /** + * ### .itself + * + * Forces all `.respondTo` assertions that follow in the chain to behave as if + * the target is a non-function object, even if it's a function. Thus, it + * causes `.respondTo` to assert that the target has a method with the given + * name, rather than asserting that the target's `prototype` property has a + * method with the given name. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * @name itself + * @namespace BDD + * @api public + */ + + Assertion.addProperty('itself', function () { + flag(this, 'itself', true); + }); + + /** + * ### .satisfy(matcher[, msg]) + * + * Invokes the given `matcher` function with the target being passed as the + * first argument, and asserts that the value returned is truthy. + * + * expect(1).to.satisfy(function(num) { + * return num > 0; + * }); + * + * Add `.not` earlier in the chain to negate `.satisfy`. + * + * expect(1).to.not.satisfy(function(num) { + * return num > 2; + * }); + * + * `.satisfy` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.satisfy(function(num) { + * return num > 2; + * }, 'nooo why fail??'); + * + * expect(1, 'nooo why fail??').to.satisfy(function(num) { + * return num > 2; + * }); + * + * The alias `.satisfies` can be used interchangeably with `.satisfy`. + * + * @name satisfy + * @alias satisfies + * @param {Function} matcher + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function satisfy (matcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var result = matcher(obj); + this.assert( + result + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) + , flag(this, 'negate') ? false : true + , result + ); + } + + Assertion.addMethod('satisfy', satisfy); + Assertion.addMethod('satisfies', satisfy); + + /** + * ### .closeTo(expected, delta[, msg]) + * + * Asserts that the target is a number that's within a given +/- `delta` range + * of the given number `expected`. However, it's often best to assert that the + * target is equal to its expected value. + * + * // Recommended + * expect(1.5).to.equal(1.5); + * + * // Not recommended + * expect(1.5).to.be.closeTo(1, 0.5); + * expect(1.5).to.be.closeTo(2, 0.5); + * expect(1.5).to.be.closeTo(1, 1); + * + * Add `.not` earlier in the chain to negate `.closeTo`. + * + * expect(1.5).to.equal(1.5); // Recommended + * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended + * + * `.closeTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); + * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); + * + * The alias `.approximately` can be used interchangeably with `.closeTo`. + * + * @name closeTo + * @alias approximately + * @param {Number} expected + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function closeTo(expected, delta, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).is.a('number'); + if (typeof expected !== 'number' || typeof delta !== 'number') { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var deltaMessage = delta === undefined ? ", and a delta is required" : ""; + throw new AssertionError( + flagMsg + 'the arguments to closeTo or approximately must be numbers' + deltaMessage, + undefined, + ssfi + ); + } + + this.assert( + Math.abs(obj - expected) <= delta + , 'expected #{this} to be close to ' + expected + ' +/- ' + delta + , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta + ); + } + + Assertion.addMethod('closeTo', closeTo); + Assertion.addMethod('approximately', closeTo); + + // Note: Duplicates are ignored if testing for inclusion instead of sameness. + function isSubsetOf(subset, superset, cmp, contains, ordered) { + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + + if (!cmp) { + var matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + } + + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); + } + + /** + * ### .members(set[, msg]) + * + * Asserts that the target array has the same members as the given array + * `set`. + * + * expect([1, 2, 3]).to.have.members([2, 1, 3]); + * expect([1, 2, 2]).to.have.members([2, 1, 2]); + * + * By default, members are compared using strict (`===`) equality. Add `.deep` + * earlier in the chain to use deep equality instead. See the `deep-eql` + * project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * By default, order doesn't matter. Add `.ordered` earlier in the chain to + * require that members appear in the same order. + * + * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); + * expect([1, 2, 3]).to.have.members([2, 1, 3]) + * .but.not.ordered.members([2, 1, 3]); + * + * By default, both arrays must be the same size. Add `.include` earlier in + * the chain to require that the target's members be a superset of the + * expected members. Note that duplicates are ignored in the subset when + * `.include` is added. + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * `.deep`, `.ordered`, and `.include` can all be combined. However, if + * `.include` and `.ordered` are combined, the ordering begins at the start of + * both arrays. + * + * expect([{a: 1}, {b: 2}, {c: 3}]) + * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) + * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); + * + * Add `.not` earlier in the chain to negate `.members`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the target array doesn't have all of the same members as + * the given array `set` but may or may not have some of them. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended + * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended + * + * `.members` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); + * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); + * + * @name members + * @param {Array} set + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('members', function (subset, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).to.be.an('array'); + new Assertion(subset, flagMsg, ssfi, true).to.be.an('array'); + + var contains = flag(this, 'contains'); + var ordered = flag(this, 'ordered'); + + var subject, failMsg, failNegateMsg; + + if (contains) { + subject = ordered ? 'an ordered superset' : 'a superset'; + failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; + failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; + } else { + subject = ordered ? 'ordered members' : 'members'; + failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; + failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; + } + + var cmp = flag(this, 'deep') ? flag(this, 'eql') : undefined; + + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered) + , failMsg + , failNegateMsg + , subset + , obj + , true + ); + }); + + /** + * ### .oneOf(list[, msg]) + * + * Asserts that the target is a member of the given array `list`. However, + * it's often best to assert that the target is equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended + * + * Comparisons are performed using strict (`===`) equality. + * + * Add `.not` earlier in the chain to negate `.oneOf`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended + * + * It can also be chained with `.contain` or `.include`, which will work with + * both arrays and strings: + * + * expect('Today is sunny').to.contain.oneOf(['sunny', 'cloudy']) + * expect('Today is rainy').to.not.contain.oneOf(['sunny', 'cloudy']) + * expect([1,2,3]).to.contain.oneOf([3,4,5]) + * expect([1,2,3]).to.not.contain.oneOf([4,5,6]) + * + * `.oneOf` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); + * + * @name oneOf + * @param {Array<*>} list + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function oneOf (list, msg) { + if (msg) flag(this, 'message', msg); + var expected = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , contains = flag(this, 'contains') + , isDeep = flag(this, 'deep') + , eql = flag(this, 'eql'); + new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); + + if (contains) { + this.assert( + list.some(function(possibility) { return expected.indexOf(possibility) > -1 }) + , 'expected #{this} to contain one of #{exp}' + , 'expected #{this} to not contain one of #{exp}' + , list + , expected + ); + } else { + if (isDeep) { + this.assert( + list.some(function(possibility) { return eql(expected, possibility) }) + , 'expected #{this} to deeply equal one of #{exp}' + , 'expected #{this} to deeply equal one of #{exp}' + , list + , expected + ); + } else { + this.assert( + list.indexOf(expected) > -1 + , 'expected #{this} to be one of #{exp}' + , 'expected #{this} to not be one of #{exp}' + , list + , expected + ); + } + } + } + + Assertion.addMethod('oneOf', oneOf); + + /** + * ### .change(subject[, prop[, msg]]) + * + * When one argument is provided, `.change` asserts that the given function + * `subject` returns a different value when it's invoked before the target + * function compared to when it's invoked afterward. However, it's often best + * to assert that `subject` is equal to its expected value. + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * // Recommended + * expect(getDots()).to.equal(''); + * addDot(); + * expect(getDots()).to.equal('.'); + * + * // Not recommended + * expect(addDot).to.change(getDots); + * + * When two arguments are provided, `.change` asserts that the value of the + * given object `subject`'s `prop` property is different before invoking the + * target function compared to afterward. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * // Recommended + * expect(myObj).to.have.property('dots', ''); + * addDot(); + * expect(myObj).to.have.property('dots', '.'); + * + * // Not recommended + * expect(addDot).to.change(myObj, 'dots'); + * + * Strict (`===`) equality is used to compare before and after values. + * + * Add `.not` earlier in the chain to negate `.change`. + * + * var dots = '' + * , noop = function () {} + * , getDots = function () { return dots; }; + * + * expect(noop).to.not.change(getDots); + * + * var myObj = {dots: ''} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'dots'); + * + * `.change` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * expect(addDot, 'nooo why fail??').to.not.change(getDots); + * + * `.change` also causes all `.by` assertions that follow in the chain to + * assert how much a numeric subject was increased or decreased by. However, + * it's dangerous to use `.change.by`. The problem is that it creates + * uncertain expectations by asserting that the subject either increases by + * the given delta, or that it decreases by the given delta. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * The alias `.changes` can be used interchangeably with `.change`. + * + * @name change + * @alias changes + * @param {String} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertChanges (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + // This gets flagged because of the .by(delta) assertion + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'change'); + flag(this, 'realDelta', final !== initial); + + this.assert( + initial !== final + , 'expected ' + msgObj + ' to change' + , 'expected ' + msgObj + ' to not change' + ); + } + + Assertion.addMethod('change', assertChanges); + Assertion.addMethod('changes', assertChanges); + + /** + * ### .increase(subject[, prop[, msg]]) + * + * When one argument is provided, `.increase` asserts that the given function + * `subject` returns a greater number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.increase` also + * causes all `.by` assertions that follow in the chain to assert how much + * greater of a number is returned. It's often best to assert that the return + * value increased by the expected amount, rather than asserting it increased + * by any amount. + * + * var val = 1 + * , addTwo = function () { val += 2; } + * , getVal = function () { return val; }; + * + * expect(addTwo).to.increase(getVal).by(2); // Recommended + * expect(addTwo).to.increase(getVal); // Not recommended + * + * When two arguments are provided, `.increase` asserts that the value of the + * given object `subject`'s `prop` property is greater after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.increase(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.increase`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either decreases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to decrease, it's often best to assert that it + * decreased by the expected amount. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.increase(myObj, 'val'); // Not recommended + * + * `.increase` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.increase(getVal); + * + * The alias `.increases` can be used interchangeably with `.increase`. + * + * @name increase + * @alias increases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertIncreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'increase'); + flag(this, 'realDelta', final - initial); + + this.assert( + final - initial > 0 + , 'expected ' + msgObj + ' to increase' + , 'expected ' + msgObj + ' to not increase' + ); + } + + Assertion.addMethod('increase', assertIncreases); + Assertion.addMethod('increases', assertIncreases); + + /** + * ### .decrease(subject[, prop[, msg]]) + * + * When one argument is provided, `.decrease` asserts that the given function + * `subject` returns a lesser number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.decrease` also + * causes all `.by` assertions that follow in the chain to assert how much + * lesser of a number is returned. It's often best to assert that the return + * value decreased by the expected amount, rather than asserting it decreased + * by any amount. + * + * var val = 1 + * , subtractTwo = function () { val -= 2; } + * , getVal = function () { return val; }; + * + * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended + * expect(subtractTwo).to.decrease(getVal); // Not recommended + * + * When two arguments are provided, `.decrease` asserts that the value of the + * given object `subject`'s `prop` property is lesser after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.decrease`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either increases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to increase, it's often best to assert that it + * increased by the expected amount. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended + * + * `.decrease` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.decrease(getVal); + * + * The alias `.decreases` can be used interchangeably with `.decrease`. + * + * @name decrease + * @alias decreases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDecreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'decrease'); + flag(this, 'realDelta', initial - final); + + this.assert( + final - initial < 0 + , 'expected ' + msgObj + ' to decrease' + , 'expected ' + msgObj + ' to not decrease' + ); + } + + Assertion.addMethod('decrease', assertDecreases); + Assertion.addMethod('decreases', assertDecreases); + + /** + * ### .by(delta[, msg]) + * + * When following an `.increase` assertion in the chain, `.by` asserts that + * the subject of the `.increase` assertion increased by the given `delta`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * When following a `.decrease` assertion in the chain, `.by` asserts that the + * subject of the `.decrease` assertion decreased by the given `delta`. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); + * + * When following a `.change` assertion in the chain, `.by` asserts that the + * subject of the `.change` assertion either increased or decreased by the + * given `delta`. However, it's dangerous to use `.change.by`. The problem is + * that it creates uncertain expectations. It's often best to identify the + * exact output that's expected, and then write an assertion that only accepts + * that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.by`. However, it's often best + * to assert that the subject changed by its expected delta, rather than + * asserting that it didn't change by one of countless unexpected deltas. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * // Recommended + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * // Not recommended + * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); + * + * `.by` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); + * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); + * + * @name by + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDelta(delta, msg) { + if (msg) flag(this, 'message', msg); + + var msgObj = flag(this, 'deltaMsgObj'); + var initial = flag(this, 'initialDeltaValue'); + var final = flag(this, 'finalDeltaValue'); + var behavior = flag(this, 'deltaBehavior'); + var realDelta = flag(this, 'realDelta'); + + var expression; + if (behavior === 'change') { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + + this.assert( + expression + , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta + , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta + ); + } + + Assertion.addMethod('by', assertDelta); + + /** + * ### .extensible + * + * Asserts that the target is extensible, which means that new properties can + * be added to it. Primitives are never extensible. + * + * expect({a: 1}).to.be.extensible; + * + * Add `.not` earlier in the chain to negate `.extensible`. + * + * var nonExtensibleObject = Object.preventExtensions({}) + * , sealedObject = Object.seal({}) + * , frozenObject = Object.freeze({}); + * + * expect(nonExtensibleObject).to.not.be.extensible; + * expect(sealedObject).to.not.be.extensible; + * expect(frozenObject).to.not.be.extensible; + * expect(1).to.not.be.extensible; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(1, 'nooo why fail??').to.be.extensible; + * + * @name extensible + * @namespace BDD + * @api public + */ + + Assertion.addProperty('extensible', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible + // The following provides ES6 behavior for ES5 environments. + + var isExtensible = obj === Object(obj) && Object.isExtensible(obj); + + this.assert( + isExtensible + , 'expected #{this} to be extensible' + , 'expected #{this} to not be extensible' + ); + }); + + /** + * ### .sealed + * + * Asserts that the target is sealed, which means that new properties can't be + * added to it, and its existing properties can't be reconfigured or deleted. + * However, it's possible that its existing properties can still be reassigned + * to different values. Primitives are always sealed. + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect(sealedObject).to.be.sealed; + * expect(frozenObject).to.be.sealed; + * expect(1).to.be.sealed; + * + * Add `.not` earlier in the chain to negate `.sealed`. + * + * expect({a: 1}).to.not.be.sealed; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.sealed; + * + * @name sealed + * @namespace BDD + * @api public + */ + + Assertion.addProperty('sealed', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed + // The following provides ES6 behavior for ES5 environments. + + var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + + this.assert( + isSealed + , 'expected #{this} to be sealed' + , 'expected #{this} to not be sealed' + ); + }); + + /** + * ### .frozen + * + * Asserts that the target is frozen, which means that new properties can't be + * added to it, and its existing properties can't be reassigned to different + * values, reconfigured, or deleted. Primitives are always frozen. + * + * var frozenObject = Object.freeze({}); + * + * expect(frozenObject).to.be.frozen; + * expect(1).to.be.frozen; + * + * Add `.not` earlier in the chain to negate `.frozen`. + * + * expect({a: 1}).to.not.be.frozen; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.frozen; + * + * @name frozen + * @namespace BDD + * @api public + */ + + Assertion.addProperty('frozen', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen + // The following provides ES6 behavior for ES5 environments. + + var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + + this.assert( + isFrozen + , 'expected #{this} to be frozen' + , 'expected #{this} to not be frozen' + ); + }); + + /** + * ### .finite + * + * Asserts that the target is a number, and isn't `NaN` or positive/negative + * `Infinity`. + * + * expect(1).to.be.finite; + * + * Add `.not` earlier in the chain to negate `.finite`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either isn't a number, or that it's `NaN`, or + * that it's positive `Infinity`, or that it's negative `Infinity`. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to be a number, it's often best to assert + * that it's the expected type, rather than asserting that it isn't one of + * many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.finite; // Not recommended + * + * When the target is expected to be `NaN`, it's often best to assert exactly + * that. + * + * expect(NaN).to.be.NaN; // Recommended + * expect(NaN).to.not.be.finite; // Not recommended + * + * When the target is expected to be positive infinity, it's often best to + * assert exactly that. + * + * expect(Infinity).to.equal(Infinity); // Recommended + * expect(Infinity).to.not.be.finite; // Not recommended + * + * When the target is expected to be negative infinity, it's often best to + * assert exactly that. + * + * expect(-Infinity).to.equal(-Infinity); // Recommended + * expect(-Infinity).to.not.be.finite; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect('foo', 'nooo why fail??').to.be.finite; + * + * @name finite + * @namespace BDD + * @api public + */ + + Assertion.addProperty('finite', function(msg) { + var obj = flag(this, 'object'); + + this.assert( + typeof obj === 'number' && isFinite(obj) + , 'expected #{this} to be a finite number' + , 'expected #{this} to not be a finite number' + ); + }); +}; + +},{}],6:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + /*! + * Chai dependencies. + */ + + var Assertion = chai.Assertion + , flag = util.flag; + + /*! + * Module export. + */ + + /** + * ### assert(expression, message) + * + * Write your own test expressions. + * + * assert('foo' !== 'bar', 'foo is not bar'); + * assert(Array.isArray([]), 'empty arrays are arrays'); + * + * @param {Mixed} expression to test for truthiness + * @param {String} message to display on error + * @name assert + * @namespace Assert + * @api public + */ + + var assert = chai.assert = function (express, errmsg) { + var test = new Assertion(null, null, chai.assert, true); + test.assert( + express + , errmsg + , '[ negation message unavailable ]' + ); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. Node.js `assert` module-compatible. + * + * assert.fail(); + * assert.fail("custom error message"); + * assert.fail(1, 2); + * assert.fail(1, 2, "custom error message"); + * assert.fail(1, 2, "custom error message", ">"); + * assert.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Assert + * @api public + */ + + assert.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + // Comply with Node's fail([message]) interface + + message = actual; + actual = undefined; + } + + message = message || 'assert.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, assert.fail); + }; + + /** + * ### .isOk(object, [message]) + * + * Asserts that `object` is truthy. + * + * assert.isOk('everything', 'everything is ok'); + * assert.isOk(false, 'this will fail'); + * + * @name isOk + * @alias ok + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isOk = function (val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; + }; + + /** + * ### .isNotOk(object, [message]) + * + * Asserts that `object` is falsy. + * + * assert.isNotOk('everything', 'this will fail'); + * assert.isNotOk(false, 'this will pass'); + * + * @name isNotOk + * @alias notOk + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotOk = function (val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * assert.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.equal = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.equal, true); + + test.assert( + exp == flag(test, 'object') + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .notEqual(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * assert.notEqual(3, 4, 'these numbers are not equal'); + * + * @name notEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notEqual = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.notEqual, true); + + test.assert( + exp != flag(test, 'object') + , 'expected #{this} to not equal #{exp}' + , 'expected #{this} to equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .strictEqual(actual, expected, [message]) + * + * Asserts strict equality (`===`) of `actual` and `expected`. + * + * assert.strictEqual(true, true, 'these booleans are strictly equal'); + * + * @name strictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.strictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); + }; + + /** + * ### .notStrictEqual(actual, expected, [message]) + * + * Asserts strict inequality (`!==`) of `actual` and `expected`. + * + * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); + * + * @name notStrictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); + }; + + /** + * ### .deepEqual(actual, expected, [message]) + * + * Asserts that `actual` is deeply equal to `expected`. + * + * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); + * + * @name deepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @alias deepStrictEqual + * @namespace Assert + * @api public + */ + + assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); + }; + + /** + * ### .notDeepEqual(actual, expected, [message]) + * + * Assert that `actual` is not deeply equal to `expected`. + * + * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); + * + * @name notDeepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); + }; + + /** + * ### .isAbove(valueToCheck, valueToBeAbove, [message]) + * + * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. + * + * assert.isAbove(5, 2, '5 is strictly greater than 2'); + * + * @name isAbove + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAbove + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAbove = function (val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); + }; + + /** + * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) + * + * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. + * + * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); + * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); + * + * @name isAtLeast + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtLeast + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtLeast = function (val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); + }; + + /** + * ### .isBelow(valueToCheck, valueToBeBelow, [message]) + * + * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. + * + * assert.isBelow(3, 6, '3 is strictly less than 6'); + * + * @name isBelow + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeBelow + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBelow = function (val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); + }; + + /** + * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) + * + * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. + * + * assert.isAtMost(3, 6, '3 is less than or equal to 6'); + * assert.isAtMost(4, 4, '4 is less than or equal to 4'); + * + * @name isAtMost + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtMost + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtMost = function (val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); + }; + + /** + * ### .isTrue(value, [message]) + * + * Asserts that `value` is true. + * + * var teaServed = true; + * assert.isTrue(teaServed, 'the tea has been served'); + * + * @name isTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isTrue = function (val, msg) { + new Assertion(val, msg, assert.isTrue, true).is['true']; + }; + + /** + * ### .isNotTrue(value, [message]) + * + * Asserts that `value` is not true. + * + * var tea = 'tasty chai'; + * assert.isNotTrue(tea, 'great, time for tea!'); + * + * @name isNotTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotTrue = function (val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); + }; + + /** + * ### .isFalse(value, [message]) + * + * Asserts that `value` is false. + * + * var teaServed = false; + * assert.isFalse(teaServed, 'no tea yet? hmm...'); + * + * @name isFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFalse = function (val, msg) { + new Assertion(val, msg, assert.isFalse, true).is['false']; + }; + + /** + * ### .isNotFalse(value, [message]) + * + * Asserts that `value` is not false. + * + * var tea = 'tasty chai'; + * assert.isNotFalse(tea, 'great, time for tea!'); + * + * @name isNotFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFalse = function (val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); + }; + + /** + * ### .isNull(value, [message]) + * + * Asserts that `value` is null. + * + * assert.isNull(err, 'there was no error'); + * + * @name isNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNull = function (val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); + }; + + /** + * ### .isNotNull(value, [message]) + * + * Asserts that `value` is not null. + * + * var tea = 'tasty chai'; + * assert.isNotNull(tea, 'great, time for tea!'); + * + * @name isNotNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNull = function (val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); + }; + + /** + * ### .isNaN + * + * Asserts that value is NaN. + * + * assert.isNaN(NaN, 'NaN is NaN'); + * + * @name isNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNaN = function (val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; + }; + + /** + * ### .isNotNaN + * + * Asserts that value is not NaN. + * + * assert.isNotNaN(4, '4 is not NaN'); + * + * @name isNotNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + assert.isNotNaN = function (val, msg) { + new Assertion(val, msg, assert.isNotNaN, true).not.to.be.NaN; + }; + + /** + * ### .exists + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * assert.exists(foo, 'foo is neither `null` nor `undefined`'); + * + * @name exists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.exists = function (val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; + }; + + /** + * ### .notExists + * + * Asserts that the target is either `null` or `undefined`. + * + * var bar = null + * , baz; + * + * assert.notExists(bar); + * assert.notExists(baz, 'baz is either null or undefined'); + * + * @name notExists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notExists = function (val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; + }; + + /** + * ### .isUndefined(value, [message]) + * + * Asserts that `value` is `undefined`. + * + * var tea; + * assert.isUndefined(tea, 'no tea defined'); + * + * @name isUndefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isUndefined = function (val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); + }; + + /** + * ### .isDefined(value, [message]) + * + * Asserts that `value` is not `undefined`. + * + * var tea = 'cup of chai'; + * assert.isDefined(tea, 'tea has been defined'); + * + * @name isDefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isDefined = function (val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); + }; + + /** + * ### .isFunction(value, [message]) + * + * Asserts that `value` is a function. + * + * function serveTea() { return 'cup of tea'; }; + * assert.isFunction(serveTea, 'great, we can have tea now'); + * + * @name isFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFunction = function (val, msg) { + new Assertion(val, msg, assert.isFunction, true).to.be.a('function'); + }; + + /** + * ### .isNotFunction(value, [message]) + * + * Asserts that `value` is _not_ a function. + * + * var serveTea = [ 'heat', 'pour', 'sip' ]; + * assert.isNotFunction(serveTea, 'great, we have listed the steps'); + * + * @name isNotFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFunction = function (val, msg) { + new Assertion(val, msg, assert.isNotFunction, true).to.not.be.a('function'); + }; + + /** + * ### .isObject(value, [message]) + * + * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). + * _The assertion does not match subclassed objects._ + * + * var selection = { name: 'Chai', serve: 'with spices' }; + * assert.isObject(selection, 'tea selection is an object'); + * + * @name isObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isObject = function (val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a('object'); + }; + + /** + * ### .isNotObject(value, [message]) + * + * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). + * + * var selection = 'chai' + * assert.isNotObject(selection, 'tea selection is not an object'); + * assert.isNotObject(null, 'null is not an object'); + * + * @name isNotObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotObject = function (val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); + }; + + /** + * ### .isArray(value, [message]) + * + * Asserts that `value` is an array. + * + * var menu = [ 'green', 'chai', 'oolong' ]; + * assert.isArray(menu, 'what kind of tea do we want?'); + * + * @name isArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isArray = function (val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an('array'); + }; + + /** + * ### .isNotArray(value, [message]) + * + * Asserts that `value` is _not_ an array. + * + * var menu = 'green|chai|oolong'; + * assert.isNotArray(menu, 'what kind of tea do we want?'); + * + * @name isNotArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotArray = function (val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); + }; + + /** + * ### .isString(value, [message]) + * + * Asserts that `value` is a string. + * + * var teaOrder = 'chai'; + * assert.isString(teaOrder, 'order placed'); + * + * @name isString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isString = function (val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a('string'); + }; + + /** + * ### .isNotString(value, [message]) + * + * Asserts that `value` is _not_ a string. + * + * var teaOrder = 4; + * assert.isNotString(teaOrder, 'order placed'); + * + * @name isNotString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotString = function (val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); + }; + + /** + * ### .isNumber(value, [message]) + * + * Asserts that `value` is a number. + * + * var cups = 2; + * assert.isNumber(cups, 'how many cups'); + * + * @name isNumber + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNumber = function (val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); + }; + + /** + * ### .isNotNumber(value, [message]) + * + * Asserts that `value` is _not_ a number. + * + * var cups = '2 cups please'; + * assert.isNotNumber(cups, 'how many cups'); + * + * @name isNotNumber + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNumber = function (val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); + }; + + /** + * ### .isFinite(value, [message]) + * + * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * var cups = 2; + * assert.isFinite(cups, 'how many cups'); + * + * assert.isFinite(NaN); // throws + * + * @name isFinite + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFinite = function (val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; + }; + + /** + * ### .isBoolean(value, [message]) + * + * Asserts that `value` is a boolean. + * + * var teaReady = true + * , teaServed = false; + * + * assert.isBoolean(teaReady, 'is the tea ready'); + * assert.isBoolean(teaServed, 'has tea been served'); + * + * @name isBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBoolean = function (val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); + }; + + /** + * ### .isNotBoolean(value, [message]) + * + * Asserts that `value` is _not_ a boolean. + * + * var teaReady = 'yep' + * , teaServed = 'nope'; + * + * assert.isNotBoolean(teaReady, 'is the tea ready'); + * assert.isNotBoolean(teaServed, 'has tea been served'); + * + * @name isNotBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotBoolean = function (val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); + }; + + /** + * ### .typeOf(value, name, [message]) + * + * Asserts that `value`'s type is `name`, as determined by + * `Object.prototype.toString`. + * + * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); + * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); + * assert.typeOf('tea', 'string', 'we have a string'); + * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); + * assert.typeOf(null, 'null', 'we have a null'); + * assert.typeOf(undefined, 'undefined', 'we have an undefined'); + * + * @name typeOf + * @param {Mixed} value + * @param {String} name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.typeOf = function (val, type, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type); + }; + + /** + * ### .notTypeOf(value, name, [message]) + * + * Asserts that `value`'s type is _not_ `name`, as determined by + * `Object.prototype.toString`. + * + * assert.notTypeOf('tea', 'number', 'strings are not numbers'); + * + * @name notTypeOf + * @param {Mixed} value + * @param {String} typeof name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notTypeOf = function (val, type, msg) { + new Assertion(val, msg, assert.notTypeOf, true).to.not.be.a(type); + }; + + /** + * ### .instanceOf(object, constructor, [message]) + * + * Asserts that `value` is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new Tea('chai'); + * + * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); + * + * @name instanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.instanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); + }; + + /** + * ### .notInstanceOf(object, constructor, [message]) + * + * Asserts `value` is not an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new String('chai'); + * + * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); + * + * @name notInstanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInstanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.notInstanceOf, true) + .to.not.be.instanceOf(type); + }; + + /** + * ### .include(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.include([1,2,3], 2, 'array contains value'); + * assert.include('foobar', 'foo', 'string contains substring'); + * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); + * + * Strict equality (===) is used. When asserting the inclusion of a value in + * an array, the array is searched for an element that's strictly equal to the + * given value. When asserting a subset of properties in an object, the object + * is searched for the given property keys, checking that each one is present + * and strictly equal to the given property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.include([obj1, obj2], obj1); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); + * + * @name include + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.include = function (exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); + }; + + /** + * ### .notInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.notInclude([1,2,3], 4, "array doesn't contain value"); + * assert.notInclude('foobar', 'baz', "string doesn't contain substring"); + * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); + * + * Strict equality (===) is used. When asserting the absence of a value in an + * array, the array is searched to confirm the absence of an element that's + * strictly equal to the given value. When asserting a subset of properties in + * an object, the object is searched to confirm that at least one of the given + * property keys is either not present or not strictly equal to the given + * property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notInclude([obj1, obj2], {a: 1}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); + * + * @name notInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); + }; + + /** + * ### .deepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.deepInclude([obj1, obj2], {a: 1}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); + * + * @name deepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); + }; + + /** + * ### .notDeepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notDeepInclude([obj1, obj2], {a: 9}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); + * + * @name notDeepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); + }; + + /** + * ### .nestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + * + * @name nestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); + }; + + /** + * ### .notNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + * + * @name notNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true) + .not.nested.include(inc); + }; + + /** + * ### .deepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + * + * @name deepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true) + .deep.nested.include(inc); + }; + + /** + * ### .notDeepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + * + * @name notDeepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepNestedInclude, true) + .not.deep.nested.include(inc); + }; + + /** + * ### .ownInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties. + * + * assert.ownInclude({ a: 1 }, { a: 1 }); + * + * @name ownInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); + }; + + /** + * ### .notOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties. + * + * Object.prototype.b = 2; + * + * assert.notOwnInclude({ a: 1 }, { b: 2 }); + * + * @name notOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); + }; + + /** + * ### .deepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + * + * @name deepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true) + .deep.own.include(inc); + }; + + /** + * ### .notDeepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + * + * @name notDeepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true) + .not.deep.own.include(inc); + }; + + /** + * ### .match(value, regexp, [message]) + * + * Asserts that `value` matches the regular expression `regexp`. + * + * assert.match('foobar', /^foo/, 'regexp matches'); + * + * @name match + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.match = function (exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); + }; + + /** + * ### .notMatch(value, regexp, [message]) + * + * Asserts that `value` does not match the regular expression `regexp`. + * + * assert.notMatch('foobar', /^foo/, 'regexp does not match'); + * + * @name notMatch + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notMatch = function (exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); + }; + + /** + * ### .property(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`. + * + * assert.property({ tea: { green: 'matcha' }}, 'tea'); + * assert.property({ tea: { green: 'matcha' }}, 'toString'); + * + * @name property + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.property = function (obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); + }; + + /** + * ### .notProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property`. + * + * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); + * + * @name notProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true) + .to.not.have.property(prop); + }; + + /** + * ### .propertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a strict equality check + * (===). + * + * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); + * + * @name propertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.propertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true) + .to.have.property(prop, val); + }; + + /** + * ### .notPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a strict equality check + * (===). + * + * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); + * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); + * + * @name notPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true) + .to.not.have.property(prop, val); + }; + + /** + * ### .deepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a deep equality check. + * + * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true) + .to.have.deep.property(prop, val); + }; + + /** + * ### .notDeepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a deep equality check. + * + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * + * @name notDeepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepPropertyVal, true) + .to.not.have.deep.property(prop, val); + }; + + /** + * ### .ownProperty(object, property, [message]) + * + * Asserts that `object` has a direct property named by `property`. Inherited + * properties aren't checked. + * + * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); + * + * @name ownProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.ownProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true) + .to.have.own.property(prop); + }; + + /** + * ### .notOwnProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct property named by + * `property`. Inherited properties aren't checked. + * + * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); + * assert.notOwnProperty({}, 'toString'); + * + * @name notOwnProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.notOwnProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true) + .to.not.have.own.property(prop); + }; + + /** + * ### .ownPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a strict equality check (===). + * Inherited properties aren't checked. + * + * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); + * + * @name ownPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.ownPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true) + .to.have.own.property(prop, value); + }; + + /** + * ### .notOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a strict equality check + * (===). Inherited properties aren't checked. + * + * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); + * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notOwnPropertyVal, true) + .to.not.have.own.property(prop, value); + }; + + /** + * ### .deepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a deep equality check. Inherited + * properties aren't checked. + * + * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.deepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.deepOwnPropertyVal, true) + .to.have.deep.own.property(prop, value); + }; + + /** + * ### .notDeepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a deep equality check. + * Inherited properties aren't checked. + * + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notDeepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) + .to.not.have.deep.own.property(prop, value); + }; + + /** + * ### .nestedProperty(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`, which can be a string using dot- and bracket-notation for + * nested reference. + * + * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); + * + * @name nestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true) + .to.have.nested.property(prop); + }; + + /** + * ### .notNestedProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`, which + * can be a string using dot- and bracket-notation for nested reference. The + * property cannot exist on the object nor anywhere in its prototype chain. + * + * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); + * + * @name notNestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notNestedProperty, true) + .to.not.have.nested.property(prop); + }; + + /** + * ### .nestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a strict equality check (===). + * + * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); + * + * @name nestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.nestedPropertyVal, true) + .to.have.nested.property(prop, val); + }; + + /** + * ### .notNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a strict equality check (===). + * + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); + * + * @name notNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notNestedPropertyVal, true) + .to.not.have.nested.property(prop, val); + }; + + /** + * ### .deepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with a value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a deep equality check. + * + * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); + * + * @name deepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepNestedPropertyVal, true) + .to.have.deep.nested.property(prop, val); + }; + + /** + * ### .notDeepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a deep equality check. + * + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); + * + * @name notDeepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) + .to.not.have.deep.nested.property(prop, val); + } + + /** + * ### .lengthOf(object, length, [message]) + * + * Asserts that `object` has a `length` or `size` with the expected value. + * + * assert.lengthOf([1,2,3], 3, 'array has length of 3'); + * assert.lengthOf('foobar', 6, 'string has length of 6'); + * assert.lengthOf(new Set([1,2,3]), 3, 'set has size of 3'); + * assert.lengthOf(new Map([['a',1],['b',2],['c',3]]), 3, 'map has size of 3'); + * + * @name lengthOf + * @param {Mixed} object + * @param {Number} length + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.lengthOf = function (exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); + }; + + /** + * ### .hasAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAnyKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); + } + + /** + * ### .hasAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); + * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); + } + + /** + * ### .containsAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}]); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name containsAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true) + .to.contain.all.keys(keys); + } + + /** + * ### .doesNotHaveAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAnyKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) + .to.not.have.any.keys(keys); + } + + /** + * ### .doesNotHaveAllKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) + .to.not.have.all.keys(keys); + } + + /** + * ### .hasAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAnyDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true) + .to.have.any.deep.keys(keys); + } + + /** + * ### .hasAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true) + .to.have.all.deep.keys(keys); + } + + /** + * ### .containsAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name containsAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllDeepKeys, true) + .to.contain.all.deep.keys(keys); + } + + /** + * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAnyDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) + .to.not.have.any.deep.keys(keys); + } + + /** + * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) + .to.not.have.all.deep.keys(keys); + } + + /** + * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a + * message matching `errMsgMatcher`. + * + * assert.throws(fn, 'Error thrown must have this msg'); + * assert.throws(fn, /Error thrown must have a msg that matches this/); + * assert.throws(fn, ReferenceError); + * assert.throws(fn, errorInstance); + * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); + * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); + * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); + * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); + * + * @name throws + * @alias throw + * @alias Throw + * @param {Function} fn + * @param {ErrorConstructor|Error} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.throws = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + var assertErr = new Assertion(fn, msg, assert.throws, true) + .to.throw(errorLike, errMsgMatcher); + return flag(assertErr, 'object'); + }; + + /** + * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a + * message matching `errMsgMatcher`. + * + * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); + * assert.doesNotThrow(fn, /Any Error thrown must not match this/); + * assert.doesNotThrow(fn, Error); + * assert.doesNotThrow(fn, errorInstance); + * assert.doesNotThrow(fn, Error, 'Error must not have this message'); + * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); + * assert.doesNotThrow(fn, Error, /Error must not match this/); + * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); + * + * @name doesNotThrow + * @param {Function} fn + * @param {ErrorConstructor} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + new Assertion(fn, msg, assert.doesNotThrow, true) + .to.not.throw(errorLike, errMsgMatcher); + }; + + /** + * ### .operator(val1, operator, val2, [message]) + * + * Compares two values using `operator`. + * + * assert.operator(1, '<', 2, 'everything is ok'); + * assert.operator(1, '>', 2, 'this will fail'); + * + * @name operator + * @param {Mixed} val1 + * @param {String} operator + * @param {Mixed} val2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.operator = function (val, operator, val2, msg) { + var ok; + switch(operator) { + case '==': + ok = val == val2; + break; + case '===': + ok = val === val2; + break; + case '>': + ok = val > val2; + break; + case '>=': + ok = val >= val2; + break; + case '<': + ok = val < val2; + break; + case '<=': + ok = val <= val2; + break; + case '!=': + ok = val != val2; + break; + case '!==': + ok = val !== val2; + break; + default: + msg = msg ? msg + ': ' : msg; + throw new chai.AssertionError( + msg + 'Invalid operator "' + operator + '"', + undefined, + assert.operator + ); + } + var test = new Assertion(ok, msg, assert.operator, true); + test.assert( + true === flag(test, 'object') + , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) + , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); + }; + + /** + * ### .closeTo(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); + * + * @name closeTo + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.closeTo = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); + }; + + /** + * ### .approximately(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.approximately(1.5, 1, 0.5, 'numbers are close'); + * + * @name approximately + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.approximately = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true) + .to.be.approximately(exp, delta); + }; + + /** + * ### .sameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * strict equality check (===). + * + * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + * + * @name sameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true) + .to.have.same.members(set2); + } + + /** + * ### .notSameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a strict equality check (===). + * + * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); + * + * @name notSameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameMembers, true) + .to.not.have.same.members(set2); + } + + /** + * ### .sameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * deep equality check. + * + * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); + * + * @name sameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepMembers, true) + .to.have.same.deep.members(set2); + } + + /** + * ### .notSameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); + * + * @name notSameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepMembers, true) + .to.not.have.same.deep.members(set2); + } + + /** + * ### .sameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a strict equality check (===). + * + * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); + * + * @name sameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameOrderedMembers, true) + .to.have.same.ordered.members(set2); + } + + /** + * ### .notSameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a strict equality check (===). + * + * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); + * + * @name notSameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameOrderedMembers, true) + .to.not.have.same.ordered.members(set2); + } + + /** + * ### .sameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a deep equality check. + * + * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); + * + * @name sameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) + .to.have.same.deep.ordered.members(set2); + } + + /** + * ### .notSameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a deep equality check. + * + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); + * + * @name notSameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) + .to.not.have.same.deep.ordered.members(set2); + } + + /** + * ### .includeMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); + * + * @name includeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true) + .to.include.members(subset); + } + + /** + * ### .notIncludeMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); + * + * @name notIncludeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeMembers, true) + .to.not.include.members(subset); + } + + /** + * ### .includeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a deep + * equality check. Duplicates are ignored. + * + * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); + * + * @name includeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepMembers, true) + .to.include.deep.members(subset); + } + + /** + * ### .notIncludeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * @name notIncludeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepMembers, true) + .to.not.include.deep.members(subset); + } + + /** + * ### .includeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); + * + * @name includeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeOrderedMembers, true) + .to.include.ordered.members(subset); + } + + /** + * ### .notIncludeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); + * + * @name notIncludeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) + .to.not.include.ordered.members(subset); + } + + /** + * ### .includeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); + * + * @name includeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) + .to.include.deep.ordered.members(subset); + } + + /** + * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); + * + * @name notIncludeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) + .to.not.include.deep.ordered.members(subset); + } + + /** + * ### .oneOf(inList, list, [message]) + * + * Asserts that non-object, non-array value `inList` appears in the flat array `list`. + * + * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); + * + * @name oneOf + * @param {*} inList + * @param {Array<*>} list + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.oneOf = function (inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); + } + + /** + * ### .changes(function, object, property, [message]) + * + * Asserts that a function changes the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 22 }; + * assert.changes(fn, obj, 'val'); + * + * @name changes + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changes = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); + } + + /** + * ### .changesBy(function, object, property, delta, [message]) + * + * Asserts that a function changes the value of a property by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 2 }; + * assert.changesBy(fn, obj, 'val', 2); + * + * @name changesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesBy, true) + .to.change(obj, prop).by(delta); + } + + /** + * ### .doesNotChange(function, object, property, [message]) + * + * Asserts that a function does not change the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { console.log('foo'); }; + * assert.doesNotChange(fn, obj, 'val'); + * + * @name doesNotChange + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotChange = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotChange, true) + .to.not.change(obj, prop); + } + + /** + * ### .changesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.changesButNotBy(fn, obj, 'val', 5); + * + * @name changesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesButNotBy, true) + .to.change(obj, prop).but.not.by(delta); + } + + /** + * ### .increases(function, object, property, [message]) + * + * Asserts that a function increases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 13 }; + * assert.increases(fn, obj, 'val'); + * + * @name increases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.increases, true) + .to.increase(obj, prop); + } + + /** + * ### .increasesBy(function, object, property, delta, [message]) + * + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.increasesBy(fn, obj, 'val', 10); + * + * @name increasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesBy, true) + .to.increase(obj, prop).by(delta); + } + + /** + * ### .doesNotIncrease(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 8 }; + * assert.doesNotIncrease(fn, obj, 'val'); + * + * @name doesNotIncrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotIncrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotIncrease, true) + .to.not.increase(obj, prop); + } + + /** + * ### .increasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.increasesButNotBy(fn, obj, 'val', 10); + * + * @name increasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesButNotBy, true) + .to.increase(obj, prop).but.not.by(delta); + } + + /** + * ### .decreases(function, object, property, [message]) + * + * Asserts that a function decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreases(fn, obj, 'val'); + * + * @name decreases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.decreases, true) + .to.decrease(obj, prop); + } + + /** + * ### .decreasesBy(function, object, property, delta, [message]) + * + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val -= 5 }; + * assert.decreasesBy(fn, obj, 'val', 5); + * + * @name decreasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesBy, true) + .to.decrease(obj, prop).by(delta); + } + + /** + * ### .doesNotDecrease(function, object, property, [message]) + * + * Asserts that a function does not decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.doesNotDecrease(fn, obj, 'val'); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecrease, true) + .to.not.decrease(obj, prop); + } + + /** + * ### .doesNotDecreaseBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.doesNotDecreaseBy(fn, obj, 'val', 1); + * + * @name doesNotDecreaseBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) + .to.not.decrease(obj, prop).by(delta); + } + + /** + * ### .decreasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreasesButNotBy(fn, obj, 'val', 1); + * + * @name decreasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesButNotBy, true) + .to.decrease(obj, prop).but.not.by(delta); + } + + /*! + * ### .ifError(object) + * + * Asserts if value is not a false value, and throws if it is a true value. + * This is added to allow for chai to be a drop-in replacement for Node's + * assert class. + * + * var err = new Error('I am a custom error'); + * assert.ifError(err); // Rethrows err! + * + * @name ifError + * @param {Object} object + * @namespace Assert + * @api public + */ + + assert.ifError = function (val) { + if (val) { + throw(val); + } + }; + + /** + * ### .isExtensible(object) + * + * Asserts that `object` is extensible (can have new properties added to it). + * + * assert.isExtensible({}); + * + * @name isExtensible + * @alias extensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; + }; + + /** + * ### .isNotExtensible(object) + * + * Asserts that `object` is _not_ extensible. + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * assert.isNotExtensible(nonExtensibleObject); + * assert.isNotExtensible(sealedObject); + * assert.isNotExtensible(frozenObject); + * + * @name isNotExtensible + * @alias notExtensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; + }; + + /** + * ### .isSealed(object) + * + * Asserts that `object` is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.seal({}); + * + * assert.isSealed(sealedObject); + * assert.isSealed(frozenObject); + * + * @name isSealed + * @alias sealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; + }; + + /** + * ### .isNotSealed(object) + * + * Asserts that `object` is _not_ sealed. + * + * assert.isNotSealed({}); + * + * @name isNotSealed + * @alias notSealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; + }; + + /** + * ### .isFrozen(object) + * + * Asserts that `object` is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * assert.frozen(frozenObject); + * + * @name isFrozen + * @alias frozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; + }; + + /** + * ### .isNotFrozen(object) + * + * Asserts that `object` is _not_ frozen. + * + * assert.isNotFrozen({}); + * + * @name isNotFrozen + * @alias notFrozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; + }; + + /** + * ### .isEmpty(target) + * + * Asserts that the target does not contain any values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isEmpty([]); + * assert.isEmpty(''); + * assert.isEmpty(new Map); + * assert.isEmpty({}); + * + * @name isEmpty + * @alias empty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; + }; + + /** + * ### .isNotEmpty(target) + * + * Asserts that the target contains values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isNotEmpty([1, 2]); + * assert.isNotEmpty('34'); + * assert.isNotEmpty(new Set([5, 6])); + * assert.isNotEmpty({ key: 7 }); + * + * @name isNotEmpty + * @alias notEmpty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; + }; + + /*! + * Aliases. + */ + + (function alias(name, as){ + assert[as] = assert[name]; + return alias; + }) + ('isOk', 'ok') + ('isNotOk', 'notOk') + ('throws', 'throw') + ('throws', 'Throw') + ('isExtensible', 'extensible') + ('isNotExtensible', 'notExtensible') + ('isSealed', 'sealed') + ('isNotSealed', 'notSealed') + ('isFrozen', 'frozen') + ('isNotFrozen', 'notFrozen') + ('isEmpty', 'empty') + ('isNotEmpty', 'notEmpty'); +}; + +},{}],7:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + chai.expect = function (val, message) { + return new chai.Assertion(val, message); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * expect.fail(); + * expect.fail("custom error message"); + * expect.fail(1, 2); + * expect.fail(1, 2, "custom error message"); + * expect.fail(1, 2, "custom error message", ">"); + * expect.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + chai.expect.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'expect.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, chai.expect.fail); + }; +}; + +},{}],8:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + var Assertion = chai.Assertion; + + function loadShould () { + // explicitly define this method as function as to have it's name to include as `ssfi` + function shouldGetter() { + if (this instanceof String + || this instanceof Number + || this instanceof Boolean + || typeof Symbol === 'function' && this instanceof Symbol + || typeof BigInt === 'function' && this instanceof BigInt) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + function shouldSetter(value) { + // See https://github.com/chaijs/chai/issues/86: this makes + // `whatever.should = someValue` actually set `someValue`, which is + // especially useful for `global.should = require('chai').should()`. + // + // Note that we have to use [[DefineProperty]] instead of [[Put]] + // since otherwise we would trigger this very setter! + Object.defineProperty(this, 'should', { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } + // modify Object.prototype to have `should` + Object.defineProperty(Object.prototype, 'should', { + set: shouldSetter + , get: shouldGetter + , configurable: true + }); + + var should = {}; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * should.fail(); + * should.fail("custom error message"); + * should.fail(1, 2); + * should.fail(1, 2, "custom error message"); + * should.fail(1, 2, "custom error message", ">"); + * should.fail(1, 2, undefined, ">"); + * + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + should.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'should.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, should.fail); + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * should.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.equal(val2); + }; + + /** + * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * should.throw(fn, 'function throws a reference error'); + * should.throw(fn, /function throws a reference error/); + * should.throw(fn, ReferenceError); + * should.throw(fn, ReferenceError, 'function throws a reference error'); + * should.throw(fn, ReferenceError, /function throws a reference error/); + * + * @name throw + * @alias Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * should.exist(foo, 'foo exists'); + * + * @name exist + * @namespace Should + * @api public + */ + + should.exist = function (val, msg) { + new Assertion(val, msg).to.exist; + } + + // negation + should.not = {} + + /** + * ### .not.equal(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * should.not.equal(3, 4, 'these numbers are not equal'); + * + * @name not.equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.not.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.not.equal(val2); + }; + + /** + * ### .throw(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * should.not.throw(fn, Error, 'function does not throw'); + * + * @name not.throw + * @alias not.Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.not.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + + /** + * ### .not.exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var bar = null; + * + * should.not.exist(bar, 'bar does not exist'); + * + * @name not.exist + * @namespace Should + * @api public + */ + + should.not.exist = function (val, msg) { + new Assertion(val, msg).to.not.exist; + } + + should['throw'] = should['Throw']; + should.not['throw'] = should.not['Throw']; + + return should; + }; + + chai.should = loadShould; + chai.Should = loadShould; +}; + +},{}],9:[function(require,module,exports){ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/*! + * Module variables + */ + +// Check whether `Object.setPrototypeOf` is supported +var canSetPrototype = typeof Object.setPrototypeOf === 'function'; + +// Without `Object.setPrototypeOf` support, this module will need to add properties to a function. +// However, some of functions' own props are not configurable and should be skipped. +var testFn = function() {}; +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + var propDesc = Object.getOwnPropertyDescriptor(testFn, name); + + // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, + // but then returns `undefined` as the property descriptor for `callee`. As a + // workaround, we perform an otherwise unnecessary type-check for `propDesc`, + // and then filter it out if it's not an object as it should be. + if (typeof propDesc !== 'object') + return true; + + return !propDesc.configurable; +}); + +// Cache `Function` properties +var call = Function.prototype.call, + apply = Function.prototype.apply; + +/** + * ### .addChainableMethod(ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @namespace Utils + * @name addChainableMethod + * @api public + */ + +module.exports = function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') { + chainingBehavior = function () { }; + } + + var chainableBehavior = { + method: method + , chainingBehavior: chainingBehavior + }; + + // save the methods so we can overwrite them later, if we need to. + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + + Object.defineProperty(ctx, name, + { get: function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + + var chainableMethodWrapper = function () { + // Setting the `ssfi` flag to `chainableMethodWrapper` causes this + // function to be the starting point for removing implementation + // frames from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then this assertion is being + // invoked from inside of another assertion. In this case, the `ssfi` + // flag has already been set by the outer assertion. + // + // Note that overwriting a chainable method merely replaces the saved + // methods in `ctx.__methods` instead of completely replacing the + // overwritten assertion. Therefore, an overwriting assertion won't + // set the `ssfi` or `lockSsfi` flags. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', chainableMethodWrapper); + } + + var result = chainableBehavior.method.apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(chainableMethodWrapper, name, true); + + // Use `Object.setPrototypeOf` if available + if (canSetPrototype) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + } + , configurable: true + }); +}; + +},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":30,"./transferFlags":32}],10:[function(require,module,exports){ +var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); + +/*! + * Chai - addLengthGuard utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .addLengthGuard(fn, assertionName, isChainable) + * + * Define `length` as a getter on the given uninvoked method assertion. The + * getter acts as a guard against chaining `length` directly off of an uninvoked + * method assertion, which is a problem because it references `function`'s + * built-in `length` property instead of Chai's `length` assertion. When the + * getter catches the user making this mistake, it throws an error with a + * helpful message. + * + * There are two ways in which this mistake can be made. The first way is by + * chaining the `length` assertion directly off of an uninvoked chainable + * method. In this case, Chai suggests that the user use `lengthOf` instead. The + * second way is by chaining the `length` assertion directly off of an uninvoked + * non-chainable method. Non-chainable methods must be invoked prior to + * chaining. In this case, Chai suggests that the user consult the docs for the + * given assertion. + * + * If the `length` property of functions is unconfigurable, then return `fn` + * without modification. + * + * Note that in ES6, the function's `length` property is configurable, so once + * support for legacy environments is dropped, Chai's `length` property can + * replace the built-in function's `length` property, and this length guard will + * no longer be necessary. In the mean time, maintaining consistency across all + * environments is the priority. + * + * @param {Function} fn + * @param {String} assertionName + * @param {Boolean} isChainable + * @namespace Utils + * @name addLengthGuard + */ + +module.exports = function addLengthGuard (fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + + Object.defineProperty(fn, 'length', { + get: function () { + if (isChainable) { + throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + + ' to a compatibility issue, "length" cannot directly follow "' + + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); + } + + throw Error('Invalid Chai property: ' + assertionName + '.length. See' + + ' docs for proper usage of "' + assertionName + '".'); + } + }); + + return fn; +}; + +},{}],11:[function(require,module,exports){ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/** + * ### .addMethod(ctx, name, method) + * + * Adds a method to the prototype of an object. + * + * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(fooStr).to.be.foo('bar'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for name + * @namespace Utils + * @name addMethod + * @api public + */ + +module.exports = function addMethod(ctx, name, method) { + var methodWrapper = function () { + // Setting the `ssfi` flag to `methodWrapper` causes this function to be the + // starting point for removing implementation frames from the stack trace of + // a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', methodWrapper); + } + + var result = method.apply(this, arguments); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); +}; + +},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":30,"./transferFlags":32}],12:[function(require,module,exports){ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var flag = require('./flag'); +var isProxyEnabled = require('./isProxyEnabled'); +var transferFlags = require('./transferFlags'); + +/** + * ### .addProperty(ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + * utils.addProperty(chai.Assertion.prototype, 'foo', function () { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.instanceof(Foo); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.foo; + * + * @param {Object} ctx object to which the property is added + * @param {String} name of property to add + * @param {Function} getter function to be used for name + * @namespace Utils + * @name addProperty + * @api public + */ + +module.exports = function addProperty(ctx, name, getter) { + getter = getter === undefined ? function () {} : getter; + + Object.defineProperty(ctx, name, + { get: function propertyGetter() { + // Setting the `ssfi` flag to `propertyGetter` causes this function to + // be the starting point for removing implementation frames from the + // stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', propertyGetter); + } + + var result = getter.call(this); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +}; + +},{"../../chai":2,"./flag":15,"./isProxyEnabled":25,"./transferFlags":32}],13:[function(require,module,exports){ +/*! + * Chai - compareByInspect utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var inspect = require('./inspect'); + +/** + * ### .compareByInspect(mixed, mixed) + * + * To be used as a compareFunction with Array.prototype.sort. Compares elements + * using inspect instead of default behavior of using toString so that Symbols + * and objects with irregular/missing toString can still be sorted without a + * TypeError. + * + * @param {Mixed} first element to compare + * @param {Mixed} second element to compare + * @returns {Number} -1 if 'a' should come before 'b'; otherwise 1 + * @name compareByInspect + * @namespace Utils + * @api public + */ + +module.exports = function compareByInspect(a, b) { + return inspect(a) < inspect(b) ? -1 : 1; +}; + +},{"./inspect":23}],14:[function(require,module,exports){ +/*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .expectTypes(obj, types) + * + * Ensures that the object being tested against is of a valid type. + * + * utils.expectTypes(this, ['array', 'object', 'string']); + * + * @param {Mixed} obj constructed Assertion + * @param {Array} type A list of allowed types for this assertion + * @namespace Utils + * @name expectTypes + * @api public + */ + +var AssertionError = require('assertion-error'); +var flag = require('./flag'); +var type = require('type-detect'); + +module.exports = function expectTypes(obj, types) { + var flagMsg = flag(obj, 'message'); + var ssfi = flag(obj, 'ssfi'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + obj = flag(obj, 'object'); + types = types.map(function (t) { return t.toLowerCase(); }); + types.sort(); + + // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' + var str = types.map(function (t, index) { + var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; + var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; + return or + art + ' ' + t; + }).join(', '); + + var objType = type(obj).toLowerCase(); + + if (!types.some(function (expected) { return objType === expected; })) { + throw new AssertionError( + flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', + undefined, + ssfi + ); + } +}; + +},{"./flag":15,"assertion-error":33,"type-detect":39}],15:[function(require,module,exports){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .flag(object, key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + * utils.flag(this, 'foo', 'bar'); // setter + * utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {Object} object constructed Assertion + * @param {String} key + * @param {Mixed} value (optional) + * @namespace Utils + * @name flag + * @api private + */ + +module.exports = function flag(obj, key, value) { + var flags = obj.__flags || (obj.__flags = Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +}; + +},{}],16:[function(require,module,exports){ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getActual + */ + +module.exports = function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +}; + +},{}],17:[function(require,module,exports){ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var flag = require('./flag') + , getActual = require('./getActual') + , objDisplay = require('./objDisplay'); + +/** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Message template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getMessage + * @api public + */ + +module.exports = function getMessage(obj, args) { + var negate = flag(obj, 'negate') + , val = flag(obj, 'object') + , expected = args[3] + , actual = getActual(obj, args) + , msg = negate ? args[2] : args[1] + , flagMsg = flag(obj, 'message'); + + if(typeof msg === "function") msg = msg(); + msg = msg || ''; + msg = msg + .replace(/#\{this\}/g, function () { return objDisplay(val); }) + .replace(/#\{act\}/g, function () { return objDisplay(actual); }) + .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); + + return flagMsg ? flagMsg + ': ' + msg : msg; +}; + +},{"./flag":15,"./getActual":16,"./objDisplay":26}],18:[function(require,module,exports){ +var type = require('type-detect'); + +var flag = require('./flag'); + +function isObjectType(obj) { + var objectType = type(obj); + var objectTypes = ['Array', 'Object', 'function']; + + return objectTypes.indexOf(objectType) !== -1; +} + +/** + * ### .getOperator(message) + * + * Extract the operator from error message. + * Operator defined is based on below link + * https://nodejs.org/api/assert.html#assert_assert. + * + * Returns the `operator` or `undefined` value for an Assertion. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getOperator + * @api public + */ + +module.exports = function getOperator(obj, args) { + var operator = flag(obj, 'operator'); + var negate = flag(obj, 'negate'); + var expected = args[3]; + var msg = negate ? args[2] : args[1]; + + if (operator) { + return operator; + } + + if (typeof msg === 'function') msg = msg(); + + msg = msg || ''; + if (!msg) { + return undefined; + } + + if (/\shave\s/.test(msg)) { + return undefined; + } + + var isObject = isObjectType(expected); + if (/\snot\s/.test(msg)) { + return isObject ? 'notDeepStrictEqual' : 'notStrictEqual'; + } + + return isObject ? 'deepStrictEqual' : 'strictEqual'; +}; + +},{"./flag":15,"type-detect":39}],19:[function(require,module,exports){ +/*! + * Chai - getOwnEnumerableProperties utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + +/** + * ### .getOwnEnumerableProperties(object) + * + * This allows the retrieval of directly-owned enumerable property names and + * symbols of an object. This function is necessary because Object.keys only + * returns enumerable property names, not enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerableProperties + * @api public + */ + +module.exports = function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +}; + +},{"./getOwnEnumerablePropertySymbols":20}],20:[function(require,module,exports){ +/*! + * Chai - getOwnEnumerablePropertySymbols utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .getOwnEnumerablePropertySymbols(object) + * + * This allows the retrieval of directly-owned enumerable property symbols of an + * object. This function is necessary because Object.getOwnPropertySymbols + * returns both enumerable and non-enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerablePropertySymbols + * @api public + */ + +module.exports = function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== 'function') return []; + + return Object.getOwnPropertySymbols(obj).filter(function (sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +}; + +},{}],21:[function(require,module,exports){ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getProperties + * @api public + */ + +module.exports = function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + + function addProperty(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty); + proto = Object.getPrototypeOf(proto); + } + + return result; +}; + +},{}],22:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ + +/*! + * Dependencies that are used for multiple exports are required here only once + */ + +var pathval = require('pathval'); + +/*! + * test utility + */ + +exports.test = require('./test'); + +/*! + * type utility + */ + +exports.type = require('type-detect'); + +/*! + * expectTypes utility + */ +exports.expectTypes = require('./expectTypes'); + +/*! + * message utility + */ + +exports.getMessage = require('./getMessage'); + +/*! + * actual utility + */ + +exports.getActual = require('./getActual'); + +/*! + * Inspect util + */ + +exports.inspect = require('./inspect'); + +/*! + * Object Display util + */ + +exports.objDisplay = require('./objDisplay'); + +/*! + * Flag utility + */ + +exports.flag = require('./flag'); + +/*! + * Flag transferring utility + */ + +exports.transferFlags = require('./transferFlags'); + +/*! + * Deep equal utility + */ + +exports.eql = require('deep-eql'); + +/*! + * Deep path info + */ + +exports.getPathInfo = pathval.getPathInfo; + +/*! + * Check if a property exists + */ + +exports.hasProperty = pathval.hasProperty; + +/*! + * Function name + */ + +exports.getName = require('get-func-name'); + +/*! + * add Property + */ + +exports.addProperty = require('./addProperty'); + +/*! + * add Method + */ + +exports.addMethod = require('./addMethod'); + +/*! + * overwrite Property + */ + +exports.overwriteProperty = require('./overwriteProperty'); + +/*! + * overwrite Method + */ + +exports.overwriteMethod = require('./overwriteMethod'); + +/*! + * Add a chainable method + */ + +exports.addChainableMethod = require('./addChainableMethod'); + +/*! + * Overwrite chainable method + */ + +exports.overwriteChainableMethod = require('./overwriteChainableMethod'); + +/*! + * Compare by inspect method + */ + +exports.compareByInspect = require('./compareByInspect'); + +/*! + * Get own enumerable property symbols method + */ + +exports.getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + +/*! + * Get own enumerable properties method + */ + +exports.getOwnEnumerableProperties = require('./getOwnEnumerableProperties'); + +/*! + * Checks error against a given set of criteria + */ + +exports.checkError = require('check-error'); + +/*! + * Proxify util + */ + +exports.proxify = require('./proxify'); + +/*! + * addLengthGuard util + */ + +exports.addLengthGuard = require('./addLengthGuard'); + +/*! + * isProxyEnabled helper + */ + +exports.isProxyEnabled = require('./isProxyEnabled'); + +/*! + * isNaN method + */ + +exports.isNaN = require('./isNaN'); + +/*! + * getOperator method + */ + +exports.getOperator = require('./getOperator'); +},{"./addChainableMethod":9,"./addLengthGuard":10,"./addMethod":11,"./addProperty":12,"./compareByInspect":13,"./expectTypes":14,"./flag":15,"./getActual":16,"./getMessage":17,"./getOperator":18,"./getOwnEnumerableProperties":19,"./getOwnEnumerablePropertySymbols":20,"./inspect":23,"./isNaN":24,"./isProxyEnabled":25,"./objDisplay":26,"./overwriteChainableMethod":27,"./overwriteMethod":28,"./overwriteProperty":29,"./proxify":30,"./test":31,"./transferFlags":32,"check-error":34,"deep-eql":35,"get-func-name":36,"pathval":38,"type-detect":39}],23:[function(require,module,exports){ +// This is (almost) directly from Node.js utils +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + +var getName = require('get-func-name'); +var loupe = require('loupe'); +var config = require('../config'); + +module.exports = inspect; + +/** + * ### .inspect(obj, [showHidden], [depth], [colors]) + * + * Echoes the value of a value. Tries to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Boolean} showHidden Flag that shows hidden (not enumerable) + * properties of objects. Default is false. + * @param {Number} depth Depth in which to descend in object. Default is 2. + * @param {Boolean} colors Flag to turn on ANSI escape codes to color the + * output. Default is false (no coloring). + * @namespace Utils + * @name inspect + */ +function inspect(obj, showHidden, depth, colors) { + var options = { + colors: colors, + depth: (typeof depth === 'undefined' ? 2 : depth), + showHidden: showHidden, + truncate: config.truncateThreshold ? config.truncateThreshold : Infinity, + }; + return loupe.inspect(obj, options); +} + +},{"../config":4,"get-func-name":36,"loupe":37}],24:[function(require,module,exports){ +/*! + * Chai - isNaN utility + * Copyright(c) 2012-2015 Sakthipriyan Vairamani + * MIT Licensed + */ + +/** + * ### .isNaN(value) + * + * Checks if the given value is NaN or not. + * + * utils.isNaN(NaN); // true + * + * @param {Value} The value which has to be checked if it is NaN + * @name isNaN + * @api private + */ + +function isNaN(value) { + // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number + // section's NOTE. + return value !== value; +} + +// If ECMAScript 6's Number.isNaN is present, prefer that. +module.exports = Number.isNaN || isNaN; + +},{}],25:[function(require,module,exports){ +var config = require('../config'); + +/*! + * Chai - isProxyEnabled helper + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .isProxyEnabled() + * + * Helper function to check if Chai's proxy protection feature is enabled. If + * proxies are unsupported or disabled via the user's Chai config, then return + * false. Otherwise, return true. + * + * @namespace Utils + * @name isProxyEnabled + */ + +module.exports = function isProxyEnabled() { + return config.useProxy && + typeof Proxy !== 'undefined' && + typeof Reflect !== 'undefined'; +}; + +},{"../config":4}],26:[function(require,module,exports){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var inspect = require('./inspect'); +var config = require('../config'); + +/** + * ### .objDisplay(object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {Mixed} javascript object to inspect + * @returns {string} stringified object + * @name objDisplay + * @namespace Utils + * @api public + */ + +module.exports = function objDisplay(obj) { + var str = inspect(obj) + , type = Object.prototype.toString.call(obj); + + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type === '[object Function]') { + return !obj.name || obj.name === '' + ? '[Function]' + : '[Function: ' + obj.name + ']'; + } else if (type === '[object Array]') { + return '[ Array(' + obj.length + ') ]'; + } else if (type === '[object Object]') { + var keys = Object.keys(obj) + , kstr = keys.length > 2 + ? keys.splice(0, 2).join(', ') + ', ...' + : keys.join(', '); + return '{ Object (' + kstr + ') }'; + } else { + return str; + } + } else { + return str; + } +}; + +},{"../config":4,"./inspect":23}],27:[function(require,module,exports){ +/*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) + * + * Overwrites an already existing chainable method + * and provides access to the previous function or + * property. Must return functions to be used for + * name. + * + * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', + * function (_super) { + * } + * , function (_super) { + * } + * ); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteChainableMethod('foo', fn, fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.have.lengthOf(3); + * expect(myFoo).to.have.lengthOf.above(3); + * + * @param {Object} ctx object whose method / property is to be overwritten + * @param {String} name of method / property to overwrite + * @param {Function} method function that returns a function to be used for name + * @param {Function} chainingBehavior function that returns a function to be used for property + * @namespace Utils + * @name overwriteChainableMethod + * @api public + */ + +module.exports = function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { + var result = chainingBehavior(_chainingBehavior).call(this); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + var _method = chainableBehavior.method; + chainableBehavior.method = function overwritingChainableMethodWrapper() { + var result = method(_method).apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; +}; + +},{"../../chai":2,"./transferFlags":32}],28:[function(require,module,exports){ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteMethod(ctx, name, fn) + * + * Overwrites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + * return function (str) { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.value).to.equal(str); + * } else { + * _super.apply(this, arguments); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.equal('bar'); + * + * @param {Object} ctx object whose method is to be overwritten + * @param {String} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @namespace Utils + * @name overwriteMethod + * @api public + */ + +module.exports = function overwriteMethod(ctx, name, method) { + var _method = ctx[name] + , _super = function () { + throw new Error(name + ' is not a function'); + }; + + if (_method && 'function' === typeof _method) + _super = _method; + + var overwritingMethodWrapper = function () { + // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this + // function to be the starting point for removing implementation frames from + // the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingMethodWrapper); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion + // from changing the `ssfi` flag. By this point, the `ssfi` flag is already + // set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = method(_super).apply(this, arguments); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +}; + +},{"../../chai":2,"./addLengthGuard":10,"./flag":15,"./proxify":30,"./transferFlags":32}],29:[function(require,module,exports){ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var flag = require('./flag'); +var isProxyEnabled = require('./isProxyEnabled'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteProperty(ctx, name, fn) + * + * Overwrites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + * return function () { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.name).to.equal('bar'); + * } else { + * _super.call(this); + * } + * } + * }); + * + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.ok; + * + * @param {Object} ctx object whose property is to be overwritten + * @param {String} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @namespace Utils + * @name overwriteProperty + * @api public + */ + +module.exports = function overwriteProperty(ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name) + , _super = function () {}; + + if (_get && 'function' === typeof _get.get) + _super = _get.get + + Object.defineProperty(ctx, name, + { get: function overwritingPropertyGetter() { + // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this + // function to be the starting point for removing implementation frames + // from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingPropertyGetter); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten + // assertion from changing the `ssfi` flag. By this point, the `ssfi` + // flag is already set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = getter(_super).call(this); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +}; + +},{"../../chai":2,"./flag":15,"./isProxyEnabled":25,"./transferFlags":32}],30:[function(require,module,exports){ +var config = require('../config'); +var flag = require('./flag'); +var getProperties = require('./getProperties'); +var isProxyEnabled = require('./isProxyEnabled'); + +/*! + * Chai - proxify utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .proxify(object) + * + * Return a proxy of given object that throws an error when a non-existent + * property is read. By default, the root cause is assumed to be a misspelled + * property, and thus an attempt is made to offer a reasonable suggestion from + * the list of existing properties. However, if a nonChainableMethodName is + * provided, then the root cause is instead a failure to invoke a non-chainable + * method prior to reading the non-existent property. + * + * If proxies are unsupported or disabled via the user's Chai config, then + * return object without modification. + * + * @param {Object} obj + * @param {String} nonChainableMethodName + * @namespace Utils + * @name proxify + */ + +var builtins = ['__flags', '__methods', '_obj', 'assert']; + +module.exports = function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + + return new Proxy(obj, { + get: function proxyGetter(target, property) { + // This check is here because we should not throw errors on Symbol properties + // such as `Symbol.toStringTag`. + // The values for which an error should be thrown can be configured using + // the `config.proxyExcludedKeys` setting. + if (typeof property === 'string' && + config.proxyExcludedKeys.indexOf(property) === -1 && + !Reflect.has(target, property)) { + // Special message for invalid property access of non-chainable methods. + if (nonChainableMethodName) { + throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + + property + '. See docs for proper usage of "' + + nonChainableMethodName + '".'); + } + + // If the property is reasonably close to an existing Chai property, + // suggest that property to the user. Only suggest properties with a + // distance less than 4. + var suggestion = null; + var suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + !Object.prototype.hasOwnProperty(prop) && + builtins.indexOf(prop) === -1 + ) { + var dist = stringDistanceCapped( + property, + prop, + suggestionDistance + ); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + + if (suggestion !== null) { + throw Error('Invalid Chai property: ' + property + + '. Did you mean "' + suggestion + '"?'); + } else { + throw Error('Invalid Chai property: ' + property); + } + } + + // Use this proxy getter as the starting point for removing implementation + // frames from the stack trace of a failed assertion. For property + // assertions, this prevents the proxy getter from showing up in the stack + // trace since it's invoked before the property getter. For method and + // chainable method assertions, this flag will end up getting changed to + // the method wrapper, which is good since this frame will no longer be in + // the stack once the method is invoked. Note that Chai builtin assertion + // properties such as `__flags` are skipped since this is only meant to + // capture the starting point of an assertion. This step is also skipped + // if the `lockSsfi` flag is set, thus indicating that this assertion is + // being called from within another assertion. In that case, the `ssfi` + // flag is already set to the outer assertion's starting point. + if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { + flag(target, 'ssfi', proxyGetter); + } + + return Reflect.get(target, property); + } + }); +}; + +/** + * # stringDistanceCapped(strA, strB, cap) + * Return the Levenshtein distance between two strings, but no more than cap. + * @param {string} strA + * @param {string} strB + * @param {number} number + * @return {number} min(string distance between strA and strB, cap) + * @api private + */ + +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + + var memo = []; + // `memo` is a two-dimensional array containing distances. + // memo[i][j] is the distance between strA.slice(0, i) and + // strB.slice(0, j). + for (var i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (var j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + + for (var i = 1; i <= strA.length; i++) { + var ch = strA.charCodeAt(i - 1); + for (var j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + + return memo[strA.length][strB.length]; +} + +},{"../config":4,"./flag":15,"./getProperties":21,"./isProxyEnabled":25}],31:[function(require,module,exports){ +/*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var flag = require('./flag'); + +/** + * ### .test(object, expression) + * + * Test an object for expression. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name test + */ + +module.exports = function test(obj, args) { + var negate = flag(obj, 'negate') + , expr = args[0]; + return negate ? !expr : expr; +}; + +},{"./flag":15}],32:[function(require,module,exports){ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, `lockSsfi`, + * and `message`) will not be transferred. + * + * + * var newAssertion = new Assertion(); + * utils.transferFlags(assertion, newAssertion); + * + * var anotherAssertion = new Assertion(myObj); + * utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {Assertion} assertion the assertion to transfer the flags from + * @param {Object} object the object to transfer the flags to; usually a new assertion + * @param {Boolean} includeAll + * @namespace Utils + * @name transferFlags + * @api private + */ + +module.exports = function transferFlags(assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + + if (!object.__flags) { + object.__flags = Object.create(null); + } + + includeAll = arguments.length === 3 ? includeAll : true; + + for (var flag in flags) { + if (includeAll || + (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { + object.__flags[flag] = flags[flag]; + } + } +}; + +},{}],33:[function(require,module,exports){ +/*! + * assertion-error + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +/*! + * Return a function that will copy properties from + * one object to another excluding any originally + * listed. Returned function will create a new `{}`. + * + * @param {String} excluded properties ... + * @return {Function} + */ + +function exclude () { + var excludes = [].slice.call(arguments); + + function excludeProps (res, obj) { + Object.keys(obj).forEach(function (key) { + if (!~excludes.indexOf(key)) res[key] = obj[key]; + }); + } + + return function extendExclude () { + var args = [].slice.call(arguments) + , i = 0 + , res = {}; + + for (; i < args.length; i++) { + excludeProps(res, args[i]); + } + + return res; + }; +}; + +/*! + * Primary Exports + */ + +module.exports = AssertionError; + +/** + * ### AssertionError + * + * An extension of the JavaScript `Error` constructor for + * assertion and validation scenarios. + * + * @param {String} message + * @param {Object} properties to include (optional) + * @param {callee} start stack function (optional) + */ + +function AssertionError (message, _props, ssf) { + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') + , props = extend(_props || {}); + + // default values + this.message = message || 'Unspecified AssertionError'; + this.showDiff = false; + + // copy from properties + for (var key in props) { + this[key] = props[key]; + } + + // capture stack trace + ssf = ssf || AssertionError; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ssf); + } else { + try { + throw new Error(); + } catch(e) { + this.stack = e.stack; + } + } +} + +/*! + * Inherit from Error.prototype + */ + +AssertionError.prototype = Object.create(Error.prototype); + +/*! + * Statically set name + */ + +AssertionError.prototype.name = 'AssertionError'; + +/*! + * Ensure correct constructor + */ + +AssertionError.prototype.constructor = AssertionError; + +/** + * Allow errors to be converted to JSON for static transfer. + * + * @param {Boolean} include stack (default: `true`) + * @return {Object} object that can be `JSON.stringify` + */ + +AssertionError.prototype.toJSON = function (stack) { + var extend = exclude('constructor', 'toJSON', 'stack') + , props = extend({ name: this.name }, this); + + // include stack if exists and not turned off + if (false !== stack && this.stack) { + props.stack = this.stack; + } + + return props; +}; + +},{}],34:[function(require,module,exports){ +'use strict'; + +/* ! + * Chai - checkError utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + +var getFunctionName = require('get-func-name'); +/** + * ### .checkError + * + * Checks that an error conforms to a given set of criteria and/or retrieves information about it. + * + * @api public + */ + +/** + * ### .compatibleInstance(thrown, errorLike) + * + * Checks if two instances are compatible (strict equal). + * Returns false if errorLike is not an instance of Error, because instances + * can only be compatible if they're both error instances. + * + * @name compatibleInstance + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleInstance(thrown, errorLike) { + return errorLike instanceof Error && thrown === errorLike; +} + +/** + * ### .compatibleConstructor(thrown, errorLike) + * + * Checks if two constructors are compatible. + * This function can receive either an error constructor or + * an error instance as the `errorLike` argument. + * Constructors are compatible if they're the same or if one is + * an instance of another. + * + * @name compatibleConstructor + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleConstructor(thrown, errorLike) { + if (errorLike instanceof Error) { + // If `errorLike` is an instance of any error we compare their constructors + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if (errorLike.prototype instanceof Error || errorLike === Error) { + // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + + return false; +} + +/** + * ### .compatibleMessage(thrown, errMatcher) + * + * Checks if an error's message is compatible with a matcher (String or RegExp). + * If the message contains the String or passes the RegExp test, + * it is considered compatible. + * + * @name compatibleMessage + * @param {Error} thrown error + * @param {String|RegExp} errMatcher to look for into the message + * @namespace Utils + * @api public + */ + +function compatibleMessage(thrown, errMatcher) { + var comparisonString = typeof thrown === 'string' ? thrown : thrown.message; + if (errMatcher instanceof RegExp) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === 'string') { + return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers + } + + return false; +} + +/** + * ### .getConstructorName(errorLike) + * + * Gets the constructor name for an Error instance or constructor itself. + * + * @name getConstructorName + * @param {Error|ErrorConstructor} errorLike + * @namespace Utils + * @api public + */ + +function getConstructorName(errorLike) { + var constructorName = errorLike; + if (errorLike instanceof Error) { + constructorName = getFunctionName(errorLike.constructor); + } else if (typeof errorLike === 'function') { + // If `err` is not an instance of Error it is an error constructor itself or another function. + // If we've got a common function we get its name, otherwise we may need to create a new instance + // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. + constructorName = getFunctionName(errorLike); + if (constructorName === '') { + var newConstructorName = getFunctionName(new errorLike()); // eslint-disable-line new-cap + constructorName = newConstructorName || constructorName; + } + } + + return constructorName; +} + +/** + * ### .getMessage(errorLike) + * + * Gets the error message from an error. + * If `err` is a String itself, we return it. + * If the error has no message, we return an empty string. + * + * @name getMessage + * @param {Error|String} errorLike + * @namespace Utils + * @api public + */ + +function getMessage(errorLike) { + var msg = ''; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === 'string') { + msg = errorLike; + } + + return msg; +} + +module.exports = { + compatibleInstance: compatibleInstance, + compatibleConstructor: compatibleConstructor, + compatibleMessage: compatibleMessage, + getMessage: getMessage, + getConstructorName: getConstructorName, +}; + +},{"get-func-name":36}],35:[function(require,module,exports){ +'use strict'; +/* globals Symbol: false, Uint8Array: false, WeakMap: false */ +/*! + * deep-eql + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +var type = require('type-detect'); +function FakeMap() { + this._key = 'chai/deep-eql__' + Math.random() + Date.now(); +} + +FakeMap.prototype = { + get: function get(key) { + return key[this._key]; + }, + set: function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value: value, + configurable: true, + }); + } + }, +}; + +var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; +/*! + * Check to see if the MemoizeMap has recorded a result of the two operands + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @returns {Boolean|null} result +*/ +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === 'boolean') { + return result; + } + } + return null; +} + +/*! + * Set the result of the equality into the MemoizeMap + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @param {Boolean} result +*/ +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} + +/*! + * Primary Export + */ + +module.exports = deepEqual; +module.exports.MemoizeMap = MemoizeMap; + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + */ +function deepEqual(leftHandOperand, rightHandOperand, options) { + // If we have a comparator, we can't assume anything; so bail to its check first. + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + + // Deeper comparisons are pushed through to a larger function + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} + +/** + * Many comparisons can be canceled out early via simple equality or primitive checks. + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @return {Boolean|null} equal match + */ +function simpleEqual(leftHandOperand, rightHandOperand) { + // Equal references (except for Numbers) can be returned early + if (leftHandOperand === rightHandOperand) { + // Handle +-0 cases + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + + // handle NaN cases + if ( + leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare + ) { + return true; + } + + // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, + // strings, and undefined, can be compared by reference. + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + // Easy out b/c it would have passed the first equality check + return false; + } + return null; +} + +/*! + * The main logic of the `deepEqual` function. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match +*/ +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + + // Check if a memoized result exists. + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + + // If a comparator is present, use it. + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + // Comparators may return null, in which case we want to go back to default behavior. + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide + // what to do, we need to make sure to return the basic tests first before we move on. + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + // Don't memoize this, it takes longer to set/retrieve than to just compare. + return simpleResult; + } + } + + var leftHandType = type(leftHandOperand); + if (leftHandType !== type(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + + // Temporarily set the operands in the memoize object to prevent blowing the stack + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} + +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case 'String': + case 'Number': + case 'Boolean': + case 'Date': + // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case 'Promise': + case 'Symbol': + case 'function': + case 'WeakMap': + case 'WeakSet': + return leftHandOperand === rightHandOperand; + case 'Error': + return keysEqual(leftHandOperand, rightHandOperand, [ 'name', 'message', 'code' ], options); + case 'Arguments': + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'Array': + return iterableEqual(leftHandOperand, rightHandOperand, options); + case 'RegExp': + return regexpEqual(leftHandOperand, rightHandOperand); + case 'Generator': + return generatorEqual(leftHandOperand, rightHandOperand, options); + case 'DataView': + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case 'ArrayBuffer': + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case 'Set': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Map': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Temporal.PlainDate': + case 'Temporal.PlainTime': + case 'Temporal.PlainDateTime': + case 'Temporal.Instant': + case 'Temporal.ZonedDateTime': + case 'Temporal.PlainYearMonth': + case 'Temporal.PlainMonthDay': + return leftHandOperand.equals(rightHandOperand); + case 'Temporal.Duration': + return leftHandOperand.total('nanoseconds') === rightHandOperand.total('nanoseconds'); + case 'Temporal.TimeZone': + case 'Temporal.Calendar': + return leftHandOperand.toString() === rightHandOperand.toString(); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} + +/*! + * Compare two Regular Expressions for equality. + * + * @param {RegExp} leftHandOperand + * @param {RegExp} rightHandOperand + * @return {Boolean} result + */ + +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} + +/*! + * Compare two Sets/Maps for equality. Faster than other equality functions. + * + * @param {Set} leftHandOperand + * @param {Set} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function entriesEqual(leftHandOperand, rightHandOperand, options) { + // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(function gatherEntries(key, value) { + leftHandItems.push([ key, value ]); + }); + rightHandOperand.forEach(function gatherEntries(key, value) { + rightHandItems.push([ key, value ]); + }); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} + +/*! + * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} + +/*! + * Simple equality for generator objects such as those returned by generator functions. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} + +/*! + * Determine if the given object has an @@iterator function. + * + * @param {Object} target + * @return {Boolean} `true` if the object has an @@iterator function. + */ +function hasIteratorFunction(target) { + return typeof Symbol !== 'undefined' && + typeof target === 'object' && + typeof Symbol.iterator !== 'undefined' && + typeof target[Symbol.iterator] === 'function'; +} + +/*! + * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. + * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * + * @param {Object} target + * @returns {Array} an array of entries from the @@iterator function + */ +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} + +/*! + * Gets all entries from a Generator. This will consume the generator - which could have side effects. + * + * @param {Generator} target + * @returns {Array} an array of entries from the Generator. + */ +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [ generatorResult.value ]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} + +/*! + * Gets all own and inherited enumerable keys from a target. + * + * @param {Object} target + * @returns {Array} an array of own and inherited enumerable keys from the target. + */ +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} + +function getEnumerableSymbols(target) { + var keys = []; + var allKeys = Object.getOwnPropertySymbols(target); + for (var i = 0; i < allKeys.length; i += 1) { + var key = allKeys[i]; + if (Object.getOwnPropertyDescriptor(target, key).enumerable) { + keys.push(key); + } + } + return keys; +} + +/*! + * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of + * each key. If any value of the given key is not equal, the function will return false (early). + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} + +/*! + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + var leftHandSymbols = getEnumerableSymbols(leftHandOperand); + var rightHandSymbols = getEnumerableSymbols(rightHandOperand); + leftHandKeys = leftHandKeys.concat(leftHandSymbols); + rightHandKeys = rightHandKeys.concat(rightHandSymbols); + + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + if (iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + + if (leftHandKeys.length === 0 && + leftHandEntries.length === 0 && + rightHandKeys.length === 0 && + rightHandEntries.length === 0) { + return true; + } + + return false; +} + +/*! + * Returns true if the argument is a primitive. + * + * This intentionally returns true for all objects that can be compared by reference, + * including functions and symbols. + * + * @param {Mixed} value + * @return {Boolean} result + */ +function isPrimitive(value) { + return value === null || typeof value !== 'object'; +} + +function mapSymbols(arr) { + return arr.map(function mapSymbol(entry) { + if (typeof entry === 'symbol') { + return entry.toString(); + } + + return entry; + }); +} + +},{"type-detect":39}],36:[function(require,module,exports){ +'use strict'; + +/* ! + * Chai - getFuncName utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .getFuncName(constructorFn) + * + * Returns the name of a function. + * When a non-function instance is passed, returns `null`. + * This also includes a polyfill function if `aFunc.name` is not defined. + * + * @name getFuncName + * @param {Function} funct + * @namespace Utils + * @api public + */ + +var toString = Function.prototype.toString; +var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; +var maxFunctionSourceLength = 512; +function getFuncName(aFunc) { + if (typeof aFunc !== 'function') { + return null; + } + + var name = ''; + if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { + // eslint-disable-next-line prefer-reflect + var functionSource = toString.call(aFunc); + // To avoid unconstrained resource consumption due to pathalogically large function names, + // we limit the available return value to be less than 512 characters. + if (functionSource.indexOf('(') > maxFunctionSourceLength) { + return name; + } + // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined + var match = functionSource.match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + // If we've got a `name` property we just use it + name = aFunc.name; + } + + return name; +} + +module.exports = getFuncName; + +},{}],37:[function(require,module,exports){ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.loupe = {})); +}(this, (function (exports) { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + 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 _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var ansiColors = { + bold: ['1', '22'], + dim: ['2', '22'], + italic: ['3', '23'], + underline: ['4', '24'], + // 5 & 6 are blinking + inverse: ['7', '27'], + hidden: ['8', '28'], + strike: ['9', '29'], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ['30', '39'], + red: ['31', '39'], + green: ['32', '39'], + yellow: ['33', '39'], + blue: ['34', '39'], + magenta: ['35', '39'], + cyan: ['36', '39'], + white: ['37', '39'], + brightblack: ['30;1', '39'], + brightred: ['31;1', '39'], + brightgreen: ['32;1', '39'], + brightyellow: ['33;1', '39'], + brightblue: ['34;1', '39'], + brightmagenta: ['35;1', '39'], + brightcyan: ['36;1', '39'], + brightwhite: ['37;1', '39'], + grey: ['90', '39'] + }; + var styles = { + special: 'cyan', + number: 'yellow', + bigint: 'yellow', + boolean: 'yellow', + undefined: 'grey', + null: 'bold', + string: 'green', + symbol: 'green', + date: 'magenta', + regexp: 'red' + }; + var truncator = '…'; + + function colorise(value, styleType) { + var color = ansiColors[styles[styleType]] || ansiColors[styleType]; + + if (!color) { + return String(value); + } + + return "\x1B[".concat(color[0], "m").concat(String(value), "\x1B[").concat(color[1], "m"); + } + + function normaliseOptions() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$showHidden = _ref.showHidden, + showHidden = _ref$showHidden === void 0 ? false : _ref$showHidden, + _ref$depth = _ref.depth, + depth = _ref$depth === void 0 ? 2 : _ref$depth, + _ref$colors = _ref.colors, + colors = _ref$colors === void 0 ? false : _ref$colors, + _ref$customInspect = _ref.customInspect, + customInspect = _ref$customInspect === void 0 ? true : _ref$customInspect, + _ref$showProxy = _ref.showProxy, + showProxy = _ref$showProxy === void 0 ? false : _ref$showProxy, + _ref$maxArrayLength = _ref.maxArrayLength, + maxArrayLength = _ref$maxArrayLength === void 0 ? Infinity : _ref$maxArrayLength, + _ref$breakLength = _ref.breakLength, + breakLength = _ref$breakLength === void 0 ? Infinity : _ref$breakLength, + _ref$seen = _ref.seen, + seen = _ref$seen === void 0 ? [] : _ref$seen, + _ref$truncate = _ref.truncate, + truncate = _ref$truncate === void 0 ? Infinity : _ref$truncate, + _ref$stylize = _ref.stylize, + stylize = _ref$stylize === void 0 ? String : _ref$stylize; + + var options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate), + seen: seen, + stylize: stylize + }; + + if (options.colors) { + options.stylize = colorise; + } + + return options; + } + function truncate(string, length) { + var tail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : truncator; + string = String(string); + var tailLength = tail.length; + var stringLength = string.length; + + if (tailLength > length && stringLength > tailLength) { + return tail; + } + + if (stringLength > length && stringLength > tailLength) { + return "".concat(string.slice(0, length - tailLength)).concat(tail); + } + + return string; + } // eslint-disable-next-line complexity + + function inspectList(list, options, inspectItem) { + var separator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ', '; + inspectItem = inspectItem || options.inspect; + var size = list.length; + if (size === 0) return ''; + var originalLength = options.truncate; + var output = ''; + var peek = ''; + var truncated = ''; + + for (var i = 0; i < size; i += 1) { + var last = i + 1 === list.length; + var secondToLast = i + 2 === list.length; + truncated = "".concat(truncator, "(").concat(list.length - i, ")"); + var value = list[i]; // If there is more than one remaining we need to account for a separator of `, ` + + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + var string = peek || inspectItem(value, options) + (last ? '' : separator); + var nextLength = output.length + string.length; + var truncatedLength = nextLength + truncated.length; // If this is the last element, and adding it would + // take us over length, but adding the truncator wouldn't - then break now + + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } // If this isn't the last or second to last element to scan, + // but the string is already over length then break here + + + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } // Peek at the next string to determine if we should + // break early before adding this item to the output + + + peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator); // If we have one element left, but this element and + // the next takes over length, the break early + + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + + output += string; // If the next element takes us to length - + // but there are more after that, then we should truncate now + + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = "".concat(truncator, "(").concat(list.length - i - 1, ")"); + break; + } + + truncated = ''; + } + + return "".concat(output).concat(truncated); + } + + function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + + return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); + } + + function inspectProperty(_ref2, options) { + var _ref3 = _slicedToArray(_ref2, 2), + key = _ref3[0], + value = _ref3[1]; + + options.truncate -= 2; + + if (typeof key === 'string') { + key = quoteComplexKey(key); + } else if (typeof key !== 'number') { + key = "[".concat(options.inspect(key, options), "]"); + } + + options.truncate -= key.length; + value = options.inspect(value, options); + return "".concat(key, ": ").concat(value); + } + + function inspectArray(array, options) { + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + var nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) return '[]'; + options.truncate -= 4; + var listContents = inspectList(array, options); + options.truncate -= listContents.length; + var propertyContents = ''; + + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(function (key) { + return [key, array[key]]; + }), options, inspectProperty); + } + + return "[ ".concat(listContents).concat(propertyContents ? ", ".concat(propertyContents) : '', " ]"); + } + + /* ! + * Chai - getFuncName utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + + /** + * ### .getFuncName(constructorFn) + * + * Returns the name of a function. + * When a non-function instance is passed, returns `null`. + * This also includes a polyfill function if `aFunc.name` is not defined. + * + * @name getFuncName + * @param {Function} funct + * @namespace Utils + * @api public + */ + + var toString = Function.prototype.toString; + var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; + function getFuncName(aFunc) { + if (typeof aFunc !== 'function') { + return null; + } + + var name = ''; + if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { + // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined + var match = toString.call(aFunc).match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + // If we've got a `name` property we just use it + name = aFunc.name; + } + + return name; + } + + var getFuncName_1 = getFuncName; + + var getArrayName = function getArrayName(array) { + // We need to special case Node.js' Buffers, which report to be Uint8Array + if (typeof Buffer === 'function' && array instanceof Buffer) { + return 'Buffer'; + } + + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + + return getFuncName_1(array.constructor); + }; + + function inspectTypedArray(array, options) { + var name = getArrayName(array); + options.truncate -= name.length + 4; // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + + var nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) return "".concat(name, "[]"); // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply + // stylise the toString() value of them + + var output = ''; + + for (var i = 0; i < array.length; i++) { + var string = "".concat(options.stylize(truncate(array[i], options.truncate), 'number')).concat(i === array.length - 1 ? '' : ', '); + options.truncate -= string.length; + + if (array[i] !== array.length && options.truncate <= 3) { + output += "".concat(truncator, "(").concat(array.length - array[i] + 1, ")"); + break; + } + + output += string; + } + + var propertyContents = ''; + + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(function (key) { + return [key, array[key]]; + }), options, inspectProperty); + } + + return "".concat(name, "[ ").concat(output).concat(propertyContents ? ", ".concat(propertyContents) : '', " ]"); + } + + function inspectDate(dateObject, options) { + var stringRepresentation = dateObject.toJSON(); + + if (stringRepresentation === null) { + return 'Invalid Date'; + } + + var split = stringRepresentation.split('T'); + var date = split[0]; // If we need to - truncate the time portion, but never the date + + return options.stylize("".concat(date, "T").concat(truncate(split[1], options.truncate - date.length - 1)), 'date'); + } + + function inspectFunction(func, options) { + var name = getFuncName_1(func); + + if (!name) { + return options.stylize('[Function]', 'special'); + } + + return options.stylize("[Function ".concat(truncate(name, options.truncate - 11), "]"), 'special'); + } + + function inspectMapEntry(_ref, options) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return "".concat(key, " => ").concat(value); + } // IE11 doesn't support `map.entries()` + + + function mapToEntries(map) { + var entries = []; + map.forEach(function (value, key) { + entries.push([key, value]); + }); + return entries; + } + + function inspectMap(map, options) { + var size = map.size - 1; + + if (size <= 0) { + return 'Map{}'; + } + + options.truncate -= 7; + return "Map{ ".concat(inspectList(mapToEntries(map), options, inspectMapEntry), " }"); + } + + var isNaN = Number.isNaN || function (i) { + return i !== i; + }; // eslint-disable-line no-self-compare + + + function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize('NaN', 'number'); + } + + if (number === Infinity) { + return options.stylize('Infinity', 'number'); + } + + if (number === -Infinity) { + return options.stylize('-Infinity', 'number'); + } + + if (number === 0) { + return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number'); + } + + return options.stylize(truncate(number, options.truncate), 'number'); + } + + function inspectBigInt(number, options) { + var nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) nums += 'n'; + return options.stylize(nums, 'bigint'); + } + + function inspectRegExp(value, options) { + var flags = value.toString().split('/')[2]; + var sourceLength = options.truncate - (2 + flags.length); + var source = value.source; + return options.stylize("/".concat(truncate(source, sourceLength), "/").concat(flags), 'regexp'); + } + + function arrayFromSet(set) { + var values = []; + set.forEach(function (value) { + values.push(value); + }); + return values; + } + + function inspectSet(set, options) { + if (set.size === 0) return 'Set{}'; + options.truncate -= 7; + return "Set{ ".concat(inspectList(arrayFromSet(set), options), " }"); + } + + var stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + "\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", 'g'); + var escapeCharacters = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\' + }; + var hex = 16; + var unicodeLength = 4; + + function escape(char) { + return escapeCharacters[char] || "\\u".concat("0000".concat(char.charCodeAt(0).toString(hex)).slice(-unicodeLength)); + } + + function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + + return options.stylize("'".concat(truncate(string, options.truncate - 2), "'"), 'string'); + } + + function inspectSymbol(value) { + if ('description' in Symbol.prototype) { + return value.description ? "Symbol(".concat(value.description, ")") : 'Symbol()'; + } + + return value.toString(); + } + + var getPromiseValue = function getPromiseValue() { + return 'Promise{…}'; + }; + + try { + var _process$binding = process.binding('util'), + getPromiseDetails = _process$binding.getPromiseDetails, + kPending = _process$binding.kPending, + kRejected = _process$binding.kRejected; + + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = function getPromiseValue(value, options) { + var _getPromiseDetails = getPromiseDetails(value), + _getPromiseDetails2 = _slicedToArray(_getPromiseDetails, 2), + state = _getPromiseDetails2[0], + innerValue = _getPromiseDetails2[1]; + + if (state === kPending) { + return 'Promise{}'; + } + + return "Promise".concat(state === kRejected ? '!' : '', "{").concat(options.inspect(innerValue, options), "}"); + }; + } + } catch (notNode) { + /* ignore */ + } + + var inspectPromise = getPromiseValue; + + function inspectObject(object, options) { + var properties = Object.getOwnPropertyNames(object); + var symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + + if (properties.length === 0 && symbols.length === 0) { + return '{}'; + } + + options.truncate -= 4; + options.seen = options.seen || []; + + if (options.seen.indexOf(object) >= 0) { + return '[Circular]'; + } + + options.seen.push(object); + var propertyContents = inspectList(properties.map(function (key) { + return [key, object[key]]; + }), options, inspectProperty); + var symbolContents = inspectList(symbols.map(function (key) { + return [key, object[key]]; + }), options, inspectProperty); + options.seen.pop(); + var sep = ''; + + if (propertyContents && symbolContents) { + sep = ', '; + } + + return "{ ".concat(propertyContents).concat(sep).concat(symbolContents, " }"); + } + + var toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false; + function inspectClass(value, options) { + var name = ''; + + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + + name = name || getFuncName_1(value.constructor); // Babel transforms anonymous classes to the name `_class` + + if (!name || name === '_class') { + name = ''; + } + + options.truncate -= name.length; + return "".concat(name).concat(inspectObject(value, options)); + } + + function inspectArguments(args, options) { + if (args.length === 0) return 'Arguments[]'; + options.truncate -= 13; + return "Arguments[ ".concat(inspectList(args, options), " ]"); + } + + var errorKeys = ['stack', 'line', 'column', 'name', 'message', 'fileName', 'lineNumber', 'columnNumber', 'number', 'description']; + function inspectObject$1(error, options) { + var properties = Object.getOwnPropertyNames(error).filter(function (key) { + return errorKeys.indexOf(key) === -1; + }); + var name = error.name; + options.truncate -= name.length; + var message = ''; + + if (typeof error.message === 'string') { + message = truncate(error.message, options.truncate); + } else { + properties.unshift('message'); + } + + message = message ? ": ".concat(message) : ''; + options.truncate -= message.length + 5; + var propertyContents = inspectList(properties.map(function (key) { + return [key, error[key]]; + }), options, inspectProperty); + return "".concat(name).concat(message).concat(propertyContents ? " { ".concat(propertyContents, " }") : ''); + } + + function inspectAttribute(_ref, options) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + + options.truncate -= 3; + + if (!value) { + return "".concat(options.stylize(key, 'yellow')); + } + + return "".concat(options.stylize(key, 'yellow'), "=").concat(options.stylize("\"".concat(value, "\""), 'string')); + } + function inspectHTMLCollection(collection, options) { + // eslint-disable-next-line no-use-before-define + return inspectList(collection, options, inspectHTML, '\n'); + } + function inspectHTML(element, options) { + var properties = element.getAttributeNames(); + var name = element.tagName.toLowerCase(); + var head = options.stylize("<".concat(name), 'special'); + var headClose = options.stylize(">", 'special'); + var tail = options.stylize(""), 'special'); + options.truncate -= name.length * 2 + 5; + var propertyContents = ''; + + if (properties.length > 0) { + propertyContents += ' '; + propertyContents += inspectList(properties.map(function (key) { + return [key, element.getAttribute(key)]; + }), options, inspectAttribute, ' '); + } + + options.truncate -= propertyContents.length; + var truncate = options.truncate; + var children = inspectHTMLCollection(element.children, options); + + if (children && children.length > truncate) { + children = "".concat(truncator, "(").concat(element.children.length, ")"); + } + + return "".concat(head).concat(propertyContents).concat(headClose).concat(children).concat(tail); + } + + var symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function'; + var chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect'; + var nodeInspect = false; + + try { + // eslint-disable-next-line global-require + var nodeUtil = require('util'); + + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; + } catch (noNodeInspect) { + nodeInspect = false; + } + + function FakeMap() { + // eslint-disable-next-line prefer-template + this.key = 'chai/loupe__' + Math.random() + Date.now(); + } + + FakeMap.prototype = { + // eslint-disable-next-line object-shorthand + get: function get(key) { + return key[this.key]; + }, + // eslint-disable-next-line object-shorthand + has: function has(key) { + return this.key in key; + }, + // eslint-disable-next-line object-shorthand + set: function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this.key, { + // eslint-disable-next-line object-shorthand + value: value, + configurable: true + }); + } + } + }; + var constructorMap = new (typeof WeakMap === 'function' ? WeakMap : FakeMap)(); + var stringTagMap = {}; + var baseTypesMap = { + undefined: function undefined$1(value, options) { + return options.stylize('undefined', 'undefined'); + }, + null: function _null(value, options) { + return options.stylize(null, 'null'); + }, + boolean: function boolean(value, options) { + return options.stylize(value, 'boolean'); + }, + Boolean: function Boolean(value, options) { + return options.stylize(value, 'boolean'); + }, + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: inspectPromise, + // WeakSet, WeakMap are totally opaque to us + WeakSet: function WeakSet(value, options) { + return options.stylize('WeakSet{…}', 'special'); + }, + WeakMap: function WeakMap(value, options) { + return options.stylize('WeakMap{…}', 'special'); + }, + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: function Generator() { + return ''; + }, + DataView: function DataView() { + return ''; + }, + ArrayBuffer: function ArrayBuffer() { + return ''; + }, + Error: inspectObject$1, + HTMLCollection: inspectHTMLCollection, + NodeList: inspectHTMLCollection + }; // eslint-disable-next-line complexity + + var inspectCustom = function inspectCustom(value, options, type) { + if (chaiInspect in value && typeof value[chaiInspect] === 'function') { + return value[chaiInspect](options); + } + + if (nodeInspect && nodeInspect in value && typeof value[nodeInspect] === 'function') { + return value[nodeInspect](options.depth, options); + } + + if ('inspect' in value && typeof value.inspect === 'function') { + return value.inspect(options.depth, options); + } + + if ('constructor' in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + + if (stringTagMap[type]) { + return stringTagMap[type](value, options); + } + + return ''; + }; + + var toString$1 = Object.prototype.toString; // eslint-disable-next-line complexity + + function inspect(value, options) { + options = normaliseOptions(options); + options.inspect = inspect; + var _options = options, + customInspect = _options.customInspect; + var type = value === null ? 'null' : _typeof(value); + + if (type === 'object') { + type = toString$1.call(value).slice(8, -1); + } // If it is a base value that we already support, then use Loupe's inspector + + + if (baseTypesMap[type]) { + return baseTypesMap[type](value, options); + } // If `options.customInspect` is set to true then try to use the custom inspector + + + if (customInspect && value) { + var output = inspectCustom(value, options, type); + + if (output) { + if (typeof output === 'string') return output; + return inspect(output, options); + } + } + + var proto = value ? Object.getPrototypeOf(value) : false; // If it's a plain Object then use Loupe's inspector + + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } // Specifically account for HTMLElements + // eslint-disable-next-line no-undef + + + if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + + if ('constructor' in value) { + // If it is a class, inspect it like an object but add the constructor name + if (value.constructor !== Object) { + return inspectClass(value, options); + } // If it is an object with an anonymous prototype, display it as an object. + + + return inspectObject(value, options); + } // last chance to check if it's an object + + + if (value === Object(value)) { + return inspectObject(value, options); + } // We have run out of options! Just stringify the value + + + return options.stylize(String(value), type); + } + function registerConstructor(constructor, inspector) { + if (constructorMap.has(constructor)) { + return false; + } + + constructorMap.set(constructor, inspector); + return true; + } + function registerStringTag(stringTag, inspector) { + if (stringTag in stringTagMap) { + return false; + } + + stringTagMap[stringTag] = inspector; + return true; + } + var custom = chaiInspect; + + exports.custom = custom; + exports.default = inspect; + exports.inspect = inspect; + exports.registerConstructor = registerConstructor; + exports.registerStringTag = registerStringTag; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + +},{"util":undefined}],38:[function(require,module,exports){ +'use strict'; + +/* ! + * Chai - pathval utility + * Copyright(c) 2012-2014 Jake Luer + * @see https://github.com/logicalparadox/filtr + * MIT Licensed + */ + +/** + * ### .hasProperty(object, name) + * + * This allows checking whether an object has own + * or inherited from prototype chain named property. + * + * Basically does the same thing as the `in` + * operator but works properly with null/undefined values + * and other primitives. + * + * var obj = { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * + * The following would be the results. + * + * hasProperty(obj, 'str'); // true + * hasProperty(obj, 'constructor'); // true + * hasProperty(obj, 'bar'); // false + * + * hasProperty(obj.str, 'length'); // true + * hasProperty(obj.str, 1); // true + * hasProperty(obj.str, 5); // false + * + * hasProperty(obj.arr, 'length'); // true + * hasProperty(obj.arr, 2); // true + * hasProperty(obj.arr, 3); // false + * + * @param {Object} object + * @param {String|Symbol} name + * @returns {Boolean} whether it exists + * @namespace Utils + * @name hasProperty + * @api public + */ + +function hasProperty(obj, name) { + if (typeof obj === 'undefined' || obj === null) { + return false; + } + + // The `in` operator does not work with primitives. + return name in Object(obj); +} + +/* ! + * ## parsePath(path) + * + * Helper function used to parse string object + * paths. Use in conjunction with `internalGetPathValue`. + * + * var parsed = parsePath('myobject.property.subprop'); + * + * ### Paths: + * + * * Can be infinitely deep and nested. + * * Arrays are also valid using the formal `myobject.document[3].property`. + * * Literal dots and brackets (not delimiter) must be backslash-escaped. + * + * @param {String} path + * @returns {Object} parsed + * @api private + */ + +function parsePath(path) { + var str = path.replace(/([^\\])\[/g, '$1.['); + var parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map(function mapMatches(value) { + if ( + value === 'constructor' || + value === '__proto__' || + value === 'prototype' + ) { + return {}; + } + var regexp = /^\[(\d+)\]$/; + var mArr = regexp.exec(value); + var parsed = null; + if (mArr) { + parsed = { i: parseFloat(mArr[1]) }; + } else { + parsed = { p: value.replace(/\\([.[\]])/g, '$1') }; + } + + return parsed; + }); +} + +/* ! + * ## internalGetPathValue(obj, parsed[, pathDepth]) + * + * Helper companion function for `.parsePath` that returns + * the value located at the parsed address. + * + * var value = getPathValue(obj, parsed); + * + * @param {Object} object to search against + * @param {Object} parsed definition from `parsePath`. + * @param {Number} depth (nesting level) of the property we want to retrieve + * @returns {Object|Undefined} value + * @api private + */ + +function internalGetPathValue(obj, parsed, pathDepth) { + var temporaryValue = obj; + var res = null; + pathDepth = typeof pathDepth === 'undefined' ? parsed.length : pathDepth; + + for (var i = 0; i < pathDepth; i++) { + var part = parsed[i]; + if (temporaryValue) { + if (typeof part.p === 'undefined') { + temporaryValue = temporaryValue[part.i]; + } else { + temporaryValue = temporaryValue[part.p]; + } + + if (i === pathDepth - 1) { + res = temporaryValue; + } + } + } + + return res; +} + +/* ! + * ## internalSetPathValue(obj, value, parsed) + * + * Companion function for `parsePath` that sets + * the value located at a parsed address. + * + * internalSetPathValue(obj, 'value', parsed); + * + * @param {Object} object to search and define on + * @param {*} value to use upon set + * @param {Object} parsed definition from `parsePath` + * @api private + */ + +function internalSetPathValue(obj, val, parsed) { + var tempObj = obj; + var pathDepth = parsed.length; + var part = null; + // Here we iterate through every part of the path + for (var i = 0; i < pathDepth; i++) { + var propName = null; + var propVal = null; + part = parsed[i]; + + // If it's the last part of the path, we set the 'propName' value with the property name + if (i === pathDepth - 1) { + propName = typeof part.p === 'undefined' ? part.i : part.p; + // Now we set the property with the name held by 'propName' on object with the desired val + tempObj[propName] = val; + } else if (typeof part.p !== 'undefined' && tempObj[part.p]) { + tempObj = tempObj[part.p]; + } else if (typeof part.i !== 'undefined' && tempObj[part.i]) { + tempObj = tempObj[part.i]; + } else { + // If the obj doesn't have the property we create one with that name to define it + var next = parsed[i + 1]; + // Here we set the name of the property which will be defined + propName = typeof part.p === 'undefined' ? part.i : part.p; + // Here we decide if this property will be an array or a new object + propVal = typeof next.p === 'undefined' ? [] : {}; + tempObj[propName] = propVal; + tempObj = tempObj[propName]; + } + } +} + +/** + * ### .getPathInfo(object, path) + * + * This allows the retrieval of property info in an + * object given a string path. + * + * The path info consists of an object with the + * following properties: + * + * * parent - The parent object of the property referenced by `path` + * * name - The name of the final property, a number if it was an array indexer + * * value - The value of the property, if it exists, otherwise `undefined` + * * exists - Whether the property exists or not + * + * @param {Object} object + * @param {String} path + * @returns {Object} info + * @namespace Utils + * @name getPathInfo + * @api public + */ + +function getPathInfo(obj, path) { + var parsed = parsePath(path); + var last = parsed[parsed.length - 1]; + var info = { + parent: + parsed.length > 1 ? + internalGetPathValue(obj, parsed, parsed.length - 1) : + obj, + name: last.p || last.i, + value: internalGetPathValue(obj, parsed), + }; + info.exists = hasProperty(info.parent, info.name); + + return info; +} + +/** + * ### .getPathValue(object, path) + * + * This allows the retrieval of values in an + * object given a string path. + * + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * } + * + * The following would be the results. + * + * getPathValue(obj, 'prop1.str'); // Hello + * getPathValue(obj, 'prop1.att[2]'); // b + * getPathValue(obj, 'prop2.arr[0].nested'); // Universe + * + * @param {Object} object + * @param {String} path + * @returns {Object} value or `undefined` + * @namespace Utils + * @name getPathValue + * @api public + */ + +function getPathValue(obj, path) { + var info = getPathInfo(obj, path); + return info.value; +} + +/** + * ### .setPathValue(object, path, value) + * + * Define the value in an object at a given string path. + * + * ```js + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * }; + * ``` + * + * The following would be acceptable. + * + * ```js + * var properties = require('tea-properties'); + * properties.set(obj, 'prop1.str', 'Hello Universe!'); + * properties.set(obj, 'prop1.arr[2]', 'B'); + * properties.set(obj, 'prop2.arr[0].nested.value', { hello: 'universe' }); + * ``` + * + * @param {Object} object + * @param {String} path + * @param {Mixed} value + * @api private + */ + +function setPathValue(obj, path, val) { + var parsed = parsePath(path); + internalSetPathValue(obj, val, parsed); + return obj; +} + +module.exports = { + hasProperty: hasProperty, + getPathInfo: getPathInfo, + getPathValue: getPathValue, + setPathValue: setPathValue, +}; + +},{}],39:[function(require,module,exports){ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.typeDetect = factory()); +}(this, (function () { 'use strict'; + +/* ! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ +var promiseExists = typeof Promise === 'function'; + +/* eslint-disable no-undef */ +var globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist + +var symbolExists = typeof Symbol !== 'undefined'; +var mapExists = typeof Map !== 'undefined'; +var setExists = typeof Set !== 'undefined'; +var weakMapExists = typeof WeakMap !== 'undefined'; +var weakSetExists = typeof WeakSet !== 'undefined'; +var dataViewExists = typeof DataView !== 'undefined'; +var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; +var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; +var setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; +var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; +var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); +var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); +var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; +var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); +var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; +var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); +var toStringLeftSliceLength = 8; +var toStringRightSliceLength = -1; +/** + * ### typeOf (obj) + * + * Uses `Object.prototype.toString` to determine the type of an object, + * normalising behaviour across engine versions & well optimised. + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ +function typeDetect(obj) { + /* ! Speed optimisation + * Pre: + * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) + * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) + * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) + * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) + * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) + * Post: + * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) + * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) + * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) + * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) + * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) + */ + var typeofObj = typeof obj; + if (typeofObj !== 'object') { + return typeofObj; + } + + /* ! Speed optimisation + * Pre: + * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) + * Post: + * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) + */ + if (obj === null) { + return 'null'; + } + + /* ! Spec Conformance + * Test: `Object.prototype.toString.call(window)`` + * - Node === "[object global]" + * - Chrome === "[object global]" + * - Firefox === "[object Window]" + * - PhantomJS === "[object Window]" + * - Safari === "[object Window]" + * - IE 11 === "[object Window]" + * - IE Edge === "[object Window]" + * Test: `Object.prototype.toString.call(this)`` + * - Chrome Worker === "[object global]" + * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" + * - Safari Worker === "[object DedicatedWorkerGlobalScope]" + * - IE 11 Worker === "[object WorkerGlobalScope]" + * - IE Edge Worker === "[object WorkerGlobalScope]" + */ + if (obj === globalObject) { + return 'global'; + } + + /* ! Speed optimisation + * Pre: + * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) + * Post: + * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) + */ + if ( + Array.isArray(obj) && + (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) + ) { + return 'Array'; + } + + // Not caching existence of `window` and related properties due to potential + // for `window` to be unset before tests in quasi-browser environments. + if (typeof window === 'object' && window !== null) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/browsers.html#location) + * WhatWG HTML$7.7.3 - The `Location` interface + * Test: `Object.prototype.toString.call(window.location)`` + * - IE <=11 === "[object Object]" + * - IE Edge <=13 === "[object Object]" + */ + if (typeof window.location === 'object' && obj === window.location) { + return 'Location'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#document) + * WhatWG HTML$3.1.1 - The `Document` object + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * WhatWG HTML states: + * > For historical reasons, Window objects must also have a + * > writable, configurable, non-enumerable property named + * > HTMLDocument whose value is the Document interface object. + * Test: `Object.prototype.toString.call(document)`` + * - Chrome === "[object HTMLDocument]" + * - Firefox === "[object HTMLDocument]" + * - Safari === "[object HTMLDocument]" + * - IE <=10 === "[object Document]" + * - IE 11 === "[object HTMLDocument]" + * - IE Edge <=13 === "[object HTMLDocument]" + */ + if (typeof window.document === 'object' && obj === window.document) { + return 'Document'; + } + + if (typeof window.navigator === 'object') { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray + * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` + * - IE <=10 === "[object MSMimeTypesCollection]" + */ + if (typeof window.navigator.mimeTypes === 'object' && + obj === window.navigator.mimeTypes) { + return 'MimeTypeArray'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray + * Test: `Object.prototype.toString.call(navigator.plugins)`` + * - IE <=10 === "[object MSPluginsCollection]" + */ + if (typeof window.navigator.plugins === 'object' && + obj === window.navigator.plugins) { + return 'PluginArray'; + } + } + + if ((typeof window.HTMLElement === 'function' || + typeof window.HTMLElement === 'object') && + obj instanceof window.HTMLElement) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` + * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` + * - IE <=10 === "[object HTMLBlockElement]" + */ + if (obj.tagName === 'BLOCKQUOTE') { + return 'HTMLQuoteElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltabledatacellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('td')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TD') { + return 'HTMLTableDataCellElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltableheadercellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('th')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TH') { + return 'HTMLTableHeaderCellElement'; + } + } + } + + /* ! Speed optimisation + * Pre: + * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) + * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) + * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) + * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) + * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) + * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) + * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) + * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) + * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) + * Post: + * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) + * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) + * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) + * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) + * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) + * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) + * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) + * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) + * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) + */ + var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]); + if (typeof stringTag === 'string') { + return stringTag; + } + + var objPrototype = Object.getPrototypeOf(obj); + /* ! Speed optimisation + * Pre: + * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) + * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) + * Post: + * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) + * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) + */ + if (objPrototype === RegExp.prototype) { + return 'RegExp'; + } + + /* ! Speed optimisation + * Pre: + * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) + * Post: + * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) + */ + if (objPrototype === Date.prototype) { + return 'Date'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) + * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": + * Test: `Object.prototype.toString.call(Promise.resolve())`` + * - Chrome <=47 === "[object Object]" + * - Edge <=20 === "[object Object]" + * - Firefox 29-Latest === "[object Promise]" + * - Safari 7.1-Latest === "[object Promise]" + */ + if (promiseExists && objPrototype === Promise.prototype) { + return 'Promise'; + } + + /* ! Speed optimisation + * Pre: + * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) + * Post: + * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) + */ + if (setExists && objPrototype === Set.prototype) { + return 'Set'; + } + + /* ! Speed optimisation + * Pre: + * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) + * Post: + * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) + */ + if (mapExists && objPrototype === Map.prototype) { + return 'Map'; + } + + /* ! Speed optimisation + * Pre: + * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) + * Post: + * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) + */ + if (weakSetExists && objPrototype === WeakSet.prototype) { + return 'WeakSet'; + } + + /* ! Speed optimisation + * Pre: + * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) + * Post: + * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) + */ + if (weakMapExists && objPrototype === WeakMap.prototype) { + return 'WeakMap'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) + * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": + * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` + * - Edge <=13 === "[object Object]" + */ + if (dataViewExists && objPrototype === DataView.prototype) { + return 'DataView'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) + * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": + * Test: `Object.prototype.toString.call(new Map().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (mapExists && objPrototype === mapIteratorPrototype) { + return 'Map Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) + * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": + * Test: `Object.prototype.toString.call(new Set().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (setExists && objPrototype === setIteratorPrototype) { + return 'Set Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) + * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": + * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { + return 'Array Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) + * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": + * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (stringIteratorExists && objPrototype === stringIteratorPrototype) { + return 'String Iterator'; + } + + /* ! Speed optimisation + * Pre: + * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) + * Post: + * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) + */ + if (objPrototype === null) { + return 'Object'; + } + + return Object + .prototype + .toString + .call(obj) + .slice(toStringLeftSliceLength, toStringRightSliceLength); +} + +return typeDetect; + +}))); + +},{}]},{},[1])(1) +}); diff --git a/web/node_modules/chai/index.js b/web/node_modules/chai/index.js new file mode 100644 index 0000000000000000000000000000000000000000..634483b026182a8c8fa3554486ba99e59b8b65ad --- /dev/null +++ b/web/node_modules/chai/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/chai'); diff --git a/web/node_modules/chai/index.mjs b/web/node_modules/chai/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..65b726ad9bdec3c22ec2c1704c4218751e52943c --- /dev/null +++ b/web/node_modules/chai/index.mjs @@ -0,0 +1,14 @@ +import chai from './index.js'; + +export const expect = chai.expect; +export const version = chai.version; +export const Assertion = chai.Assertion; +export const AssertionError = chai.AssertionError; +export const util = chai.util; +export const config = chai.config; +export const use = chai.use; +export const should = chai.should; +export const assert = chai.assert; +export const core = chai.core; + +export default chai; diff --git a/web/node_modules/chai/karma.conf.js b/web/node_modules/chai/karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..e22923fc5a5550649fc2584a5f056d7996090d77 --- /dev/null +++ b/web/node_modules/chai/karma.conf.js @@ -0,0 +1,34 @@ +module.exports = function(config) { + config.set({ + frameworks: [ 'mocha' ] + , files: [ + 'chai.js' + , 'test/bootstrap/index.js' + , 'test/*.js' + ] + , reporters: [ 'progress' ] + , colors: true + , logLevel: config.LOG_INFO + , autoWatch: false + , browsers: [ 'HeadlessChrome' ] + , customLaunchers: { + HeadlessChrome: { + base: 'ChromeHeadless' + , flags: [ '--no-sandbox',] + , } + , } + , browserDisconnectTimeout: 10000 + , browserDisconnectTolerance: 2 + , browserNoActivityTimeout: 20000 + , singleRun: true + }); + + switch (process.env.CHAI_TEST_ENV) { + case 'sauce': + require('./karma.sauce')(config); + break; + default: + // ... + break; + }; +}; diff --git a/web/node_modules/chai/karma.sauce.js b/web/node_modules/chai/karma.sauce.js new file mode 100644 index 0000000000000000000000000000000000000000..b4f22fe069a63c0f0b5bb7ea868f2d8c9c14b06a --- /dev/null +++ b/web/node_modules/chai/karma.sauce.js @@ -0,0 +1,41 @@ +var version = require('./package.json').version; +var ts = new Date().getTime(); + +module.exports = function(config) { + var auth; + + try { + auth = require('./test/auth/index'); + } catch(ex) { + auth = {}; + auth.SAUCE_USERNAME = process.env.SAUCE_USERNAME || null; + auth.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY || null; + } + + if (!auth.SAUCE_USERNAME || !auth.SAUCE_ACCESS_KEY) return; + if (process.env.SKIP_SAUCE) return; + + var branch = process.env.TRAVIS_BRANCH || 'local' + var browserConfig = require('./sauce.browsers'); + var browsers = Object.keys(browserConfig); + var tags = [ 'chaijs_' + version, auth.SAUCE_USERNAME + '@' + branch ]; + var tunnel = process.env.TRAVIS_JOB_NUMBER || ts; + + if (process.env.TRAVIS_JOB_NUMBER) { + tags.push('travis@' + process.env.TRAVIS_JOB_NUMBER); + } + + config.browsers = config.browsers.concat(browsers); + Object.assign(config.customLaunchers, browserConfig); + config.reporters.push('saucelabs'); + config.captureTimeout = 300000; + + config.sauceLabs = { + username: auth.SAUCE_USERNAME + , accessKey: auth.SAUCE_ACCESS_KEY + , startConnect: ('TRAVIS' in process.env) === false + , tags: tags + , testName: 'ChaiJS' + , tunnelIdentifier: tunnel + }; +}; diff --git a/web/node_modules/chai/lib/chai.js b/web/node_modules/chai/lib/chai.js new file mode 100644 index 0000000000000000000000000000000000000000..960d83c2b8c8eaff9eb87566e0775668850ea011 --- /dev/null +++ b/web/node_modules/chai/lib/chai.js @@ -0,0 +1,92 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var used = []; + +/*! + * Chai version + */ + +exports.version = '4.3.8'; + +/*! + * Assertion Error + */ + +exports.AssertionError = require('assertion-error'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('./chai/utils'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai. + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(exports, util); + used.push(fn); + } + + return exports; +}; + +/*! + * Utility Functions + */ + +exports.util = util; + +/*! + * Configuration + */ + +var config = require('./chai/config'); +exports.config = config; + +/*! + * Primary `Assertion` prototype + */ + +var assertion = require('./chai/assertion'); +exports.use(assertion); + +/*! + * Core Assertions + */ + +var core = require('./chai/core/assertions'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('./chai/interface/expect'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('./chai/interface/should'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('./chai/interface/assert'); +exports.use(assert); diff --git a/web/node_modules/chai/lib/chai/assertion.js b/web/node_modules/chai/lib/chai/assertion.js new file mode 100644 index 0000000000000000000000000000000000000000..32e7ee2bb849db16f0a6c469859ccfedf2c4ead0 --- /dev/null +++ b/web/node_modules/chai/lib/chai/assertion.js @@ -0,0 +1,178 @@ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var config = require('./config'); + +module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * - `eql`: This flag contains the deepEqual function to be used by the assertion. + * + * @param {Mixed} obj target of the assertion + * @param {String} msg (optional) custom error message + * @param {Function} ssfi (optional) starting point for removing stack frames + * @param {Boolean} lockSsfi (optional) whether or not the ssfi flag is locked + * @api private + */ + + function Assertion (obj, msg, ssfi, lockSsfi) { + flag(this, 'ssfi', ssfi || Assertion); + flag(this, 'lockSsfi', lockSsfi); + flag(this, 'object', obj); + flag(this, 'message', msg); + flag(this, 'eql', config.deepEqual || util.eql); + + return util.proxify(this); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String|Function} message or function that returns message to display if expression fails + * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (false !== showDiff) showDiff = true; + if (undefined === expected && undefined === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + msg = util.getMessage(this, arguments); + var actual = util.getActual(this, arguments); + var assertionErrorObjectProperties = { + actual: actual + , expected: expected + , showDiff: showDiff + }; + + var operator = util.getOperator(this, arguments); + if (operator) { + assertionErrorObjectProperties.operator = operator; + } + + throw new AssertionError( + msg, + assertionErrorObjectProperties, + (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); +}; diff --git a/web/node_modules/chai/lib/chai/config.js b/web/node_modules/chai/lib/chai/config.js new file mode 100644 index 0000000000000000000000000000000000000000..d7cbdb9d97a8cfcf32beb95672039ce721ded443 --- /dev/null +++ b/web/node_modules/chai/lib/chai/config.js @@ -0,0 +1,120 @@ +module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40, + + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {Boolean} + * @api public + */ + + useProxy: true, + + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @api public + */ + + proxyExcludedKeys: ['then', 'catch', 'inspect', 'toJSON'], + + /** + * ### config.deepEqual + * + * User configurable property, defines which a custom function to use for deepEqual + * comparisons. + * By default, the function used is the one from the `deep-eql` package without custom comparator. + * + * // use a custom comparator + * chai.config.deepEqual = (expected, actual) => { + * return chai.util.eql(expected, actual, { + * comparator: (expected, actual) => { + * // for non number comparison, use the default behavior + * if(typeof expected !== 'number') return null; + * // allow a difference of 10 between compared numbers + * return typeof actual === 'number' && Math.abs(actual - expected) < 10 + * } + * }) + * }; + * + * @param {Function} + * @api public + */ + + deepEqual: null + +}; diff --git a/web/node_modules/chai/lib/chai/core/assertions.js b/web/node_modules/chai/lib/chai/core/assertions.js new file mode 100644 index 0000000000000000000000000000000000000000..19bdbbc55713a6d8c5f5657af536e9d920a43f72 --- /dev/null +++ b/web/node_modules/chai/lib/chai/core/assertions.js @@ -0,0 +1,3850 @@ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, _) { + var Assertion = chai.Assertion + , AssertionError = chai.AssertionError + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to improve the readability + * of your assertions. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * - but + * - does + * - still + * - also + * + * @name language chains + * @namespace BDD + * @api public + */ + + [ 'to', 'be', 'been', 'is' + , 'and', 'has', 'have', 'with' + , 'that', 'which', 'at', 'of' + , 'same', 'but', 'does', 'still', "also" ].forEach(function (chain) { + Assertion.addProperty(chain); + }); + + /** + * ### .not + * + * Negates all assertions that follow in the chain. + * + * expect(function () {}).to.not.throw(); + * expect({a: 1}).to.not.have.property('b'); + * expect([1, 2]).to.be.an('array').that.does.not.include(3); + * + * Just because you can negate any assertion with `.not` doesn't mean you + * should. With great power comes great responsibility. It's often best to + * assert that the one expected output was produced, rather than asserting + * that one of countless unexpected outputs wasn't produced. See individual + * assertions for specific guidance. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.equal(1); // Not recommended + * + * @name not + * @namespace BDD + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` + * assertions that follow in the chain to use deep equality instead of strict + * (`===`) equality. See the `deep-eql` project page for info on the deep + * equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * @name deep + * @namespace BDD + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .nested + * + * Enables dot- and bracket-notation in all `.property` and `.include` + * assertions that follow in the chain. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); + * + * `.nested` cannot be combined with `.own`. + * + * @name nested + * @namespace BDD + * @api public + */ + + Assertion.addProperty('nested', function () { + flag(this, 'nested', true); + }); + + /** + * ### .own + * + * Causes all `.property` and `.include` assertions that follow in the chain + * to ignore inherited properties. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * `.own` cannot be combined with `.nested`. + * + * @name own + * @namespace BDD + * @api public + */ + + Assertion.addProperty('own', function () { + flag(this, 'own', true); + }); + + /** + * ### .ordered + * + * Causes all `.members` assertions that follow in the chain to require that + * members be in the same order. + * + * expect([1, 2]).to.have.ordered.members([1, 2]) + * .but.not.have.ordered.members([2, 1]); + * + * When `.include` and `.ordered` are combined, the ordering begins at the + * start of both arrays. + * + * expect([1, 2, 3]).to.include.ordered.members([1, 2]) + * .but.not.include.ordered.members([2, 3]); + * + * @name ordered + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ordered', function () { + flag(this, 'ordered', true); + }); + + /** + * ### .any + * + * Causes all `.keys` assertions that follow in the chain to only require that + * the target have at least one of the given keys. This is the opposite of + * `.all`, which requires that the target have all of the given keys. + * + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name any + * @namespace BDD + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false); + }); + + /** + * ### .all + * + * Causes all `.keys` assertions that follow in the chain to require that the + * target have all of the given keys. This is the opposite of `.any`, which + * only requires that the target have at least one of the given keys. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` are + * added earlier in the chain. However, it's often best to add `.all` anyway + * because it improves readability. + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name all + * @namespace BDD + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type[, msg]) + * + * Asserts that the target's type is equal to the given string `type`. Types + * are case insensitive. See the `type-detect` project page for info on the + * type detection algorithm: https://github.com/chaijs/type-detect. + * + * expect('foo').to.be.a('string'); + * expect({a: 1}).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * expect(new Error).to.be.an('error'); + * expect(Promise.resolve()).to.be.a('promise'); + * expect(new Float32Array).to.be.a('float32array'); + * expect(Symbol()).to.be.a('symbol'); + * + * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. + * + * var myObj = { + * [Symbol.toStringTag]: 'myCustomType' + * }; + * + * expect(myObj).to.be.a('myCustomType').but.not.an('object'); + * + * It's often best to use `.a` to check a target's type before making more + * assertions on the same target. That way, you avoid unexpected behavior from + * any assertion that does different things based on the target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.a`. However, it's often best to + * assert that the target is the expected type, rather than asserting that it + * isn't one of many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.an('array'); // Not recommended + * + * `.a` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * expect(1).to.be.a('string', 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.a('string'); + * + * `.a` can also be used as a language chain to improve the readability of + * your assertions. + * + * expect({b: 2}).to.have.a.property('b'); + * + * The alias `.an` can be used interchangeably with `.a`. + * + * @name a + * @alias an + * @param {String} type + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj).toLowerCase() + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(val[, msg]) + * + * When the target is a string, `.include` asserts that the given string `val` + * is a substring of the target. + * + * expect('foobar').to.include('foo'); + * + * When the target is an array, `.include` asserts that the given `val` is a + * member of the target. + * + * expect([1, 2, 3]).to.include(2); + * + * When the target is an object, `.include` asserts that the given object + * `val`'s properties are a subset of the target's properties. + * + * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); + * + * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a + * member of the target. SameValueZero equality algorithm is used. + * + * expect(new Set([1, 2])).to.include(2); + * + * When the target is a Map, `.include` asserts that the given `val` is one of + * the values of the target. SameValueZero equality algorithm is used. + * + * expect(new Map([['a', 1], ['b', 2]])).to.include(2); + * + * Because `.include` does different things based on the target's type, it's + * important to check the target's type before using `.include`. See the `.a` + * doc for info on testing a target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * + * By default, strict (`===`) equality is used to compare array members and + * object properties. Add `.deep` earlier in the chain to use deep equality + * instead (WeakSet targets are not supported). See the `deep-eql` project + * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * By default, all of the target's properties are searched when working with + * objects. This includes properties that are inherited and/or non-enumerable. + * Add `.own` earlier in the chain to exclude the target's inherited + * properties from the search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * Note that a target object is always only searched for `val`'s own + * enumerable properties. + * + * `.deep` and `.own` can be combined. + * + * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.include`. + * + * expect('foobar').to.not.include('taco'); + * expect([1, 2, 3]).to.not.include(4); + * + * However, it's dangerous to negate `.include` when the target is an object. + * The problem is that it creates uncertain expectations by asserting that the + * target object doesn't have all of `val`'s key/value pairs but may or may + * not have some of them. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target object isn't even expected to have `val`'s keys, it's + * often best to assert exactly that. + * + * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended + * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended + * + * When the target object is expected to have `val`'s keys, it's often best to + * assert that each of the properties has its expected value, rather than + * asserting that each property doesn't have one of many unexpected values. + * + * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended + * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended + * + * `.include` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.include(4); + * + * `.include` can also be used as a language chain, causing all `.members` and + * `.keys` assertions that follow in the chain to require the target to be a + * superset of the expected set, rather than an identical set. Note that + * `.members` ignores duplicates in the subset when `.include` is added. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * Note that adding `.any` earlier in the chain causes the `.keys` assertion + * to ignore `.include`. + * + * // Both assertions are identical + * expect({a: 1}).to.include.any.keys('a', 'b'); + * expect({a: 1}).to.have.any.keys('a', 'b'); + * + * The aliases `.includes`, `.contain`, and `.contains` can be used + * interchangeably with `.include`. + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function SameValueZero(a, b) { + return (_.isNaN(a) && _.isNaN(b)) || a === b; + } + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + if (msg) flag(this, 'message', msg); + + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , descriptor = isDeep ? 'deep ' : '' + , isEql = isDeep ? flag(this, 'eql') : SameValueZero; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + var included = false; + + switch (objType) { + case 'string': + included = obj.indexOf(val) !== -1; + break; + + case 'weakset': + if (isDeep) { + throw new AssertionError( + flagMsg + 'unable to use .deep.include with WeakSet', + undefined, + ssfi + ); + } + + included = obj.has(val); + break; + + case 'map': + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + break; + + case 'set': + if (isDeep) { + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + } else { + included = obj.has(val); + } + break; + + case 'array': + if (isDeep) { + included = obj.some(function (item) { + return isEql(item, val); + }) + } else { + included = obj.indexOf(val) !== -1; + } + break; + + default: + // This block is for asserting a subset of properties in an object. + // `_.expectTypes` isn't used here because `.include` should work with + // objects with a custom `@@toStringTag`. + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + 'the given combination of arguments (' + + objType + ' and ' + + _.type(val).toLowerCase() + ')' + + ' is invalid for this assertion. ' + + 'You can use an array, a map, an object, a set, a string, ' + + 'or a weakset instead of a ' + + _.type(val).toLowerCase(), + undefined, + ssfi + ); + } + + var props = Object.keys(val) + , firstErr = null + , numErrs = 0; + + props.forEach(function (prop) { + var propAssertion = new Assertion(obj); + _.transferFlags(this, propAssertion, true); + flag(propAssertion, 'lockSsfi', true); + + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!_.checkError.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + + // When validating .not.include with multiple properties, we only want + // to throw an assertion error if all of the properties are included, + // in which case we throw the first property assertion error that we + // encountered. + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + + // Assert inclusion in collection or substring in a string. + this.assert( + included + , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) + , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is a truthy value (considered `true` in boolean context). + * However, it's often best to assert that the target is strictly (`===`) or + * deeply equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.ok; // Not recommended + * + * expect(true).to.be.true; // Recommended + * expect(true).to.be.ok; // Not recommended + * + * Add `.not` earlier in the chain to negate `.ok`. + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.not.be.ok; // Not recommended + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.ok; // Not recommended + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.be.ok; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.be.ok; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.ok; + * + * @name ok + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is strictly (`===`) equal to `true`. + * + * expect(true).to.be.true; + * + * Add `.not` earlier in the chain to negate `.true`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `true`. + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.true; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.true; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.true; + * + * @name true + * @namespace BDD + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , flag(this, 'negate') ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is strictly (`===`) equal to `false`. + * + * expect(false).to.be.false; + * + * Add `.not` earlier in the chain to negate `.false`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `false`. + * + * expect(true).to.be.true; // Recommended + * expect(true).to.not.be.false; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.false; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(true, 'nooo why fail??').to.be.false; + * + * @name false + * @namespace BDD + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , flag(this, 'negate') ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is strictly (`===`) equal to `null`. + * + * expect(null).to.be.null; + * + * Add `.not` earlier in the chain to negate `.null`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `null`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.null; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.null; + * + * @name null + * @namespace BDD + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is strictly (`===`) equal to `undefined`. + * + * expect(undefined).to.be.undefined; + * + * Add `.not` earlier in the chain to negate `.undefined`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `undefined`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.undefined; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.undefined; + * + * @name undefined + * @namespace BDD + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .NaN + * + * Asserts that the target is exactly `NaN`. + * + * expect(NaN).to.be.NaN; + * + * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `NaN`. + * + * expect('foo').to.equal('foo'); // Recommended + * expect('foo').to.not.be.NaN; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.NaN; + * + * @name NaN + * @namespace BDD + * @api public + */ + + Assertion.addProperty('NaN', function () { + this.assert( + _.isNaN(flag(this, 'object')) + , 'expected #{this} to be NaN' + , 'expected #{this} not to be NaN' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is not strictly (`===`) equal to either `null` or + * `undefined`. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.exist; // Not recommended + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.exist; // Not recommended + * + * Add `.not` earlier in the chain to negate `.exist`. + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.exist; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.exist; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(null, 'nooo why fail??').to.exist; + * + * The alias `.exists` can be used interchangeably with `.exist`. + * + * @name exist + * @alias exists + * @namespace BDD + * @api public + */ + + function assertExist () { + var val = flag(this, 'object'); + this.assert( + val !== null && val !== undefined + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + } + + Assertion.addProperty('exist', assertExist); + Assertion.addProperty('exists', assertExist); + + /** + * ### .empty + * + * When the target is a string or array, `.empty` asserts that the target's + * `length` property is strictly (`===`) equal to `0`. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * + * When the target is a map or set, `.empty` asserts that the target's `size` + * property is strictly equal to `0`. + * + * expect(new Set()).to.be.empty; + * expect(new Map()).to.be.empty; + * + * When the target is a non-function object, `.empty` asserts that the target + * doesn't have any own enumerable properties. Properties with Symbol-based + * keys are excluded from the count. + * + * expect({}).to.be.empty; + * + * Because `.empty` does different things based on the target's type, it's + * important to check the target's type before using `.empty`. See the `.a` + * doc for info on testing a target's type. + * + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.empty`. However, it's often + * best to assert that the target contains its expected number of values, + * rather than asserting that it's not empty. + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.not.be.empty; // Not recommended + * + * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended + * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended + * + * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended + * expect({a: 1}).to.not.be.empty; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect([1, 2, 3], 'nooo why fail??').to.be.empty; + * + * @name empty + * @namespace BDD + * @api public + */ + + Assertion.addProperty('empty', function () { + var val = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , itemsCount; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + switch (_.type(val).toLowerCase()) { + case 'array': + case 'string': + itemsCount = val.length; + break; + case 'map': + case 'set': + itemsCount = val.size; + break; + case 'weakmap': + case 'weakset': + throw new AssertionError( + flagMsg + '.empty was passed a weak collection', + undefined, + ssfi + ); + case 'function': + var msg = flagMsg + '.empty was passed a function ' + _.getName(val); + throw new AssertionError(msg.trim(), undefined, ssfi); + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), + undefined, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + + this.assert( + 0 === itemsCount + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an `arguments` object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * test(); + * + * Add `.not` earlier in the chain to negate `.arguments`. However, it's often + * best to assert which type the target is expected to be, rather than + * asserting that it’s not an `arguments` object. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.arguments; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({}, 'nooo why fail??').to.be.arguments; + * + * The alias `.Arguments` can be used interchangeably with `.arguments`. + * + * @name arguments + * @alias Arguments + * @namespace BDD + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = _.type(obj); + this.assert( + 'Arguments' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(val[, msg]) + * + * Asserts that the target is strictly (`===`) equal to the given `val`. + * + * expect(1).to.equal(1); + * expect('foo').to.equal('foo'); + * + * Add `.deep` earlier in the chain to use deep equality instead. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) equals `[1, 2]` + * expect([1, 2]).to.deep.equal([1, 2]); + * expect([1, 2]).to.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.equal`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to one of countless unexpected values. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.equal(2); // Not recommended + * + * `.equal` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.equal(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.equal(2); + * + * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. + * + * @name equal + * @alias equals + * @alias eq + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + var prevLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + this.eql(val); + flag(this, 'lockSsfi', prevLockSsfi); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(obj[, msg]) + * + * Asserts that the target is deeply equal to the given `obj`. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object is deeply (but not strictly) equal to {a: 1} + * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); + * + * // Target array is deeply (but not strictly) equal to [1, 2] + * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.eql`. However, it's often best + * to assert that the target is deeply equal to its expected value, rather + * than not deeply equal to one of countless unexpected values. + * + * expect({a: 1}).to.eql({a: 1}); // Recommended + * expect({a: 1}).to.not.eql({b: 2}); // Not recommended + * + * `.eql` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); + * + * The alias `.eqls` can be used interchangeably with `.eql`. + * + * The `.deep.equal` assertion is almost identical to `.eql` but with one + * difference: `.deep.equal` causes deep equality comparisons to also be used + * for any other assertions that follow in the chain. + * + * @name eql + * @alias eqls + * @param {Mixed} obj + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + var eql = flag(this, 'eql'); + this.assert( + eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(n[, msg]) + * + * Asserts that the target is a number or a date greater than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.above(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.above(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.above`. + * + * expect(2).to.equal(2); // Recommended + * expect(1).to.not.be.above(2); // Not recommended + * + * `.above` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.above(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.above(2); + * + * The aliases `.gt` and `.greaterThan` can be used interchangeably with + * `.above`. + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to above must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to above must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n + , 'expected #{this} to have a ' + descriptor + ' above #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above #{exp}' + , 'expected #{this} to be at most #{exp}' + , n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(n[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `n` respectively. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.at.least(1); // Not recommended + * expect(2).to.be.at.least(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.least(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.least`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.at.least(2); // Not recommended + * + * `.least` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.at.least(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.at.least(2); + * + * The aliases `.gte` and `.greaterThanOrEqual` can be used interchangeably with + * `.least`. + * + * @name least + * @alias gte + * @alias greaterThanOrEqual + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to least must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to least must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n + , 'expected #{this} to have a ' + descriptor + ' at least #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least #{exp}' + , 'expected #{this} to be below #{exp}' + , n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + Assertion.addMethod('greaterThanOrEqual', assertLeast); + + /** + * ### .below(n[, msg]) + * + * Asserts that the target is a number or a date less than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.below(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.below(4); // Not recommended + * + * expect([1, 2, 3]).to.have.length(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.below`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.below(1); // Not recommended + * + * `.below` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.below(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.below(1); + * + * The aliases `.lt` and `.lessThan` can be used interchangeably with + * `.below`. + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to below must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to below must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n + , 'expected #{this} to have a ' + descriptor + ' below #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below #{exp}' + , 'expected #{this} to be at least #{exp}' + , n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(n[, msg]) + * + * Asserts that the target is a number or a date less than or equal to the given number + * or date `n` respectively. However, it's often best to assert that the target is equal to its + * expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.at.most(2); // Not recommended + * expect(1).to.be.at.most(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.most(4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.most`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.at.most(1); // Not recommended + * + * `.most` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.at.most(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.at.most(1); + * + * The aliases `.lte` and `.lessThanOrEqual` can be used interchangeably with + * `.most`. + * + * @name most + * @alias lte + * @alias lessThanOrEqual + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to most must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to most must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n + , 'expected #{this} to have a ' + descriptor + ' at most #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most #{exp}' + , 'expected #{this} to be above #{exp}' + , n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + Assertion.addMethod('lessThanOrEqual', assertMost); + + /** + * ### .within(start, finish[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `start`, and less than or equal to the given number or date `finish` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.within(1, 3); // Not recommended + * expect(2).to.be.within(2, 3); // Not recommended + * expect(2).to.be.within(1, 2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `start`, and less + * than or equal to the given number `finish`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.within`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.within(2, 4); // Not recommended + * + * `.within` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(4).to.be.within(1, 3, 'nooo why fail??'); + * expect(4, 'nooo why fail??').to.be.within(1, 3); + * + * @name within + * @param {Number} start lower bound inclusive + * @param {Number} finish upper bound inclusive + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , startType = _.type(start).toLowerCase() + , finishType = _.type(finish).toLowerCase() + , errorMessage + , shouldThrow = true + , range = (startType === 'date' && finishType === 'date') + ? start.toISOString() + '..' + finish.toISOString() + : start + '..' + finish; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { + errorMessage = msgPrefix + 'the arguments to within must be dates'; + } else if ((startType !== 'number' || finishType !== 'number') && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the arguments to within must be numbers'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish + , 'expected #{this} to have a ' + descriptor + ' within ' + range + , 'expected #{this} to not have a ' + descriptor + ' within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor[, msg]) + * + * Asserts that the target is an instance of the given `constructor`. + * + * function Cat () { } + * + * expect(new Cat()).to.be.an.instanceof(Cat); + * expect([1, 2]).to.be.an.instanceof(Array); + * + * Add `.not` earlier in the chain to negate `.instanceof`. + * + * expect({a: 1}).to.not.be.an.instanceof(Array); + * + * `.instanceof` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); + * + * Due to limitations in ES5, `.instanceof` may not always work as expected + * when using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing built-in object such as + * `Array`, `Error`, and `Map`. See your transpiler's docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * The alias `.instanceOf` can be used interchangeably with `.instanceof`. + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} msg _optional_ + * @alias instanceOf + * @namespace BDD + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + + var target = flag(this, 'object') + var ssfi = flag(this, 'ssfi'); + var flagMsg = flag(this, 'message'); + + try { + var isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'The instanceof assertion needs a constructor but ' + + _.type(constructor) + ' was given.', + undefined, + ssfi + ); + } + throw err; + } + + var name = _.getName(constructor); + if (name === null) { + name = 'an unnamed constructor'; + } + + this.assert( + isInstanceOf + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name[, val[, msg]]) + * + * Asserts that the target has a property with the given key `name`. + * + * expect({a: 1}).to.have.property('a'); + * + * When `val` is provided, `.property` also asserts that the property's value + * is equal to the given `val`. + * + * expect({a: 1}).to.have.property('a', 1); + * + * By default, strict (`===`) equality is used. Add `.deep` earlier in the + * chain to use deep equality instead. See the `deep-eql` project page for + * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * The target's enumerable and non-enumerable properties are always included + * in the search. By default, both own and inherited properties are included. + * Add `.own` earlier in the chain to exclude inherited properties from the + * search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.own.property('a', 1); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * `.deep` and `.own` can be combined. + * + * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}) + * .to.have.deep.nested.property('a.b[0]', {c: 3}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.property`. + * + * expect({a: 1}).to.not.have.property('b'); + * + * However, it's dangerous to negate `.property` when providing `val`. The + * problem is that it creates uncertain expectations by asserting that the + * target either doesn't have a property with the given key `name`, or that it + * does have a property with the given key `name` but its value isn't equal to + * the given `val`. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target isn't expected to have a property with the given key + * `name`, it's often best to assert exactly that. + * + * expect({b: 2}).to.not.have.property('a'); // Recommended + * expect({b: 2}).to.not.have.property('a', 1); // Not recommended + * + * When the target is expected to have a property with the given key `name`, + * it's often best to assert that the property has its expected value, rather + * than asserting that it doesn't have one of many unexpected values. + * + * expect({a: 3}).to.have.property('a', 3); // Recommended + * expect({a: 3}).to.not.have.property('a', 1); // Not recommended + * + * `.property` changes the target of any assertions that follow in the chain + * to be the value of the property from the original target object. + * + * expect({a: 1}).to.have.property('a').that.is.a('number'); + * + * `.property` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing `val`, only use the + * second form. + * + * // Recommended + * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); + * expect({a: 1}, 'nooo why fail??').to.have.property('b'); + * + * // Not recommended + * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `val`. Instead, + * it's asserting that the target object has a `b` property that's equal to + * `undefined`. + * + * The assertions `.ownProperty` and `.haveOwnProperty` can be used + * interchangeably with `.own.property`. + * + * @name property + * @param {String} name + * @param {Mixed} val (optional) + * @param {String} msg _optional_ + * @returns value of property for chaining + * @namespace BDD + * @api public + */ + + function assertProperty (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isNested = flag(this, 'nested') + , isOwn = flag(this, 'own') + , flagMsg = flag(this, 'message') + , obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , nameType = typeof name; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + if (isNested) { + if (nameType !== 'string') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string when using nested syntax', + undefined, + ssfi + ); + } + } else { + if (nameType !== 'string' && nameType !== 'number' && nameType !== 'symbol') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string, number, or symbol', + undefined, + ssfi + ); + } + } + + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + undefined, + ssfi + ); + } + + if (obj === null || obj === undefined) { + throw new AssertionError( + flagMsg + 'Target cannot be null or undefined.', + undefined, + ssfi + ); + } + + var isDeep = flag(this, 'deep') + , negate = flag(this, 'negate') + , pathInfo = isNested ? _.getPathInfo(obj, name) : null + , value = isNested ? pathInfo.value : obj[name] + , isEql = isDeep ? flag(this, 'eql') : (val1, val2) => val1 === val2;; + + var descriptor = ''; + if (isDeep) descriptor += 'deep '; + if (isOwn) descriptor += 'own '; + if (isNested) descriptor += 'nested '; + descriptor += 'property '; + + var hasProperty; + if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty = pathInfo.exists; + else hasProperty = _.hasProperty(obj, name); + + // When performing a negated assertion for both name and val, merely having + // a property with the given name isn't enough to cause the assertion to + // fail. It must both have a property with the given name, and the value of + // that property must equal the given val. Therefore, skip this assertion in + // favor of the next. + if (!negate || arguments.length === 1) { + this.assert( + hasProperty + , 'expected #{this} to have ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (arguments.length > 1) { + this.assert( + hasProperty && isEql(val, value) + , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + } + + Assertion.addMethod('property', assertProperty); + + function assertOwnProperty (name, value, msg) { + flag(this, 'own', true); + assertProperty.apply(this, arguments); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) + * + * Asserts that the target has its own property descriptor with the given key + * `name`. Enumerable and non-enumerable properties are included in the + * search. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a'); + * + * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that + * the property's descriptor is deeply equal to the given `descriptor`. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. + * + * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); + * + * However, it's dangerous to negate `.ownPropertyDescriptor` when providing + * a `descriptor`. The problem is that it creates uncertain expectations by + * asserting that the target either doesn't have a property descriptor with + * the given key `name`, or that it does have a property descriptor with the + * given key `name` but it’s not deeply equal to the given `descriptor`. It's + * often best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to have a property descriptor with the given + * key `name`, it's often best to assert exactly that. + * + * // Recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); + * + * // Not recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * When the target is expected to have a property descriptor with the given + * key `name`, it's often best to assert that the property has its expected + * descriptor, rather than asserting that it doesn't have one of many + * unexpected descriptors. + * + * // Recommended + * expect({a: 3}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 3, + * }); + * + * // Not recommended + * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * `.ownPropertyDescriptor` changes the target of any assertions that follow + * in the chain to be the value of the property descriptor from the original + * target object. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a') + * .that.has.property('enumerable', true); + * + * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a + * custom error message to show when the assertion fails. The message can also + * be given as the second argument to `expect`. When not providing + * `descriptor`, only use the second form. + * + * // Recommended + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }, 'nooo why fail??'); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); + * + * // Not recommended + * expect({a: 1}) + * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `descriptor`. + * Instead, it's asserting that the target object has a `b` property + * descriptor that's deeply equal to `undefined`. + * + * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with + * `.ownPropertyDescriptor`. + * + * @name ownPropertyDescriptor + * @alias haveOwnPropertyDescriptor + * @param {String} name + * @param {Object} descriptor _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertOwnPropertyDescriptor (name, descriptor, msg) { + if (typeof descriptor === 'string') { + msg = descriptor; + descriptor = null; + } + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + var eql = flag(this, 'eql'); + if (actualDescriptor && descriptor) { + this.assert( + eql(descriptor, actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) + , descriptor + , actualDescriptor + , true + ); + } else { + this.assert( + actualDescriptor + , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) + , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) + ); + } + flag(this, 'object', actualDescriptor); + } + + Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); + Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); + + /** + * ### .lengthOf(n[, msg]) + * + * Asserts that the target's `length` or `size` is equal to the given number + * `n`. + * + * expect([1, 2, 3]).to.have.lengthOf(3); + * expect('foo').to.have.lengthOf(3); + * expect(new Set([1, 2, 3])).to.have.lengthOf(3); + * expect(new Map([['a', 1], ['b', 2], ['c', 3]])).to.have.lengthOf(3); + * + * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often + * best to assert that the target's `length` property is equal to its expected + * value, rather than not equal to one of many unexpected values. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.not.have.lengthOf(4); // Not recommended + * + * `.lengthOf` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); + * + * `.lengthOf` can also be used as a language chain, causing all `.above`, + * `.below`, `.least`, `.most`, and `.within` assertions that follow in the + * chain to use the target's `length` property as the target. However, it's + * often best to assert that the target's `length` property is equal to its + * expected length, rather than asserting that its `length` property falls + * within some range of values. + * + * // Recommended + * expect([1, 2, 3]).to.have.lengthOf(3); + * + * // Not recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); + * expect([1, 2, 3]).to.have.lengthOf.below(4); + * expect([1, 2, 3]).to.have.lengthOf.at.least(3); + * expect([1, 2, 3]).to.have.lengthOf.at.most(3); + * expect([1, 2, 3]).to.have.lengthOf.within(2,4); + * + * Due to a compatibility issue, the alias `.length` can't be chained directly + * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used + * interchangeably with `.lengthOf` in every situation. It's recommended to + * always use `.lengthOf` instead of `.length`. + * + * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error + * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected + * + * @name lengthOf + * @alias length + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , descriptor = 'length' + , itemsCount; + + switch (objType) { + case 'map': + case 'set': + descriptor = 'size'; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + itemsCount = obj.length; + } + + this.assert( + itemsCount == n + , 'expected #{this} to have a ' + descriptor + ' of #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' of #{act}' + , n + , itemsCount + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); + + /** + * ### .match(re[, msg]) + * + * Asserts that the target matches the given regular expression `re`. + * + * expect('foobar').to.match(/^foo/); + * + * Add `.not` earlier in the chain to negate `.match`. + * + * expect('foobar').to.not.match(/taco/); + * + * `.match` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect('foobar').to.match(/taco/, 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.match(/taco/); + * + * The alias `.matches` can be used interchangeably with `.match`. + * + * @name match + * @alias matches + * @param {RegExp} re + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + function assertMatch(re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + } + + Assertion.addMethod('match', assertMatch); + Assertion.addMethod('matches', assertMatch); + + /** + * ### .string(str[, msg]) + * + * Asserts that the target string contains the given substring `str`. + * + * expect('foobar').to.have.string('bar'); + * + * Add `.not` earlier in the chain to negate `.string`. + * + * expect('foobar').to.not.have.string('taco'); + * + * `.string` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect('foobar').to.have.string('taco', 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.have.string('taco'); + * + * @name string + * @param {String} str + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(obj, flagMsg, ssfi, true).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + /** + * ### .keys(key1[, key2[, ...]]) + * + * Asserts that the target object, array, map, or set has the given keys. Only + * the target's own inherited properties are included in the search. + * + * When the target is an object or array, keys can be provided as one or more + * string arguments, a single array argument, or a single object argument. In + * the latter case, only the keys in the given object matter; the values are + * ignored. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * expect(['x', 'y']).to.have.all.keys(0, 1); + * + * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); + * expect(['x', 'y']).to.have.all.keys([0, 1]); + * + * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 + * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 + * + * When the target is a map or set, each key must be provided as a separate + * argument. + * + * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); + * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); + * + * Because `.keys` does different things based on the target's type, it's + * important to check the target's type before using `.keys`. See the `.a` doc + * for info on testing a target's type. + * + * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); + * + * By default, strict (`===`) equality is used to compare keys of maps and + * sets. Add `.deep` earlier in the chain to use deep equality instead. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); + * + * By default, the target must have all of the given keys and no more. Add + * `.any` earlier in the chain to only require that the target have at least + * one of the given keys. Also, add `.not` earlier in the chain to negate + * `.keys`. It's often best to add `.any` when negating `.keys`, and to use + * `.all` when asserting `.keys` without negation. + * + * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts + * exactly what's expected of the output, whereas `.not.all.keys` creates + * uncertain expectations. + * + * // Recommended; asserts that target doesn't have any of the given keys + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * // Not recommended; asserts that target doesn't have all of the given + * // keys but may or may not have some of them + * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); + * + * When asserting `.keys` without negation, `.all` is preferred because + * `.all.keys` asserts exactly what's expected of the output, whereas + * `.any.keys` creates uncertain expectations. + * + * // Recommended; asserts that target has all the given keys + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * // Not recommended; asserts that target has at least one of the given + * // keys but may or may not have more of them + * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` appear + * earlier in the chain. However, it's often best to add `.all` anyway because + * it improves readability. + * + * // Both assertions are identical + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended + * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended + * + * Add `.include` earlier in the chain to require that the target's keys be a + * superset of the expected keys, rather than identical sets. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * However, if `.any` and `.include` are combined, only the `.any` takes + * effect. The `.include` is ignored in this case. + * + * // Both assertions are identical + * expect({a: 1}).to.have.any.keys('a', 'b'); + * expect({a: 1}).to.include.any.keys('a', 'b'); + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.have.key('b'); + * + * The alias `.key` can be used interchangeably with `.keys`. + * + * @name keys + * @alias key + * @param {...String|Array|Object} keys + * @namespace BDD + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , objType = _.type(obj) + , keysType = _.type(keys) + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , str + , deepStr = '' + , actual + , ok = true + , flagMsg = flag(this, 'message'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; + + if (objType === 'Map' || objType === 'Set') { + deepStr = isDeep ? 'deeply ' : ''; + actual = []; + + // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. + obj.forEach(function (val, key) { actual.push(key) }); + + if (keysType !== 'Array') { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = _.getOwnEnumerableProperties(obj); + + switch (keysType) { + case 'Array': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + break; + case 'Object': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + + // Only stringify non-Symbols because Symbols would become "Symbol()" + keys = keys.map(function (val) { + return typeof val === 'symbol' ? val : String(val); + }); + } + + if (!keys.length) { + throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); + } + + var len = keys.length + , any = flag(this, 'any') + , all = flag(this, 'all') + , expected = keys + , isEql = isDeep ? flag(this, 'eql') : (val1, val2) => val1 === val2; + + if (!any && !all) { + all = true; + } + + // Has any + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + } + + // Has all + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + + if (!flag(this, 'contains')) { + ok = ok && keys.length == actual.length; + } + } + + // Key string + if (len > 1) { + keys = keys.map(function(key) { + return _.inspect(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(', ') + ', and ' + last; + } + if (any) { + str = keys.join(', ') + ', or ' + last; + } + } else { + str = _.inspect(keys[0]); + } + + // Form + str = (len > 1 ? 'keys ' : 'key ') + str; + + // Have / include + str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + + // Assertion + this.assert( + ok + , 'expected #{this} to ' + deepStr + str + , 'expected #{this} to not ' + deepStr + str + , expected.slice(0).sort(_.compareByInspect) + , actual.sort(_.compareByInspect) + , true + ); + } + + Assertion.addMethod('keys', assertKeys); + Assertion.addMethod('key', assertKeys); + + /** + * ### .throw([errorLike], [errMsgMatcher], [msg]) + * + * When no arguments are provided, `.throw` invokes the target function and + * asserts that an error is thrown. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(); + * + * When one argument is provided, and it's an error constructor, `.throw` + * invokes the target function and asserts that an error is thrown that's an + * instance of that error constructor. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError); + * + * When one argument is provided, and it's an error instance, `.throw` invokes + * the target function and asserts that an error is thrown that's strictly + * (`===`) equal to that error instance. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(err); + * + * When one argument is provided, and it's a string, `.throw` invokes the + * target function and asserts that an error is thrown with a message that + * contains that string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw('salmon'); + * + * When one argument is provided, and it's a regular expression, `.throw` + * invokes the target function and asserts that an error is thrown with a + * message that matches that regular expression. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(/salmon/); + * + * When two arguments are provided, and the first is an error instance or + * constructor, and the second is a string or regular expression, `.throw` + * invokes the function and asserts that an error is thrown that fulfills both + * conditions as described above. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); + * expect(badFn).to.throw(TypeError, /salmon/); + * expect(badFn).to.throw(err, 'salmon'); + * expect(badFn).to.throw(err, /salmon/); + * + * Add `.not` earlier in the chain to negate `.throw`. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); + * + * However, it's dangerous to negate `.throw` when providing any arguments. + * The problem is that it creates uncertain expectations by asserting that the + * target either doesn't throw an error, or that it throws an error but of a + * different type than the given type, or that it throws an error of the given + * type but with a message that doesn't include the given string. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to throw an error, it's often best to assert + * exactly that. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); // Recommended + * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * When the target is expected to throw an error, it's often best to assert + * that the error is of its expected type, and has a message that includes an + * expected string, rather than asserting that it doesn't have one of many + * unexpected types, and doesn't have a message that includes some string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended + * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * `.throw` changes the target of any assertions that follow in the chain to + * be the error object that's thrown. + * + * var err = new TypeError('Illegal salmon!'); + * err.code = 42; + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError).with.property('code', 42); + * + * `.throw` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. When not providing two arguments, always use + * the second form. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); + * expect(goodFn, 'nooo why fail??').to.throw(); + * + * Due to limitations in ES5, `.throw` may not always work as expected when + * using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing the built-in `Error` object and + * then passing the subclassed constructor to `.throw`. See your transpiler's + * docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * Beware of some common mistakes when using the `throw` assertion. One common + * mistake is to accidentally invoke the function yourself instead of letting + * the `throw` assertion invoke the function for you. For example, when + * testing if a function named `fn` throws, provide `fn` instead of `fn()` as + * the target for the assertion. + * + * expect(fn).to.throw(); // Good! Tests `fn` as desired + * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` + * + * If you need to assert that your function `fn` throws when passed certain + * arguments, then wrap a call to `fn` inside of another function. + * + * expect(function () { fn(42); }).to.throw(); // Function expression + * expect(() => fn(42)).to.throw(); // ES6 arrow function + * + * Another common mistake is to provide an object method (or any stand-alone + * function that relies on `this`) as the target of the assertion. Doing so is + * problematic because the `this` context will be lost when the function is + * invoked by `.throw`; there's no way for it to know what `this` is supposed + * to be. There are two ways around this problem. One solution is to wrap the + * method or function call inside of another function. Another solution is to + * use `bind`. + * + * expect(function () { cat.meow(); }).to.throw(); // Function expression + * expect(() => cat.meow()).to.throw(); // ES6 arrow function + * expect(cat.meow.bind(cat)).to.throw(); // Bind + * + * Finally, it's worth mentioning that it's a best practice in JavaScript to + * only throw `Error` and derivatives of `Error` such as `ReferenceError`, + * `TypeError`, and user-defined objects that extend `Error`. No other type of + * value will generate a stack trace when initialized. With that said, the + * `throw` assertion does technically support any type of value being thrown, + * not just `Error` and its derivatives. + * + * The aliases `.throws` and `.Throw` can be used interchangeably with + * `.throw`. + * + * @name throw + * @alias throws + * @alias Throw + * @param {Error|ErrorConstructor} errorLike + * @param {String|RegExp} errMsgMatcher error message + * @param {String} msg _optional_ + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @returns error for chaining (null if no error) + * @namespace BDD + * @api public + */ + + function assertThrows (errorLike, errMsgMatcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') || false; + new Assertion(obj, flagMsg, ssfi, true).is.a('function'); + + if (errorLike instanceof RegExp || typeof errorLike === 'string') { + errMsgMatcher = errorLike; + errorLike = null; + } + + var caughtErr; + try { + obj(); + } catch (err) { + caughtErr = err; + } + + // If we have the negate flag enabled and at least one valid argument it means we do expect an error + // but we want it to match a given set of criteria + var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; + + // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible + // See Issue #551 and PR #683@GitHub + var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + var errorLikeFail = false; + var errMsgMatcherFail = false; + + // Checking if error was thrown + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + // We need this to display results correctly according to their types + var errorLikeString = 'an error'; + if (errorLike instanceof Error) { + errorLikeString = '#{exp}'; + } else if (errorLike) { + errorLikeString = _.checkError.getConstructorName(errorLike); + } + + this.assert( + caughtErr + , 'expected #{this} to throw ' + errorLikeString + , 'expected #{this} to not throw an error but #{act} was thrown' + , errorLike && errorLike.toString() + , (caughtErr instanceof Error ? + caughtErr.toString() : (typeof caughtErr === 'string' ? caughtErr : caughtErr && + _.checkError.getConstructorName(caughtErr))) + ); + } + + if (errorLike && caughtErr) { + // We should compare instances only if `errorLike` is an instance of `Error` + if (errorLike instanceof Error) { + var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); + + if (isCompatibleInstance === negate) { + // These checks were created to ensure we won't fail too soon when we've got both args and a negate + // See Issue #551 and PR #683@GitHub + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') + , errorLike.toString() + , caughtErr.toString() + ); + } + } + } + + var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + } + } + + if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { + // Here we check compatible messages + var placeholder = 'including'; + if (errMsgMatcher instanceof RegExp) { + placeholder = 'matching' + } + + var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' + , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' + , errMsgMatcher + , _.checkError.getMessage(caughtErr) + ); + } + } + } + + // If both assertions failed and both should've matched we throw an error + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + + flag(this, 'object', caughtErr); + }; + + Assertion.addMethod('throw', assertThrows); + Assertion.addMethod('throws', assertThrows); + Assertion.addMethod('Throw', assertThrows); + + /** + * ### .respondTo(method[, msg]) + * + * When the target is a non-function object, `.respondTo` asserts that the + * target has a method with the given name `method`. The method can be own or + * inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.respondTo('meow'); + * + * When the target is a function, `.respondTo` asserts that the target's + * `prototype` property has a method with the given name `method`. Again, the + * method can be own or inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(Cat).to.respondTo('meow'); + * + * Add `.itself` earlier in the chain to force `.respondTo` to treat the + * target as a non-function object, even if it's a function. Thus, it asserts + * that the target has a method with the given name `method`, rather than + * asserting that the target's `prototype` property has a method with the + * given name `method`. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * When not adding `.itself`, it's important to check the target's type before + * using `.respondTo`. See the `.a` doc for info on checking a target's type. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); + * + * Add `.not` earlier in the chain to negate `.respondTo`. + * + * function Dog () {} + * Dog.prototype.bark = function () {}; + * + * expect(new Dog()).to.not.respondTo('meow'); + * + * `.respondTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect({}).to.respondTo('meow', 'nooo why fail??'); + * expect({}, 'nooo why fail??').to.respondTo('meow'); + * + * The alias `.respondsTo` can be used interchangeably with `.respondTo`. + * + * @name respondTo + * @alias respondsTo + * @param {String} method + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function respondTo (method, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , itself = flag(this, 'itself') + , context = ('function' === typeof obj && !itself) + ? obj.prototype[method] + : obj[method]; + + this.assert( + 'function' === typeof context + , 'expected #{this} to respond to ' + _.inspect(method) + , 'expected #{this} to not respond to ' + _.inspect(method) + ); + } + + Assertion.addMethod('respondTo', respondTo); + Assertion.addMethod('respondsTo', respondTo); + + /** + * ### .itself + * + * Forces all `.respondTo` assertions that follow in the chain to behave as if + * the target is a non-function object, even if it's a function. Thus, it + * causes `.respondTo` to assert that the target has a method with the given + * name, rather than asserting that the target's `prototype` property has a + * method with the given name. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * @name itself + * @namespace BDD + * @api public + */ + + Assertion.addProperty('itself', function () { + flag(this, 'itself', true); + }); + + /** + * ### .satisfy(matcher[, msg]) + * + * Invokes the given `matcher` function with the target being passed as the + * first argument, and asserts that the value returned is truthy. + * + * expect(1).to.satisfy(function(num) { + * return num > 0; + * }); + * + * Add `.not` earlier in the chain to negate `.satisfy`. + * + * expect(1).to.not.satisfy(function(num) { + * return num > 2; + * }); + * + * `.satisfy` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.satisfy(function(num) { + * return num > 2; + * }, 'nooo why fail??'); + * + * expect(1, 'nooo why fail??').to.satisfy(function(num) { + * return num > 2; + * }); + * + * The alias `.satisfies` can be used interchangeably with `.satisfy`. + * + * @name satisfy + * @alias satisfies + * @param {Function} matcher + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function satisfy (matcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var result = matcher(obj); + this.assert( + result + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) + , flag(this, 'negate') ? false : true + , result + ); + } + + Assertion.addMethod('satisfy', satisfy); + Assertion.addMethod('satisfies', satisfy); + + /** + * ### .closeTo(expected, delta[, msg]) + * + * Asserts that the target is a number that's within a given +/- `delta` range + * of the given number `expected`. However, it's often best to assert that the + * target is equal to its expected value. + * + * // Recommended + * expect(1.5).to.equal(1.5); + * + * // Not recommended + * expect(1.5).to.be.closeTo(1, 0.5); + * expect(1.5).to.be.closeTo(2, 0.5); + * expect(1.5).to.be.closeTo(1, 1); + * + * Add `.not` earlier in the chain to negate `.closeTo`. + * + * expect(1.5).to.equal(1.5); // Recommended + * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended + * + * `.closeTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); + * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); + * + * The alias `.approximately` can be used interchangeably with `.closeTo`. + * + * @name closeTo + * @alias approximately + * @param {Number} expected + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function closeTo(expected, delta, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).is.a('number'); + if (typeof expected !== 'number' || typeof delta !== 'number') { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var deltaMessage = delta === undefined ? ", and a delta is required" : ""; + throw new AssertionError( + flagMsg + 'the arguments to closeTo or approximately must be numbers' + deltaMessage, + undefined, + ssfi + ); + } + + this.assert( + Math.abs(obj - expected) <= delta + , 'expected #{this} to be close to ' + expected + ' +/- ' + delta + , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta + ); + } + + Assertion.addMethod('closeTo', closeTo); + Assertion.addMethod('approximately', closeTo); + + // Note: Duplicates are ignored if testing for inclusion instead of sameness. + function isSubsetOf(subset, superset, cmp, contains, ordered) { + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + + if (!cmp) { + var matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + } + + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); + } + + /** + * ### .members(set[, msg]) + * + * Asserts that the target array has the same members as the given array + * `set`. + * + * expect([1, 2, 3]).to.have.members([2, 1, 3]); + * expect([1, 2, 2]).to.have.members([2, 1, 2]); + * + * By default, members are compared using strict (`===`) equality. Add `.deep` + * earlier in the chain to use deep equality instead. See the `deep-eql` + * project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * By default, order doesn't matter. Add `.ordered` earlier in the chain to + * require that members appear in the same order. + * + * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); + * expect([1, 2, 3]).to.have.members([2, 1, 3]) + * .but.not.ordered.members([2, 1, 3]); + * + * By default, both arrays must be the same size. Add `.include` earlier in + * the chain to require that the target's members be a superset of the + * expected members. Note that duplicates are ignored in the subset when + * `.include` is added. + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * `.deep`, `.ordered`, and `.include` can all be combined. However, if + * `.include` and `.ordered` are combined, the ordering begins at the start of + * both arrays. + * + * expect([{a: 1}, {b: 2}, {c: 3}]) + * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) + * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); + * + * Add `.not` earlier in the chain to negate `.members`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the target array doesn't have all of the same members as + * the given array `set` but may or may not have some of them. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended + * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended + * + * `.members` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); + * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); + * + * @name members + * @param {Array} set + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('members', function (subset, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).to.be.an('array'); + new Assertion(subset, flagMsg, ssfi, true).to.be.an('array'); + + var contains = flag(this, 'contains'); + var ordered = flag(this, 'ordered'); + + var subject, failMsg, failNegateMsg; + + if (contains) { + subject = ordered ? 'an ordered superset' : 'a superset'; + failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; + failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; + } else { + subject = ordered ? 'ordered members' : 'members'; + failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; + failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; + } + + var cmp = flag(this, 'deep') ? flag(this, 'eql') : undefined; + + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered) + , failMsg + , failNegateMsg + , subset + , obj + , true + ); + }); + + /** + * ### .oneOf(list[, msg]) + * + * Asserts that the target is a member of the given array `list`. However, + * it's often best to assert that the target is equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended + * + * Comparisons are performed using strict (`===`) equality. + * + * Add `.not` earlier in the chain to negate `.oneOf`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended + * + * It can also be chained with `.contain` or `.include`, which will work with + * both arrays and strings: + * + * expect('Today is sunny').to.contain.oneOf(['sunny', 'cloudy']) + * expect('Today is rainy').to.not.contain.oneOf(['sunny', 'cloudy']) + * expect([1,2,3]).to.contain.oneOf([3,4,5]) + * expect([1,2,3]).to.not.contain.oneOf([4,5,6]) + * + * `.oneOf` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); + * + * @name oneOf + * @param {Array<*>} list + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function oneOf (list, msg) { + if (msg) flag(this, 'message', msg); + var expected = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , contains = flag(this, 'contains') + , isDeep = flag(this, 'deep') + , eql = flag(this, 'eql'); + new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); + + if (contains) { + this.assert( + list.some(function(possibility) { return expected.indexOf(possibility) > -1 }) + , 'expected #{this} to contain one of #{exp}' + , 'expected #{this} to not contain one of #{exp}' + , list + , expected + ); + } else { + if (isDeep) { + this.assert( + list.some(function(possibility) { return eql(expected, possibility) }) + , 'expected #{this} to deeply equal one of #{exp}' + , 'expected #{this} to deeply equal one of #{exp}' + , list + , expected + ); + } else { + this.assert( + list.indexOf(expected) > -1 + , 'expected #{this} to be one of #{exp}' + , 'expected #{this} to not be one of #{exp}' + , list + , expected + ); + } + } + } + + Assertion.addMethod('oneOf', oneOf); + + /** + * ### .change(subject[, prop[, msg]]) + * + * When one argument is provided, `.change` asserts that the given function + * `subject` returns a different value when it's invoked before the target + * function compared to when it's invoked afterward. However, it's often best + * to assert that `subject` is equal to its expected value. + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * // Recommended + * expect(getDots()).to.equal(''); + * addDot(); + * expect(getDots()).to.equal('.'); + * + * // Not recommended + * expect(addDot).to.change(getDots); + * + * When two arguments are provided, `.change` asserts that the value of the + * given object `subject`'s `prop` property is different before invoking the + * target function compared to afterward. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * // Recommended + * expect(myObj).to.have.property('dots', ''); + * addDot(); + * expect(myObj).to.have.property('dots', '.'); + * + * // Not recommended + * expect(addDot).to.change(myObj, 'dots'); + * + * Strict (`===`) equality is used to compare before and after values. + * + * Add `.not` earlier in the chain to negate `.change`. + * + * var dots = '' + * , noop = function () {} + * , getDots = function () { return dots; }; + * + * expect(noop).to.not.change(getDots); + * + * var myObj = {dots: ''} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'dots'); + * + * `.change` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * expect(addDot, 'nooo why fail??').to.not.change(getDots); + * + * `.change` also causes all `.by` assertions that follow in the chain to + * assert how much a numeric subject was increased or decreased by. However, + * it's dangerous to use `.change.by`. The problem is that it creates + * uncertain expectations by asserting that the subject either increases by + * the given delta, or that it decreases by the given delta. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * The alias `.changes` can be used interchangeably with `.change`. + * + * @name change + * @alias changes + * @param {String} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertChanges (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + // This gets flagged because of the .by(delta) assertion + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'change'); + flag(this, 'realDelta', final !== initial); + + this.assert( + initial !== final + , 'expected ' + msgObj + ' to change' + , 'expected ' + msgObj + ' to not change' + ); + } + + Assertion.addMethod('change', assertChanges); + Assertion.addMethod('changes', assertChanges); + + /** + * ### .increase(subject[, prop[, msg]]) + * + * When one argument is provided, `.increase` asserts that the given function + * `subject` returns a greater number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.increase` also + * causes all `.by` assertions that follow in the chain to assert how much + * greater of a number is returned. It's often best to assert that the return + * value increased by the expected amount, rather than asserting it increased + * by any amount. + * + * var val = 1 + * , addTwo = function () { val += 2; } + * , getVal = function () { return val; }; + * + * expect(addTwo).to.increase(getVal).by(2); // Recommended + * expect(addTwo).to.increase(getVal); // Not recommended + * + * When two arguments are provided, `.increase` asserts that the value of the + * given object `subject`'s `prop` property is greater after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.increase(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.increase`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either decreases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to decrease, it's often best to assert that it + * decreased by the expected amount. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.increase(myObj, 'val'); // Not recommended + * + * `.increase` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.increase(getVal); + * + * The alias `.increases` can be used interchangeably with `.increase`. + * + * @name increase + * @alias increases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertIncreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'increase'); + flag(this, 'realDelta', final - initial); + + this.assert( + final - initial > 0 + , 'expected ' + msgObj + ' to increase' + , 'expected ' + msgObj + ' to not increase' + ); + } + + Assertion.addMethod('increase', assertIncreases); + Assertion.addMethod('increases', assertIncreases); + + /** + * ### .decrease(subject[, prop[, msg]]) + * + * When one argument is provided, `.decrease` asserts that the given function + * `subject` returns a lesser number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.decrease` also + * causes all `.by` assertions that follow in the chain to assert how much + * lesser of a number is returned. It's often best to assert that the return + * value decreased by the expected amount, rather than asserting it decreased + * by any amount. + * + * var val = 1 + * , subtractTwo = function () { val -= 2; } + * , getVal = function () { return val; }; + * + * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended + * expect(subtractTwo).to.decrease(getVal); // Not recommended + * + * When two arguments are provided, `.decrease` asserts that the value of the + * given object `subject`'s `prop` property is lesser after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.decrease`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either increases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to increase, it's often best to assert that it + * increased by the expected amount. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended + * + * `.decrease` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.decrease(getVal); + * + * The alias `.decreases` can be used interchangeably with `.decrease`. + * + * @name decrease + * @alias decreases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDecreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'decrease'); + flag(this, 'realDelta', initial - final); + + this.assert( + final - initial < 0 + , 'expected ' + msgObj + ' to decrease' + , 'expected ' + msgObj + ' to not decrease' + ); + } + + Assertion.addMethod('decrease', assertDecreases); + Assertion.addMethod('decreases', assertDecreases); + + /** + * ### .by(delta[, msg]) + * + * When following an `.increase` assertion in the chain, `.by` asserts that + * the subject of the `.increase` assertion increased by the given `delta`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * When following a `.decrease` assertion in the chain, `.by` asserts that the + * subject of the `.decrease` assertion decreased by the given `delta`. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); + * + * When following a `.change` assertion in the chain, `.by` asserts that the + * subject of the `.change` assertion either increased or decreased by the + * given `delta`. However, it's dangerous to use `.change.by`. The problem is + * that it creates uncertain expectations. It's often best to identify the + * exact output that's expected, and then write an assertion that only accepts + * that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.by`. However, it's often best + * to assert that the subject changed by its expected delta, rather than + * asserting that it didn't change by one of countless unexpected deltas. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * // Recommended + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * // Not recommended + * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); + * + * `.by` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); + * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); + * + * @name by + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDelta(delta, msg) { + if (msg) flag(this, 'message', msg); + + var msgObj = flag(this, 'deltaMsgObj'); + var initial = flag(this, 'initialDeltaValue'); + var final = flag(this, 'finalDeltaValue'); + var behavior = flag(this, 'deltaBehavior'); + var realDelta = flag(this, 'realDelta'); + + var expression; + if (behavior === 'change') { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + + this.assert( + expression + , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta + , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta + ); + } + + Assertion.addMethod('by', assertDelta); + + /** + * ### .extensible + * + * Asserts that the target is extensible, which means that new properties can + * be added to it. Primitives are never extensible. + * + * expect({a: 1}).to.be.extensible; + * + * Add `.not` earlier in the chain to negate `.extensible`. + * + * var nonExtensibleObject = Object.preventExtensions({}) + * , sealedObject = Object.seal({}) + * , frozenObject = Object.freeze({}); + * + * expect(nonExtensibleObject).to.not.be.extensible; + * expect(sealedObject).to.not.be.extensible; + * expect(frozenObject).to.not.be.extensible; + * expect(1).to.not.be.extensible; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(1, 'nooo why fail??').to.be.extensible; + * + * @name extensible + * @namespace BDD + * @api public + */ + + Assertion.addProperty('extensible', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible + // The following provides ES6 behavior for ES5 environments. + + var isExtensible = obj === Object(obj) && Object.isExtensible(obj); + + this.assert( + isExtensible + , 'expected #{this} to be extensible' + , 'expected #{this} to not be extensible' + ); + }); + + /** + * ### .sealed + * + * Asserts that the target is sealed, which means that new properties can't be + * added to it, and its existing properties can't be reconfigured or deleted. + * However, it's possible that its existing properties can still be reassigned + * to different values. Primitives are always sealed. + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect(sealedObject).to.be.sealed; + * expect(frozenObject).to.be.sealed; + * expect(1).to.be.sealed; + * + * Add `.not` earlier in the chain to negate `.sealed`. + * + * expect({a: 1}).to.not.be.sealed; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.sealed; + * + * @name sealed + * @namespace BDD + * @api public + */ + + Assertion.addProperty('sealed', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed + // The following provides ES6 behavior for ES5 environments. + + var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + + this.assert( + isSealed + , 'expected #{this} to be sealed' + , 'expected #{this} to not be sealed' + ); + }); + + /** + * ### .frozen + * + * Asserts that the target is frozen, which means that new properties can't be + * added to it, and its existing properties can't be reassigned to different + * values, reconfigured, or deleted. Primitives are always frozen. + * + * var frozenObject = Object.freeze({}); + * + * expect(frozenObject).to.be.frozen; + * expect(1).to.be.frozen; + * + * Add `.not` earlier in the chain to negate `.frozen`. + * + * expect({a: 1}).to.not.be.frozen; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.frozen; + * + * @name frozen + * @namespace BDD + * @api public + */ + + Assertion.addProperty('frozen', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen + // The following provides ES6 behavior for ES5 environments. + + var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + + this.assert( + isFrozen + , 'expected #{this} to be frozen' + , 'expected #{this} to not be frozen' + ); + }); + + /** + * ### .finite + * + * Asserts that the target is a number, and isn't `NaN` or positive/negative + * `Infinity`. + * + * expect(1).to.be.finite; + * + * Add `.not` earlier in the chain to negate `.finite`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either isn't a number, or that it's `NaN`, or + * that it's positive `Infinity`, or that it's negative `Infinity`. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to be a number, it's often best to assert + * that it's the expected type, rather than asserting that it isn't one of + * many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.finite; // Not recommended + * + * When the target is expected to be `NaN`, it's often best to assert exactly + * that. + * + * expect(NaN).to.be.NaN; // Recommended + * expect(NaN).to.not.be.finite; // Not recommended + * + * When the target is expected to be positive infinity, it's often best to + * assert exactly that. + * + * expect(Infinity).to.equal(Infinity); // Recommended + * expect(Infinity).to.not.be.finite; // Not recommended + * + * When the target is expected to be negative infinity, it's often best to + * assert exactly that. + * + * expect(-Infinity).to.equal(-Infinity); // Recommended + * expect(-Infinity).to.not.be.finite; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect('foo', 'nooo why fail??').to.be.finite; + * + * @name finite + * @namespace BDD + * @api public + */ + + Assertion.addProperty('finite', function(msg) { + var obj = flag(this, 'object'); + + this.assert( + typeof obj === 'number' && isFinite(obj) + , 'expected #{this} to be a finite number' + , 'expected #{this} to not be a finite number' + ); + }); +}; diff --git a/web/node_modules/chai/lib/chai/interface/assert.js b/web/node_modules/chai/lib/chai/interface/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..11b3c25e658e64943832f136528f42a34ecf43f6 --- /dev/null +++ b/web/node_modules/chai/lib/chai/interface/assert.js @@ -0,0 +1,3113 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + /*! + * Chai dependencies. + */ + + var Assertion = chai.Assertion + , flag = util.flag; + + /*! + * Module export. + */ + + /** + * ### assert(expression, message) + * + * Write your own test expressions. + * + * assert('foo' !== 'bar', 'foo is not bar'); + * assert(Array.isArray([]), 'empty arrays are arrays'); + * + * @param {Mixed} expression to test for truthiness + * @param {String} message to display on error + * @name assert + * @namespace Assert + * @api public + */ + + var assert = chai.assert = function (express, errmsg) { + var test = new Assertion(null, null, chai.assert, true); + test.assert( + express + , errmsg + , '[ negation message unavailable ]' + ); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. Node.js `assert` module-compatible. + * + * assert.fail(); + * assert.fail("custom error message"); + * assert.fail(1, 2); + * assert.fail(1, 2, "custom error message"); + * assert.fail(1, 2, "custom error message", ">"); + * assert.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Assert + * @api public + */ + + assert.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + // Comply with Node's fail([message]) interface + + message = actual; + actual = undefined; + } + + message = message || 'assert.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, assert.fail); + }; + + /** + * ### .isOk(object, [message]) + * + * Asserts that `object` is truthy. + * + * assert.isOk('everything', 'everything is ok'); + * assert.isOk(false, 'this will fail'); + * + * @name isOk + * @alias ok + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isOk = function (val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; + }; + + /** + * ### .isNotOk(object, [message]) + * + * Asserts that `object` is falsy. + * + * assert.isNotOk('everything', 'this will fail'); + * assert.isNotOk(false, 'this will pass'); + * + * @name isNotOk + * @alias notOk + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotOk = function (val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * assert.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.equal = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.equal, true); + + test.assert( + exp == flag(test, 'object') + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .notEqual(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * assert.notEqual(3, 4, 'these numbers are not equal'); + * + * @name notEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notEqual = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.notEqual, true); + + test.assert( + exp != flag(test, 'object') + , 'expected #{this} to not equal #{exp}' + , 'expected #{this} to equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .strictEqual(actual, expected, [message]) + * + * Asserts strict equality (`===`) of `actual` and `expected`. + * + * assert.strictEqual(true, true, 'these booleans are strictly equal'); + * + * @name strictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.strictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); + }; + + /** + * ### .notStrictEqual(actual, expected, [message]) + * + * Asserts strict inequality (`!==`) of `actual` and `expected`. + * + * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); + * + * @name notStrictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); + }; + + /** + * ### .deepEqual(actual, expected, [message]) + * + * Asserts that `actual` is deeply equal to `expected`. + * + * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); + * + * @name deepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @alias deepStrictEqual + * @namespace Assert + * @api public + */ + + assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); + }; + + /** + * ### .notDeepEqual(actual, expected, [message]) + * + * Assert that `actual` is not deeply equal to `expected`. + * + * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); + * + * @name notDeepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); + }; + + /** + * ### .isAbove(valueToCheck, valueToBeAbove, [message]) + * + * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. + * + * assert.isAbove(5, 2, '5 is strictly greater than 2'); + * + * @name isAbove + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAbove + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAbove = function (val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); + }; + + /** + * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) + * + * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. + * + * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); + * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); + * + * @name isAtLeast + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtLeast + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtLeast = function (val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); + }; + + /** + * ### .isBelow(valueToCheck, valueToBeBelow, [message]) + * + * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. + * + * assert.isBelow(3, 6, '3 is strictly less than 6'); + * + * @name isBelow + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeBelow + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBelow = function (val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); + }; + + /** + * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) + * + * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. + * + * assert.isAtMost(3, 6, '3 is less than or equal to 6'); + * assert.isAtMost(4, 4, '4 is less than or equal to 4'); + * + * @name isAtMost + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtMost + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtMost = function (val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); + }; + + /** + * ### .isTrue(value, [message]) + * + * Asserts that `value` is true. + * + * var teaServed = true; + * assert.isTrue(teaServed, 'the tea has been served'); + * + * @name isTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isTrue = function (val, msg) { + new Assertion(val, msg, assert.isTrue, true).is['true']; + }; + + /** + * ### .isNotTrue(value, [message]) + * + * Asserts that `value` is not true. + * + * var tea = 'tasty chai'; + * assert.isNotTrue(tea, 'great, time for tea!'); + * + * @name isNotTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotTrue = function (val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); + }; + + /** + * ### .isFalse(value, [message]) + * + * Asserts that `value` is false. + * + * var teaServed = false; + * assert.isFalse(teaServed, 'no tea yet? hmm...'); + * + * @name isFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFalse = function (val, msg) { + new Assertion(val, msg, assert.isFalse, true).is['false']; + }; + + /** + * ### .isNotFalse(value, [message]) + * + * Asserts that `value` is not false. + * + * var tea = 'tasty chai'; + * assert.isNotFalse(tea, 'great, time for tea!'); + * + * @name isNotFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFalse = function (val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); + }; + + /** + * ### .isNull(value, [message]) + * + * Asserts that `value` is null. + * + * assert.isNull(err, 'there was no error'); + * + * @name isNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNull = function (val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); + }; + + /** + * ### .isNotNull(value, [message]) + * + * Asserts that `value` is not null. + * + * var tea = 'tasty chai'; + * assert.isNotNull(tea, 'great, time for tea!'); + * + * @name isNotNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNull = function (val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); + }; + + /** + * ### .isNaN + * + * Asserts that value is NaN. + * + * assert.isNaN(NaN, 'NaN is NaN'); + * + * @name isNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNaN = function (val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; + }; + + /** + * ### .isNotNaN + * + * Asserts that value is not NaN. + * + * assert.isNotNaN(4, '4 is not NaN'); + * + * @name isNotNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + assert.isNotNaN = function (val, msg) { + new Assertion(val, msg, assert.isNotNaN, true).not.to.be.NaN; + }; + + /** + * ### .exists + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * assert.exists(foo, 'foo is neither `null` nor `undefined`'); + * + * @name exists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.exists = function (val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; + }; + + /** + * ### .notExists + * + * Asserts that the target is either `null` or `undefined`. + * + * var bar = null + * , baz; + * + * assert.notExists(bar); + * assert.notExists(baz, 'baz is either null or undefined'); + * + * @name notExists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notExists = function (val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; + }; + + /** + * ### .isUndefined(value, [message]) + * + * Asserts that `value` is `undefined`. + * + * var tea; + * assert.isUndefined(tea, 'no tea defined'); + * + * @name isUndefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isUndefined = function (val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); + }; + + /** + * ### .isDefined(value, [message]) + * + * Asserts that `value` is not `undefined`. + * + * var tea = 'cup of chai'; + * assert.isDefined(tea, 'tea has been defined'); + * + * @name isDefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isDefined = function (val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); + }; + + /** + * ### .isFunction(value, [message]) + * + * Asserts that `value` is a function. + * + * function serveTea() { return 'cup of tea'; }; + * assert.isFunction(serveTea, 'great, we can have tea now'); + * + * @name isFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFunction = function (val, msg) { + new Assertion(val, msg, assert.isFunction, true).to.be.a('function'); + }; + + /** + * ### .isNotFunction(value, [message]) + * + * Asserts that `value` is _not_ a function. + * + * var serveTea = [ 'heat', 'pour', 'sip' ]; + * assert.isNotFunction(serveTea, 'great, we have listed the steps'); + * + * @name isNotFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFunction = function (val, msg) { + new Assertion(val, msg, assert.isNotFunction, true).to.not.be.a('function'); + }; + + /** + * ### .isObject(value, [message]) + * + * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). + * _The assertion does not match subclassed objects._ + * + * var selection = { name: 'Chai', serve: 'with spices' }; + * assert.isObject(selection, 'tea selection is an object'); + * + * @name isObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isObject = function (val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a('object'); + }; + + /** + * ### .isNotObject(value, [message]) + * + * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). + * + * var selection = 'chai' + * assert.isNotObject(selection, 'tea selection is not an object'); + * assert.isNotObject(null, 'null is not an object'); + * + * @name isNotObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotObject = function (val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); + }; + + /** + * ### .isArray(value, [message]) + * + * Asserts that `value` is an array. + * + * var menu = [ 'green', 'chai', 'oolong' ]; + * assert.isArray(menu, 'what kind of tea do we want?'); + * + * @name isArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isArray = function (val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an('array'); + }; + + /** + * ### .isNotArray(value, [message]) + * + * Asserts that `value` is _not_ an array. + * + * var menu = 'green|chai|oolong'; + * assert.isNotArray(menu, 'what kind of tea do we want?'); + * + * @name isNotArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotArray = function (val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); + }; + + /** + * ### .isString(value, [message]) + * + * Asserts that `value` is a string. + * + * var teaOrder = 'chai'; + * assert.isString(teaOrder, 'order placed'); + * + * @name isString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isString = function (val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a('string'); + }; + + /** + * ### .isNotString(value, [message]) + * + * Asserts that `value` is _not_ a string. + * + * var teaOrder = 4; + * assert.isNotString(teaOrder, 'order placed'); + * + * @name isNotString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotString = function (val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); + }; + + /** + * ### .isNumber(value, [message]) + * + * Asserts that `value` is a number. + * + * var cups = 2; + * assert.isNumber(cups, 'how many cups'); + * + * @name isNumber + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNumber = function (val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); + }; + + /** + * ### .isNotNumber(value, [message]) + * + * Asserts that `value` is _not_ a number. + * + * var cups = '2 cups please'; + * assert.isNotNumber(cups, 'how many cups'); + * + * @name isNotNumber + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNumber = function (val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); + }; + + /** + * ### .isFinite(value, [message]) + * + * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * var cups = 2; + * assert.isFinite(cups, 'how many cups'); + * + * assert.isFinite(NaN); // throws + * + * @name isFinite + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFinite = function (val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; + }; + + /** + * ### .isBoolean(value, [message]) + * + * Asserts that `value` is a boolean. + * + * var teaReady = true + * , teaServed = false; + * + * assert.isBoolean(teaReady, 'is the tea ready'); + * assert.isBoolean(teaServed, 'has tea been served'); + * + * @name isBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBoolean = function (val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); + }; + + /** + * ### .isNotBoolean(value, [message]) + * + * Asserts that `value` is _not_ a boolean. + * + * var teaReady = 'yep' + * , teaServed = 'nope'; + * + * assert.isNotBoolean(teaReady, 'is the tea ready'); + * assert.isNotBoolean(teaServed, 'has tea been served'); + * + * @name isNotBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotBoolean = function (val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); + }; + + /** + * ### .typeOf(value, name, [message]) + * + * Asserts that `value`'s type is `name`, as determined by + * `Object.prototype.toString`. + * + * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); + * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); + * assert.typeOf('tea', 'string', 'we have a string'); + * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); + * assert.typeOf(null, 'null', 'we have a null'); + * assert.typeOf(undefined, 'undefined', 'we have an undefined'); + * + * @name typeOf + * @param {Mixed} value + * @param {String} name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.typeOf = function (val, type, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type); + }; + + /** + * ### .notTypeOf(value, name, [message]) + * + * Asserts that `value`'s type is _not_ `name`, as determined by + * `Object.prototype.toString`. + * + * assert.notTypeOf('tea', 'number', 'strings are not numbers'); + * + * @name notTypeOf + * @param {Mixed} value + * @param {String} typeof name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notTypeOf = function (val, type, msg) { + new Assertion(val, msg, assert.notTypeOf, true).to.not.be.a(type); + }; + + /** + * ### .instanceOf(object, constructor, [message]) + * + * Asserts that `value` is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new Tea('chai'); + * + * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); + * + * @name instanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.instanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); + }; + + /** + * ### .notInstanceOf(object, constructor, [message]) + * + * Asserts `value` is not an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new String('chai'); + * + * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); + * + * @name notInstanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInstanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.notInstanceOf, true) + .to.not.be.instanceOf(type); + }; + + /** + * ### .include(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.include([1,2,3], 2, 'array contains value'); + * assert.include('foobar', 'foo', 'string contains substring'); + * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); + * + * Strict equality (===) is used. When asserting the inclusion of a value in + * an array, the array is searched for an element that's strictly equal to the + * given value. When asserting a subset of properties in an object, the object + * is searched for the given property keys, checking that each one is present + * and strictly equal to the given property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.include([obj1, obj2], obj1); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); + * + * @name include + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.include = function (exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); + }; + + /** + * ### .notInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.notInclude([1,2,3], 4, "array doesn't contain value"); + * assert.notInclude('foobar', 'baz', "string doesn't contain substring"); + * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); + * + * Strict equality (===) is used. When asserting the absence of a value in an + * array, the array is searched to confirm the absence of an element that's + * strictly equal to the given value. When asserting a subset of properties in + * an object, the object is searched to confirm that at least one of the given + * property keys is either not present or not strictly equal to the given + * property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notInclude([obj1, obj2], {a: 1}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); + * + * @name notInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); + }; + + /** + * ### .deepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.deepInclude([obj1, obj2], {a: 1}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); + * + * @name deepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); + }; + + /** + * ### .notDeepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notDeepInclude([obj1, obj2], {a: 9}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); + * + * @name notDeepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); + }; + + /** + * ### .nestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + * + * @name nestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); + }; + + /** + * ### .notNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + * + * @name notNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true) + .not.nested.include(inc); + }; + + /** + * ### .deepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + * + * @name deepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true) + .deep.nested.include(inc); + }; + + /** + * ### .notDeepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + * + * @name notDeepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepNestedInclude, true) + .not.deep.nested.include(inc); + }; + + /** + * ### .ownInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties. + * + * assert.ownInclude({ a: 1 }, { a: 1 }); + * + * @name ownInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); + }; + + /** + * ### .notOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties. + * + * Object.prototype.b = 2; + * + * assert.notOwnInclude({ a: 1 }, { b: 2 }); + * + * @name notOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); + }; + + /** + * ### .deepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + * + * @name deepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true) + .deep.own.include(inc); + }; + + /** + * ### .notDeepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + * + * @name notDeepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true) + .not.deep.own.include(inc); + }; + + /** + * ### .match(value, regexp, [message]) + * + * Asserts that `value` matches the regular expression `regexp`. + * + * assert.match('foobar', /^foo/, 'regexp matches'); + * + * @name match + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.match = function (exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); + }; + + /** + * ### .notMatch(value, regexp, [message]) + * + * Asserts that `value` does not match the regular expression `regexp`. + * + * assert.notMatch('foobar', /^foo/, 'regexp does not match'); + * + * @name notMatch + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notMatch = function (exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); + }; + + /** + * ### .property(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`. + * + * assert.property({ tea: { green: 'matcha' }}, 'tea'); + * assert.property({ tea: { green: 'matcha' }}, 'toString'); + * + * @name property + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.property = function (obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); + }; + + /** + * ### .notProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property`. + * + * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); + * + * @name notProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true) + .to.not.have.property(prop); + }; + + /** + * ### .propertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a strict equality check + * (===). + * + * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); + * + * @name propertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.propertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true) + .to.have.property(prop, val); + }; + + /** + * ### .notPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a strict equality check + * (===). + * + * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); + * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); + * + * @name notPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true) + .to.not.have.property(prop, val); + }; + + /** + * ### .deepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a deep equality check. + * + * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true) + .to.have.deep.property(prop, val); + }; + + /** + * ### .notDeepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a deep equality check. + * + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * + * @name notDeepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepPropertyVal, true) + .to.not.have.deep.property(prop, val); + }; + + /** + * ### .ownProperty(object, property, [message]) + * + * Asserts that `object` has a direct property named by `property`. Inherited + * properties aren't checked. + * + * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); + * + * @name ownProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.ownProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true) + .to.have.own.property(prop); + }; + + /** + * ### .notOwnProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct property named by + * `property`. Inherited properties aren't checked. + * + * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); + * assert.notOwnProperty({}, 'toString'); + * + * @name notOwnProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.notOwnProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true) + .to.not.have.own.property(prop); + }; + + /** + * ### .ownPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a strict equality check (===). + * Inherited properties aren't checked. + * + * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); + * + * @name ownPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.ownPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true) + .to.have.own.property(prop, value); + }; + + /** + * ### .notOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a strict equality check + * (===). Inherited properties aren't checked. + * + * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); + * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notOwnPropertyVal, true) + .to.not.have.own.property(prop, value); + }; + + /** + * ### .deepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a deep equality check. Inherited + * properties aren't checked. + * + * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.deepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.deepOwnPropertyVal, true) + .to.have.deep.own.property(prop, value); + }; + + /** + * ### .notDeepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a deep equality check. + * Inherited properties aren't checked. + * + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notDeepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) + .to.not.have.deep.own.property(prop, value); + }; + + /** + * ### .nestedProperty(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`, which can be a string using dot- and bracket-notation for + * nested reference. + * + * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); + * + * @name nestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true) + .to.have.nested.property(prop); + }; + + /** + * ### .notNestedProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`, which + * can be a string using dot- and bracket-notation for nested reference. The + * property cannot exist on the object nor anywhere in its prototype chain. + * + * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); + * + * @name notNestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notNestedProperty, true) + .to.not.have.nested.property(prop); + }; + + /** + * ### .nestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a strict equality check (===). + * + * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); + * + * @name nestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.nestedPropertyVal, true) + .to.have.nested.property(prop, val); + }; + + /** + * ### .notNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a strict equality check (===). + * + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); + * + * @name notNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notNestedPropertyVal, true) + .to.not.have.nested.property(prop, val); + }; + + /** + * ### .deepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with a value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a deep equality check. + * + * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); + * + * @name deepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepNestedPropertyVal, true) + .to.have.deep.nested.property(prop, val); + }; + + /** + * ### .notDeepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a deep equality check. + * + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); + * + * @name notDeepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) + .to.not.have.deep.nested.property(prop, val); + } + + /** + * ### .lengthOf(object, length, [message]) + * + * Asserts that `object` has a `length` or `size` with the expected value. + * + * assert.lengthOf([1,2,3], 3, 'array has length of 3'); + * assert.lengthOf('foobar', 6, 'string has length of 6'); + * assert.lengthOf(new Set([1,2,3]), 3, 'set has size of 3'); + * assert.lengthOf(new Map([['a',1],['b',2],['c',3]]), 3, 'map has size of 3'); + * + * @name lengthOf + * @param {Mixed} object + * @param {Number} length + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.lengthOf = function (exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); + }; + + /** + * ### .hasAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAnyKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); + } + + /** + * ### .hasAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); + * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); + } + + /** + * ### .containsAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}]); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name containsAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true) + .to.contain.all.keys(keys); + } + + /** + * ### .doesNotHaveAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAnyKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) + .to.not.have.any.keys(keys); + } + + /** + * ### .doesNotHaveAllKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) + .to.not.have.all.keys(keys); + } + + /** + * ### .hasAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAnyDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true) + .to.have.any.deep.keys(keys); + } + + /** + * ### .hasAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true) + .to.have.all.deep.keys(keys); + } + + /** + * ### .containsAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name containsAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllDeepKeys, true) + .to.contain.all.deep.keys(keys); + } + + /** + * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAnyDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) + .to.not.have.any.deep.keys(keys); + } + + /** + * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) + .to.not.have.all.deep.keys(keys); + } + + /** + * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a + * message matching `errMsgMatcher`. + * + * assert.throws(fn, 'Error thrown must have this msg'); + * assert.throws(fn, /Error thrown must have a msg that matches this/); + * assert.throws(fn, ReferenceError); + * assert.throws(fn, errorInstance); + * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); + * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); + * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); + * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); + * + * @name throws + * @alias throw + * @alias Throw + * @param {Function} fn + * @param {ErrorConstructor|Error} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.throws = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + var assertErr = new Assertion(fn, msg, assert.throws, true) + .to.throw(errorLike, errMsgMatcher); + return flag(assertErr, 'object'); + }; + + /** + * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a + * message matching `errMsgMatcher`. + * + * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); + * assert.doesNotThrow(fn, /Any Error thrown must not match this/); + * assert.doesNotThrow(fn, Error); + * assert.doesNotThrow(fn, errorInstance); + * assert.doesNotThrow(fn, Error, 'Error must not have this message'); + * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); + * assert.doesNotThrow(fn, Error, /Error must not match this/); + * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); + * + * @name doesNotThrow + * @param {Function} fn + * @param {ErrorConstructor} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + new Assertion(fn, msg, assert.doesNotThrow, true) + .to.not.throw(errorLike, errMsgMatcher); + }; + + /** + * ### .operator(val1, operator, val2, [message]) + * + * Compares two values using `operator`. + * + * assert.operator(1, '<', 2, 'everything is ok'); + * assert.operator(1, '>', 2, 'this will fail'); + * + * @name operator + * @param {Mixed} val1 + * @param {String} operator + * @param {Mixed} val2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.operator = function (val, operator, val2, msg) { + var ok; + switch(operator) { + case '==': + ok = val == val2; + break; + case '===': + ok = val === val2; + break; + case '>': + ok = val > val2; + break; + case '>=': + ok = val >= val2; + break; + case '<': + ok = val < val2; + break; + case '<=': + ok = val <= val2; + break; + case '!=': + ok = val != val2; + break; + case '!==': + ok = val !== val2; + break; + default: + msg = msg ? msg + ': ' : msg; + throw new chai.AssertionError( + msg + 'Invalid operator "' + operator + '"', + undefined, + assert.operator + ); + } + var test = new Assertion(ok, msg, assert.operator, true); + test.assert( + true === flag(test, 'object') + , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) + , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); + }; + + /** + * ### .closeTo(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); + * + * @name closeTo + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.closeTo = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); + }; + + /** + * ### .approximately(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.approximately(1.5, 1, 0.5, 'numbers are close'); + * + * @name approximately + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.approximately = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true) + .to.be.approximately(exp, delta); + }; + + /** + * ### .sameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * strict equality check (===). + * + * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + * + * @name sameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true) + .to.have.same.members(set2); + } + + /** + * ### .notSameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a strict equality check (===). + * + * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); + * + * @name notSameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameMembers, true) + .to.not.have.same.members(set2); + } + + /** + * ### .sameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * deep equality check. + * + * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); + * + * @name sameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepMembers, true) + .to.have.same.deep.members(set2); + } + + /** + * ### .notSameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); + * + * @name notSameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepMembers, true) + .to.not.have.same.deep.members(set2); + } + + /** + * ### .sameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a strict equality check (===). + * + * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); + * + * @name sameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameOrderedMembers, true) + .to.have.same.ordered.members(set2); + } + + /** + * ### .notSameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a strict equality check (===). + * + * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); + * + * @name notSameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameOrderedMembers, true) + .to.not.have.same.ordered.members(set2); + } + + /** + * ### .sameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a deep equality check. + * + * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); + * + * @name sameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) + .to.have.same.deep.ordered.members(set2); + } + + /** + * ### .notSameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a deep equality check. + * + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); + * + * @name notSameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) + .to.not.have.same.deep.ordered.members(set2); + } + + /** + * ### .includeMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); + * + * @name includeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true) + .to.include.members(subset); + } + + /** + * ### .notIncludeMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); + * + * @name notIncludeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeMembers, true) + .to.not.include.members(subset); + } + + /** + * ### .includeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a deep + * equality check. Duplicates are ignored. + * + * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); + * + * @name includeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepMembers, true) + .to.include.deep.members(subset); + } + + /** + * ### .notIncludeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * @name notIncludeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepMembers, true) + .to.not.include.deep.members(subset); + } + + /** + * ### .includeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); + * + * @name includeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeOrderedMembers, true) + .to.include.ordered.members(subset); + } + + /** + * ### .notIncludeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); + * + * @name notIncludeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) + .to.not.include.ordered.members(subset); + } + + /** + * ### .includeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); + * + * @name includeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) + .to.include.deep.ordered.members(subset); + } + + /** + * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); + * + * @name notIncludeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) + .to.not.include.deep.ordered.members(subset); + } + + /** + * ### .oneOf(inList, list, [message]) + * + * Asserts that non-object, non-array value `inList` appears in the flat array `list`. + * + * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); + * + * @name oneOf + * @param {*} inList + * @param {Array<*>} list + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.oneOf = function (inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); + } + + /** + * ### .changes(function, object, property, [message]) + * + * Asserts that a function changes the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 22 }; + * assert.changes(fn, obj, 'val'); + * + * @name changes + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changes = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); + } + + /** + * ### .changesBy(function, object, property, delta, [message]) + * + * Asserts that a function changes the value of a property by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 2 }; + * assert.changesBy(fn, obj, 'val', 2); + * + * @name changesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesBy, true) + .to.change(obj, prop).by(delta); + } + + /** + * ### .doesNotChange(function, object, property, [message]) + * + * Asserts that a function does not change the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { console.log('foo'); }; + * assert.doesNotChange(fn, obj, 'val'); + * + * @name doesNotChange + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotChange = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotChange, true) + .to.not.change(obj, prop); + } + + /** + * ### .changesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.changesButNotBy(fn, obj, 'val', 5); + * + * @name changesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesButNotBy, true) + .to.change(obj, prop).but.not.by(delta); + } + + /** + * ### .increases(function, object, property, [message]) + * + * Asserts that a function increases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 13 }; + * assert.increases(fn, obj, 'val'); + * + * @name increases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.increases, true) + .to.increase(obj, prop); + } + + /** + * ### .increasesBy(function, object, property, delta, [message]) + * + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.increasesBy(fn, obj, 'val', 10); + * + * @name increasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesBy, true) + .to.increase(obj, prop).by(delta); + } + + /** + * ### .doesNotIncrease(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 8 }; + * assert.doesNotIncrease(fn, obj, 'val'); + * + * @name doesNotIncrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotIncrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotIncrease, true) + .to.not.increase(obj, prop); + } + + /** + * ### .increasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.increasesButNotBy(fn, obj, 'val', 10); + * + * @name increasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesButNotBy, true) + .to.increase(obj, prop).but.not.by(delta); + } + + /** + * ### .decreases(function, object, property, [message]) + * + * Asserts that a function decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreases(fn, obj, 'val'); + * + * @name decreases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.decreases, true) + .to.decrease(obj, prop); + } + + /** + * ### .decreasesBy(function, object, property, delta, [message]) + * + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val -= 5 }; + * assert.decreasesBy(fn, obj, 'val', 5); + * + * @name decreasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesBy, true) + .to.decrease(obj, prop).by(delta); + } + + /** + * ### .doesNotDecrease(function, object, property, [message]) + * + * Asserts that a function does not decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.doesNotDecrease(fn, obj, 'val'); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecrease, true) + .to.not.decrease(obj, prop); + } + + /** + * ### .doesNotDecreaseBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.doesNotDecreaseBy(fn, obj, 'val', 1); + * + * @name doesNotDecreaseBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) + .to.not.decrease(obj, prop).by(delta); + } + + /** + * ### .decreasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreasesButNotBy(fn, obj, 'val', 1); + * + * @name decreasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesButNotBy, true) + .to.decrease(obj, prop).but.not.by(delta); + } + + /*! + * ### .ifError(object) + * + * Asserts if value is not a false value, and throws if it is a true value. + * This is added to allow for chai to be a drop-in replacement for Node's + * assert class. + * + * var err = new Error('I am a custom error'); + * assert.ifError(err); // Rethrows err! + * + * @name ifError + * @param {Object} object + * @namespace Assert + * @api public + */ + + assert.ifError = function (val) { + if (val) { + throw(val); + } + }; + + /** + * ### .isExtensible(object) + * + * Asserts that `object` is extensible (can have new properties added to it). + * + * assert.isExtensible({}); + * + * @name isExtensible + * @alias extensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; + }; + + /** + * ### .isNotExtensible(object) + * + * Asserts that `object` is _not_ extensible. + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * assert.isNotExtensible(nonExtensibleObject); + * assert.isNotExtensible(sealedObject); + * assert.isNotExtensible(frozenObject); + * + * @name isNotExtensible + * @alias notExtensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; + }; + + /** + * ### .isSealed(object) + * + * Asserts that `object` is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.seal({}); + * + * assert.isSealed(sealedObject); + * assert.isSealed(frozenObject); + * + * @name isSealed + * @alias sealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; + }; + + /** + * ### .isNotSealed(object) + * + * Asserts that `object` is _not_ sealed. + * + * assert.isNotSealed({}); + * + * @name isNotSealed + * @alias notSealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; + }; + + /** + * ### .isFrozen(object) + * + * Asserts that `object` is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * assert.frozen(frozenObject); + * + * @name isFrozen + * @alias frozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; + }; + + /** + * ### .isNotFrozen(object) + * + * Asserts that `object` is _not_ frozen. + * + * assert.isNotFrozen({}); + * + * @name isNotFrozen + * @alias notFrozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; + }; + + /** + * ### .isEmpty(target) + * + * Asserts that the target does not contain any values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isEmpty([]); + * assert.isEmpty(''); + * assert.isEmpty(new Map); + * assert.isEmpty({}); + * + * @name isEmpty + * @alias empty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; + }; + + /** + * ### .isNotEmpty(target) + * + * Asserts that the target contains values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isNotEmpty([1, 2]); + * assert.isNotEmpty('34'); + * assert.isNotEmpty(new Set([5, 6])); + * assert.isNotEmpty({ key: 7 }); + * + * @name isNotEmpty + * @alias notEmpty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; + }; + + /*! + * Aliases. + */ + + (function alias(name, as){ + assert[as] = assert[name]; + return alias; + }) + ('isOk', 'ok') + ('isNotOk', 'notOk') + ('throws', 'throw') + ('throws', 'Throw') + ('isExtensible', 'extensible') + ('isNotExtensible', 'notExtensible') + ('isSealed', 'sealed') + ('isNotSealed', 'notSealed') + ('isFrozen', 'frozen') + ('isNotFrozen', 'notFrozen') + ('isEmpty', 'empty') + ('isNotEmpty', 'notEmpty'); +}; diff --git a/web/node_modules/chai/lib/chai/interface/expect.js b/web/node_modules/chai/lib/chai/interface/expect.js new file mode 100644 index 0000000000000000000000000000000000000000..6867e2a931d92fdc7cdf199652127d15aa874058 --- /dev/null +++ b/web/node_modules/chai/lib/chai/interface/expect.js @@ -0,0 +1,47 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + chai.expect = function (val, message) { + return new chai.Assertion(val, message); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * expect.fail(); + * expect.fail("custom error message"); + * expect.fail(1, 2); + * expect.fail(1, 2, "custom error message"); + * expect.fail(1, 2, "custom error message", ">"); + * expect.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + chai.expect.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'expect.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, chai.expect.fail); + }; +}; diff --git a/web/node_modules/chai/lib/chai/interface/should.js b/web/node_modules/chai/lib/chai/interface/should.js new file mode 100644 index 0000000000000000000000000000000000000000..17902af7daf7815424f295e946256eea9ddc6327 --- /dev/null +++ b/web/node_modules/chai/lib/chai/interface/should.js @@ -0,0 +1,219 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + var Assertion = chai.Assertion; + + function loadShould () { + // explicitly define this method as function as to have it's name to include as `ssfi` + function shouldGetter() { + if (this instanceof String + || this instanceof Number + || this instanceof Boolean + || typeof Symbol === 'function' && this instanceof Symbol + || typeof BigInt === 'function' && this instanceof BigInt) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + function shouldSetter(value) { + // See https://github.com/chaijs/chai/issues/86: this makes + // `whatever.should = someValue` actually set `someValue`, which is + // especially useful for `global.should = require('chai').should()`. + // + // Note that we have to use [[DefineProperty]] instead of [[Put]] + // since otherwise we would trigger this very setter! + Object.defineProperty(this, 'should', { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } + // modify Object.prototype to have `should` + Object.defineProperty(Object.prototype, 'should', { + set: shouldSetter + , get: shouldGetter + , configurable: true + }); + + var should = {}; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * should.fail(); + * should.fail("custom error message"); + * should.fail(1, 2); + * should.fail(1, 2, "custom error message"); + * should.fail(1, 2, "custom error message", ">"); + * should.fail(1, 2, undefined, ">"); + * + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + should.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'should.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, should.fail); + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * should.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.equal(val2); + }; + + /** + * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * should.throw(fn, 'function throws a reference error'); + * should.throw(fn, /function throws a reference error/); + * should.throw(fn, ReferenceError); + * should.throw(fn, ReferenceError, 'function throws a reference error'); + * should.throw(fn, ReferenceError, /function throws a reference error/); + * + * @name throw + * @alias Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * should.exist(foo, 'foo exists'); + * + * @name exist + * @namespace Should + * @api public + */ + + should.exist = function (val, msg) { + new Assertion(val, msg).to.exist; + } + + // negation + should.not = {} + + /** + * ### .not.equal(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * should.not.equal(3, 4, 'these numbers are not equal'); + * + * @name not.equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.not.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.not.equal(val2); + }; + + /** + * ### .throw(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * should.not.throw(fn, Error, 'function does not throw'); + * + * @name not.throw + * @alias not.Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.not.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + + /** + * ### .not.exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var bar = null; + * + * should.not.exist(bar, 'bar does not exist'); + * + * @name not.exist + * @namespace Should + * @api public + */ + + should.not.exist = function (val, msg) { + new Assertion(val, msg).to.not.exist; + } + + should['throw'] = should['Throw']; + should.not['throw'] = should.not['Throw']; + + return should; + }; + + chai.should = loadShould; + chai.Should = loadShould; +}; diff --git a/web/node_modules/chai/lib/chai/utils/addChainableMethod.js b/web/node_modules/chai/lib/chai/utils/addChainableMethod.js new file mode 100644 index 0000000000000000000000000000000000000000..a713f6ac873b5a7cea02ca1470cb26957261c614 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/addChainableMethod.js @@ -0,0 +1,152 @@ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/*! + * Module variables + */ + +// Check whether `Object.setPrototypeOf` is supported +var canSetPrototype = typeof Object.setPrototypeOf === 'function'; + +// Without `Object.setPrototypeOf` support, this module will need to add properties to a function. +// However, some of functions' own props are not configurable and should be skipped. +var testFn = function() {}; +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + var propDesc = Object.getOwnPropertyDescriptor(testFn, name); + + // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, + // but then returns `undefined` as the property descriptor for `callee`. As a + // workaround, we perform an otherwise unnecessary type-check for `propDesc`, + // and then filter it out if it's not an object as it should be. + if (typeof propDesc !== 'object') + return true; + + return !propDesc.configurable; +}); + +// Cache `Function` properties +var call = Function.prototype.call, + apply = Function.prototype.apply; + +/** + * ### .addChainableMethod(ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @namespace Utils + * @name addChainableMethod + * @api public + */ + +module.exports = function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') { + chainingBehavior = function () { }; + } + + var chainableBehavior = { + method: method + , chainingBehavior: chainingBehavior + }; + + // save the methods so we can overwrite them later, if we need to. + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + + Object.defineProperty(ctx, name, + { get: function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + + var chainableMethodWrapper = function () { + // Setting the `ssfi` flag to `chainableMethodWrapper` causes this + // function to be the starting point for removing implementation + // frames from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then this assertion is being + // invoked from inside of another assertion. In this case, the `ssfi` + // flag has already been set by the outer assertion. + // + // Note that overwriting a chainable method merely replaces the saved + // methods in `ctx.__methods` instead of completely replacing the + // overwritten assertion. Therefore, an overwriting assertion won't + // set the `ssfi` or `lockSsfi` flags. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', chainableMethodWrapper); + } + + var result = chainableBehavior.method.apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(chainableMethodWrapper, name, true); + + // Use `Object.setPrototypeOf` if available + if (canSetPrototype) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + } + , configurable: true + }); +}; diff --git a/web/node_modules/chai/lib/chai/utils/addLengthGuard.js b/web/node_modules/chai/lib/chai/utils/addLengthGuard.js new file mode 100644 index 0000000000000000000000000000000000000000..e51ce80e898d7fb4a3d9ef61d51adc68907d5530 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/addLengthGuard.js @@ -0,0 +1,60 @@ +var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); + +/*! + * Chai - addLengthGuard utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .addLengthGuard(fn, assertionName, isChainable) + * + * Define `length` as a getter on the given uninvoked method assertion. The + * getter acts as a guard against chaining `length` directly off of an uninvoked + * method assertion, which is a problem because it references `function`'s + * built-in `length` property instead of Chai's `length` assertion. When the + * getter catches the user making this mistake, it throws an error with a + * helpful message. + * + * There are two ways in which this mistake can be made. The first way is by + * chaining the `length` assertion directly off of an uninvoked chainable + * method. In this case, Chai suggests that the user use `lengthOf` instead. The + * second way is by chaining the `length` assertion directly off of an uninvoked + * non-chainable method. Non-chainable methods must be invoked prior to + * chaining. In this case, Chai suggests that the user consult the docs for the + * given assertion. + * + * If the `length` property of functions is unconfigurable, then return `fn` + * without modification. + * + * Note that in ES6, the function's `length` property is configurable, so once + * support for legacy environments is dropped, Chai's `length` property can + * replace the built-in function's `length` property, and this length guard will + * no longer be necessary. In the mean time, maintaining consistency across all + * environments is the priority. + * + * @param {Function} fn + * @param {String} assertionName + * @param {Boolean} isChainable + * @namespace Utils + * @name addLengthGuard + */ + +module.exports = function addLengthGuard (fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + + Object.defineProperty(fn, 'length', { + get: function () { + if (isChainable) { + throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + + ' to a compatibility issue, "length" cannot directly follow "' + + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); + } + + throw Error('Invalid Chai property: ' + assertionName + '.length. See' + + ' docs for proper usage of "' + assertionName + '".'); + } + }); + + return fn; +}; diff --git a/web/node_modules/chai/lib/chai/utils/addMethod.js b/web/node_modules/chai/lib/chai/utils/addMethod.js new file mode 100644 index 0000000000000000000000000000000000000000..021f080420e9015c5826f559bda82c70669515c8 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/addMethod.js @@ -0,0 +1,68 @@ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/** + * ### .addMethod(ctx, name, method) + * + * Adds a method to the prototype of an object. + * + * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(fooStr).to.be.foo('bar'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for name + * @namespace Utils + * @name addMethod + * @api public + */ + +module.exports = function addMethod(ctx, name, method) { + var methodWrapper = function () { + // Setting the `ssfi` flag to `methodWrapper` causes this function to be the + // starting point for removing implementation frames from the stack trace of + // a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', methodWrapper); + } + + var result = method.apply(this, arguments); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); +}; diff --git a/web/node_modules/chai/lib/chai/utils/addProperty.js b/web/node_modules/chai/lib/chai/utils/addProperty.js new file mode 100644 index 0000000000000000000000000000000000000000..872a8cd7e7355cab1db4435a19c44e89e0c4f870 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/addProperty.js @@ -0,0 +1,72 @@ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var flag = require('./flag'); +var isProxyEnabled = require('./isProxyEnabled'); +var transferFlags = require('./transferFlags'); + +/** + * ### .addProperty(ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + * utils.addProperty(chai.Assertion.prototype, 'foo', function () { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.instanceof(Foo); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.foo; + * + * @param {Object} ctx object to which the property is added + * @param {String} name of property to add + * @param {Function} getter function to be used for name + * @namespace Utils + * @name addProperty + * @api public + */ + +module.exports = function addProperty(ctx, name, getter) { + getter = getter === undefined ? function () {} : getter; + + Object.defineProperty(ctx, name, + { get: function propertyGetter() { + // Setting the `ssfi` flag to `propertyGetter` causes this function to + // be the starting point for removing implementation frames from the + // stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', propertyGetter); + } + + var result = getter.call(this); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +}; diff --git a/web/node_modules/chai/lib/chai/utils/compareByInspect.js b/web/node_modules/chai/lib/chai/utils/compareByInspect.js new file mode 100644 index 0000000000000000000000000000000000000000..c8cd5e197c760153220794d2f7a08c68b8da99ac --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/compareByInspect.js @@ -0,0 +1,31 @@ +/*! + * Chai - compareByInspect utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var inspect = require('./inspect'); + +/** + * ### .compareByInspect(mixed, mixed) + * + * To be used as a compareFunction with Array.prototype.sort. Compares elements + * using inspect instead of default behavior of using toString so that Symbols + * and objects with irregular/missing toString can still be sorted without a + * TypeError. + * + * @param {Mixed} first element to compare + * @param {Mixed} second element to compare + * @returns {Number} -1 if 'a' should come before 'b'; otherwise 1 + * @name compareByInspect + * @namespace Utils + * @api public + */ + +module.exports = function compareByInspect(a, b) { + return inspect(a) < inspect(b) ? -1 : 1; +}; diff --git a/web/node_modules/chai/lib/chai/utils/expectTypes.js b/web/node_modules/chai/lib/chai/utils/expectTypes.js new file mode 100644 index 0000000000000000000000000000000000000000..6293db74897ac7ce4f57319613f0fe5a81ccc039 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/expectTypes.js @@ -0,0 +1,51 @@ +/*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .expectTypes(obj, types) + * + * Ensures that the object being tested against is of a valid type. + * + * utils.expectTypes(this, ['array', 'object', 'string']); + * + * @param {Mixed} obj constructed Assertion + * @param {Array} type A list of allowed types for this assertion + * @namespace Utils + * @name expectTypes + * @api public + */ + +var AssertionError = require('assertion-error'); +var flag = require('./flag'); +var type = require('type-detect'); + +module.exports = function expectTypes(obj, types) { + var flagMsg = flag(obj, 'message'); + var ssfi = flag(obj, 'ssfi'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + obj = flag(obj, 'object'); + types = types.map(function (t) { return t.toLowerCase(); }); + types.sort(); + + // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' + var str = types.map(function (t, index) { + var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; + var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; + return or + art + ' ' + t; + }).join(', '); + + var objType = type(obj).toLowerCase(); + + if (!types.some(function (expected) { return objType === expected; })) { + throw new AssertionError( + flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', + undefined, + ssfi + ); + } +}; diff --git a/web/node_modules/chai/lib/chai/utils/flag.js b/web/node_modules/chai/lib/chai/utils/flag.js new file mode 100644 index 0000000000000000000000000000000000000000..dd53bfbf895692867d627edbd636827f2ae76d3d --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/flag.js @@ -0,0 +1,33 @@ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .flag(object, key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + * utils.flag(this, 'foo', 'bar'); // setter + * utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {Object} object constructed Assertion + * @param {String} key + * @param {Mixed} value (optional) + * @namespace Utils + * @name flag + * @api private + */ + +module.exports = function flag(obj, key, value) { + var flags = obj.__flags || (obj.__flags = Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +}; diff --git a/web/node_modules/chai/lib/chai/utils/getActual.js b/web/node_modules/chai/lib/chai/utils/getActual.js new file mode 100644 index 0000000000000000000000000000000000000000..976e11259e7bb22cd9efee6b757fc0181dc3102d --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getActual.js @@ -0,0 +1,20 @@ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getActual + */ + +module.exports = function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +}; diff --git a/web/node_modules/chai/lib/chai/utils/getEnumerableProperties.js b/web/node_modules/chai/lib/chai/utils/getEnumerableProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..a84252cfdc25b5acb7e6643672446adba3bdd19e --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getEnumerableProperties.js @@ -0,0 +1,26 @@ +/*! + * Chai - getEnumerableProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getEnumerableProperties(object) + * + * This allows the retrieval of enumerable property names of an object, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getEnumerableProperties + * @api public + */ + +module.exports = function getEnumerableProperties(object) { + var result = []; + for (var name in object) { + result.push(name); + } + return result; +}; diff --git a/web/node_modules/chai/lib/chai/utils/getMessage.js b/web/node_modules/chai/lib/chai/utils/getMessage.js new file mode 100644 index 0000000000000000000000000000000000000000..bb8371668c61f14f13c4db7c21efaeac0d5fd7d6 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getMessage.js @@ -0,0 +1,50 @@ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var flag = require('./flag') + , getActual = require('./getActual') + , objDisplay = require('./objDisplay'); + +/** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Message template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getMessage + * @api public + */ + +module.exports = function getMessage(obj, args) { + var negate = flag(obj, 'negate') + , val = flag(obj, 'object') + , expected = args[3] + , actual = getActual(obj, args) + , msg = negate ? args[2] : args[1] + , flagMsg = flag(obj, 'message'); + + if(typeof msg === "function") msg = msg(); + msg = msg || ''; + msg = msg + .replace(/#\{this\}/g, function () { return objDisplay(val); }) + .replace(/#\{act\}/g, function () { return objDisplay(actual); }) + .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); + + return flagMsg ? flagMsg + ': ' + msg : msg; +}; diff --git a/web/node_modules/chai/lib/chai/utils/getOperator.js b/web/node_modules/chai/lib/chai/utils/getOperator.js new file mode 100644 index 0000000000000000000000000000000000000000..f7d10ef170ba26163e27e13ea076bc337fcaa229 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getOperator.js @@ -0,0 +1,55 @@ +var type = require('type-detect'); + +var flag = require('./flag'); + +function isObjectType(obj) { + var objectType = type(obj); + var objectTypes = ['Array', 'Object', 'function']; + + return objectTypes.indexOf(objectType) !== -1; +} + +/** + * ### .getOperator(message) + * + * Extract the operator from error message. + * Operator defined is based on below link + * https://nodejs.org/api/assert.html#assert_assert. + * + * Returns the `operator` or `undefined` value for an Assertion. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getOperator + * @api public + */ + +module.exports = function getOperator(obj, args) { + var operator = flag(obj, 'operator'); + var negate = flag(obj, 'negate'); + var expected = args[3]; + var msg = negate ? args[2] : args[1]; + + if (operator) { + return operator; + } + + if (typeof msg === 'function') msg = msg(); + + msg = msg || ''; + if (!msg) { + return undefined; + } + + if (/\shave\s/.test(msg)) { + return undefined; + } + + var isObject = isObjectType(expected); + if (/\snot\s/.test(msg)) { + return isObject ? 'notDeepStrictEqual' : 'notStrictEqual'; + } + + return isObject ? 'deepStrictEqual' : 'strictEqual'; +}; diff --git a/web/node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js b/web/node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..a4aa83a4c279907684028f77f316a3b272d2ea26 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js @@ -0,0 +1,29 @@ +/*! + * Chai - getOwnEnumerableProperties utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + +/** + * ### .getOwnEnumerableProperties(object) + * + * This allows the retrieval of directly-owned enumerable property names and + * symbols of an object. This function is necessary because Object.keys only + * returns enumerable property names, not enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerableProperties + * @api public + */ + +module.exports = function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +}; diff --git a/web/node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js b/web/node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js new file mode 100644 index 0000000000000000000000000000000000000000..823c6b7aae792b3862911d811c8ac1c3aae860c5 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js @@ -0,0 +1,27 @@ +/*! + * Chai - getOwnEnumerablePropertySymbols utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .getOwnEnumerablePropertySymbols(object) + * + * This allows the retrieval of directly-owned enumerable property symbols of an + * object. This function is necessary because Object.getOwnPropertySymbols + * returns both enumerable and non-enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerablePropertySymbols + * @api public + */ + +module.exports = function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== 'function') return []; + + return Object.getOwnPropertySymbols(obj).filter(function (sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +}; diff --git a/web/node_modules/chai/lib/chai/utils/getProperties.js b/web/node_modules/chai/lib/chai/utils/getProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..ccf9631aba0cb38aae6fe666cdbfbb2addd93b1a --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/getProperties.js @@ -0,0 +1,36 @@ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getProperties + * @api public + */ + +module.exports = function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + + function addProperty(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty); + proto = Object.getPrototypeOf(proto); + } + + return result; +}; diff --git a/web/node_modules/chai/lib/chai/utils/index.js b/web/node_modules/chai/lib/chai/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c12a38ed59b9ad2c561b905265ed83a543f442a8 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/index.js @@ -0,0 +1,178 @@ +/*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ + +/*! + * Dependencies that are used for multiple exports are required here only once + */ + +var pathval = require('pathval'); + +/*! + * test utility + */ + +exports.test = require('./test'); + +/*! + * type utility + */ + +exports.type = require('type-detect'); + +/*! + * expectTypes utility + */ +exports.expectTypes = require('./expectTypes'); + +/*! + * message utility + */ + +exports.getMessage = require('./getMessage'); + +/*! + * actual utility + */ + +exports.getActual = require('./getActual'); + +/*! + * Inspect util + */ + +exports.inspect = require('./inspect'); + +/*! + * Object Display util + */ + +exports.objDisplay = require('./objDisplay'); + +/*! + * Flag utility + */ + +exports.flag = require('./flag'); + +/*! + * Flag transferring utility + */ + +exports.transferFlags = require('./transferFlags'); + +/*! + * Deep equal utility + */ + +exports.eql = require('deep-eql'); + +/*! + * Deep path info + */ + +exports.getPathInfo = pathval.getPathInfo; + +/*! + * Check if a property exists + */ + +exports.hasProperty = pathval.hasProperty; + +/*! + * Function name + */ + +exports.getName = require('get-func-name'); + +/*! + * add Property + */ + +exports.addProperty = require('./addProperty'); + +/*! + * add Method + */ + +exports.addMethod = require('./addMethod'); + +/*! + * overwrite Property + */ + +exports.overwriteProperty = require('./overwriteProperty'); + +/*! + * overwrite Method + */ + +exports.overwriteMethod = require('./overwriteMethod'); + +/*! + * Add a chainable method + */ + +exports.addChainableMethod = require('./addChainableMethod'); + +/*! + * Overwrite chainable method + */ + +exports.overwriteChainableMethod = require('./overwriteChainableMethod'); + +/*! + * Compare by inspect method + */ + +exports.compareByInspect = require('./compareByInspect'); + +/*! + * Get own enumerable property symbols method + */ + +exports.getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + +/*! + * Get own enumerable properties method + */ + +exports.getOwnEnumerableProperties = require('./getOwnEnumerableProperties'); + +/*! + * Checks error against a given set of criteria + */ + +exports.checkError = require('check-error'); + +/*! + * Proxify util + */ + +exports.proxify = require('./proxify'); + +/*! + * addLengthGuard util + */ + +exports.addLengthGuard = require('./addLengthGuard'); + +/*! + * isProxyEnabled helper + */ + +exports.isProxyEnabled = require('./isProxyEnabled'); + +/*! + * isNaN method + */ + +exports.isNaN = require('./isNaN'); + +/*! + * getOperator method + */ + +exports.getOperator = require('./getOperator'); \ No newline at end of file diff --git a/web/node_modules/chai/lib/chai/utils/inspect.js b/web/node_modules/chai/lib/chai/utils/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..3c8305730f6403826163c9a20cf211508e9e1dea --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/inspect.js @@ -0,0 +1,33 @@ +// This is (almost) directly from Node.js utils +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + +var getName = require('get-func-name'); +var loupe = require('loupe'); +var config = require('../config'); + +module.exports = inspect; + +/** + * ### .inspect(obj, [showHidden], [depth], [colors]) + * + * Echoes the value of a value. Tries to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Boolean} showHidden Flag that shows hidden (not enumerable) + * properties of objects. Default is false. + * @param {Number} depth Depth in which to descend in object. Default is 2. + * @param {Boolean} colors Flag to turn on ANSI escape codes to color the + * output. Default is false (no coloring). + * @namespace Utils + * @name inspect + */ +function inspect(obj, showHidden, depth, colors) { + var options = { + colors: colors, + depth: (typeof depth === 'undefined' ? 2 : depth), + showHidden: showHidden, + truncate: config.truncateThreshold ? config.truncateThreshold : Infinity, + }; + return loupe.inspect(obj, options); +} diff --git a/web/node_modules/chai/lib/chai/utils/isNaN.js b/web/node_modules/chai/lib/chai/utils/isNaN.js new file mode 100644 index 0000000000000000000000000000000000000000..d64f7f4aacedf57ea1a30b832c2874cba8554629 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/isNaN.js @@ -0,0 +1,26 @@ +/*! + * Chai - isNaN utility + * Copyright(c) 2012-2015 Sakthipriyan Vairamani + * MIT Licensed + */ + +/** + * ### .isNaN(value) + * + * Checks if the given value is NaN or not. + * + * utils.isNaN(NaN); // true + * + * @param {Value} The value which has to be checked if it is NaN + * @name isNaN + * @api private + */ + +function isNaN(value) { + // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number + // section's NOTE. + return value !== value; +} + +// If ECMAScript 6's Number.isNaN is present, prefer that. +module.exports = Number.isNaN || isNaN; diff --git a/web/node_modules/chai/lib/chai/utils/isProxyEnabled.js b/web/node_modules/chai/lib/chai/utils/isProxyEnabled.js new file mode 100644 index 0000000000000000000000000000000000000000..11e58edfedbfca90f952bc508ce09d425722e444 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/isProxyEnabled.js @@ -0,0 +1,24 @@ +var config = require('../config'); + +/*! + * Chai - isProxyEnabled helper + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .isProxyEnabled() + * + * Helper function to check if Chai's proxy protection feature is enabled. If + * proxies are unsupported or disabled via the user's Chai config, then return + * false. Otherwise, return true. + * + * @namespace Utils + * @name isProxyEnabled + */ + +module.exports = function isProxyEnabled() { + return config.useProxy && + typeof Proxy !== 'undefined' && + typeof Reflect !== 'undefined'; +}; diff --git a/web/node_modules/chai/lib/chai/utils/objDisplay.js b/web/node_modules/chai/lib/chai/utils/objDisplay.js new file mode 100644 index 0000000000000000000000000000000000000000..2891c2dcc9168cb5570b14e0c58e45eb127c7f54 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/objDisplay.js @@ -0,0 +1,51 @@ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var inspect = require('./inspect'); +var config = require('../config'); + +/** + * ### .objDisplay(object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {Mixed} javascript object to inspect + * @returns {string} stringified object + * @name objDisplay + * @namespace Utils + * @api public + */ + +module.exports = function objDisplay(obj) { + var str = inspect(obj) + , type = Object.prototype.toString.call(obj); + + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type === '[object Function]') { + return !obj.name || obj.name === '' + ? '[Function]' + : '[Function: ' + obj.name + ']'; + } else if (type === '[object Array]') { + return '[ Array(' + obj.length + ') ]'; + } else if (type === '[object Object]') { + var keys = Object.keys(obj) + , kstr = keys.length > 2 + ? keys.splice(0, 2).join(', ') + ', ...' + : keys.join(', '); + return '{ Object (' + kstr + ') }'; + } else { + return str; + } + } else { + return str; + } +}; diff --git a/web/node_modules/chai/lib/chai/utils/overwriteChainableMethod.js b/web/node_modules/chai/lib/chai/utils/overwriteChainableMethod.js new file mode 100644 index 0000000000000000000000000000000000000000..4b38569e41da22f7f400d2d35d3377e91de17c71 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/overwriteChainableMethod.js @@ -0,0 +1,69 @@ +/*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) + * + * Overwrites an already existing chainable method + * and provides access to the previous function or + * property. Must return functions to be used for + * name. + * + * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', + * function (_super) { + * } + * , function (_super) { + * } + * ); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteChainableMethod('foo', fn, fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.have.lengthOf(3); + * expect(myFoo).to.have.lengthOf.above(3); + * + * @param {Object} ctx object whose method / property is to be overwritten + * @param {String} name of method / property to overwrite + * @param {Function} method function that returns a function to be used for name + * @param {Function} chainingBehavior function that returns a function to be used for property + * @namespace Utils + * @name overwriteChainableMethod + * @api public + */ + +module.exports = function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { + var result = chainingBehavior(_chainingBehavior).call(this); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + var _method = chainableBehavior.method; + chainableBehavior.method = function overwritingChainableMethodWrapper() { + var result = method(_method).apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; +}; diff --git a/web/node_modules/chai/lib/chai/utils/overwriteMethod.js b/web/node_modules/chai/lib/chai/utils/overwriteMethod.js new file mode 100644 index 0000000000000000000000000000000000000000..7925e05ffeac1027bfca7c3d19828967f857b006 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/overwriteMethod.js @@ -0,0 +1,92 @@ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteMethod(ctx, name, fn) + * + * Overwrites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + * return function (str) { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.value).to.equal(str); + * } else { + * _super.apply(this, arguments); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.equal('bar'); + * + * @param {Object} ctx object whose method is to be overwritten + * @param {String} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @namespace Utils + * @name overwriteMethod + * @api public + */ + +module.exports = function overwriteMethod(ctx, name, method) { + var _method = ctx[name] + , _super = function () { + throw new Error(name + ' is not a function'); + }; + + if (_method && 'function' === typeof _method) + _super = _method; + + var overwritingMethodWrapper = function () { + // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this + // function to be the starting point for removing implementation frames from + // the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingMethodWrapper); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion + // from changing the `ssfi` flag. By this point, the `ssfi` flag is already + // set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = method(_super).apply(this, arguments); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +}; diff --git a/web/node_modules/chai/lib/chai/utils/overwriteProperty.js b/web/node_modules/chai/lib/chai/utils/overwriteProperty.js new file mode 100644 index 0000000000000000000000000000000000000000..5f870b02a80ffb8941157ba020651223f8298e34 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/overwriteProperty.js @@ -0,0 +1,92 @@ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var flag = require('./flag'); +var isProxyEnabled = require('./isProxyEnabled'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteProperty(ctx, name, fn) + * + * Overwrites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + * return function () { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.name).to.equal('bar'); + * } else { + * _super.call(this); + * } + * } + * }); + * + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.ok; + * + * @param {Object} ctx object whose property is to be overwritten + * @param {String} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @namespace Utils + * @name overwriteProperty + * @api public + */ + +module.exports = function overwriteProperty(ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name) + , _super = function () {}; + + if (_get && 'function' === typeof _get.get) + _super = _get.get + + Object.defineProperty(ctx, name, + { get: function overwritingPropertyGetter() { + // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this + // function to be the starting point for removing implementation frames + // from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingPropertyGetter); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten + // assertion from changing the `ssfi` flag. By this point, the `ssfi` + // flag is already set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = getter(_super).call(this); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +}; diff --git a/web/node_modules/chai/lib/chai/utils/proxify.js b/web/node_modules/chai/lib/chai/utils/proxify.js new file mode 100644 index 0000000000000000000000000000000000000000..4bbbee38c57f174615ff7a310556f12c8f45e515 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/proxify.js @@ -0,0 +1,147 @@ +var config = require('../config'); +var flag = require('./flag'); +var getProperties = require('./getProperties'); +var isProxyEnabled = require('./isProxyEnabled'); + +/*! + * Chai - proxify utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .proxify(object) + * + * Return a proxy of given object that throws an error when a non-existent + * property is read. By default, the root cause is assumed to be a misspelled + * property, and thus an attempt is made to offer a reasonable suggestion from + * the list of existing properties. However, if a nonChainableMethodName is + * provided, then the root cause is instead a failure to invoke a non-chainable + * method prior to reading the non-existent property. + * + * If proxies are unsupported or disabled via the user's Chai config, then + * return object without modification. + * + * @param {Object} obj + * @param {String} nonChainableMethodName + * @namespace Utils + * @name proxify + */ + +var builtins = ['__flags', '__methods', '_obj', 'assert']; + +module.exports = function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + + return new Proxy(obj, { + get: function proxyGetter(target, property) { + // This check is here because we should not throw errors on Symbol properties + // such as `Symbol.toStringTag`. + // The values for which an error should be thrown can be configured using + // the `config.proxyExcludedKeys` setting. + if (typeof property === 'string' && + config.proxyExcludedKeys.indexOf(property) === -1 && + !Reflect.has(target, property)) { + // Special message for invalid property access of non-chainable methods. + if (nonChainableMethodName) { + throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + + property + '. See docs for proper usage of "' + + nonChainableMethodName + '".'); + } + + // If the property is reasonably close to an existing Chai property, + // suggest that property to the user. Only suggest properties with a + // distance less than 4. + var suggestion = null; + var suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + !Object.prototype.hasOwnProperty(prop) && + builtins.indexOf(prop) === -1 + ) { + var dist = stringDistanceCapped( + property, + prop, + suggestionDistance + ); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + + if (suggestion !== null) { + throw Error('Invalid Chai property: ' + property + + '. Did you mean "' + suggestion + '"?'); + } else { + throw Error('Invalid Chai property: ' + property); + } + } + + // Use this proxy getter as the starting point for removing implementation + // frames from the stack trace of a failed assertion. For property + // assertions, this prevents the proxy getter from showing up in the stack + // trace since it's invoked before the property getter. For method and + // chainable method assertions, this flag will end up getting changed to + // the method wrapper, which is good since this frame will no longer be in + // the stack once the method is invoked. Note that Chai builtin assertion + // properties such as `__flags` are skipped since this is only meant to + // capture the starting point of an assertion. This step is also skipped + // if the `lockSsfi` flag is set, thus indicating that this assertion is + // being called from within another assertion. In that case, the `ssfi` + // flag is already set to the outer assertion's starting point. + if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { + flag(target, 'ssfi', proxyGetter); + } + + return Reflect.get(target, property); + } + }); +}; + +/** + * # stringDistanceCapped(strA, strB, cap) + * Return the Levenshtein distance between two strings, but no more than cap. + * @param {string} strA + * @param {string} strB + * @param {number} number + * @return {number} min(string distance between strA and strB, cap) + * @api private + */ + +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + + var memo = []; + // `memo` is a two-dimensional array containing distances. + // memo[i][j] is the distance between strA.slice(0, i) and + // strB.slice(0, j). + for (var i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (var j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + + for (var i = 1; i <= strA.length; i++) { + var ch = strA.charCodeAt(i - 1); + for (var j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + + return memo[strA.length][strB.length]; +} diff --git a/web/node_modules/chai/lib/chai/utils/test.js b/web/node_modules/chai/lib/chai/utils/test.js new file mode 100644 index 0000000000000000000000000000000000000000..277a2a5c2b32286a6c668124ccbd0f448e6c2dc2 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/test.js @@ -0,0 +1,28 @@ +/*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var flag = require('./flag'); + +/** + * ### .test(object, expression) + * + * Test an object for expression. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name test + */ + +module.exports = function test(obj, args) { + var negate = flag(obj, 'negate') + , expr = args[0]; + return negate ? !expr : expr; +}; diff --git a/web/node_modules/chai/lib/chai/utils/transferFlags.js b/web/node_modules/chai/lib/chai/utils/transferFlags.js new file mode 100644 index 0000000000000000000000000000000000000000..7b501900daf00864589d22eb6b93c65602cc6e29 --- /dev/null +++ b/web/node_modules/chai/lib/chai/utils/transferFlags.js @@ -0,0 +1,45 @@ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, `lockSsfi`, + * and `message`) will not be transferred. + * + * + * var newAssertion = new Assertion(); + * utils.transferFlags(assertion, newAssertion); + * + * var anotherAssertion = new Assertion(myObj); + * utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {Assertion} assertion the assertion to transfer the flags from + * @param {Object} object the object to transfer the flags to; usually a new assertion + * @param {Boolean} includeAll + * @namespace Utils + * @name transferFlags + * @api private + */ + +module.exports = function transferFlags(assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + + if (!object.__flags) { + object.__flags = Object.create(null); + } + + includeAll = arguments.length === 3 ? includeAll : true; + + for (var flag in flags) { + if (includeAll || + (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { + object.__flags[flag] = flags[flag]; + } + } +}; diff --git a/web/node_modules/chai/package.json b/web/node_modules/chai/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ad95c002605bb5b95ef9302e22c4bce36f8a4812 --- /dev/null +++ b/web/node_modules/chai/package.json @@ -0,0 +1,63 @@ +{ + "author": "Jake Luer ", + "name": "chai", + "description": "BDD/TDD assertion library for node.js and the browser. Test framework agnostic.", + "keywords": [ + "test", + "assertion", + "assert", + "testing", + "chai" + ], + "homepage": "http://chaijs.com", + "license": "MIT", + "contributors": [ + "Jake Luer ", + "Domenic Denicola (http://domenicdenicola.com)", + "Veselin Todorov ", + "John Firebaugh " + ], + "version": "4.4.1", + "repository": { + "type": "git", + "url": "https://github.com/chaijs/chai" + }, + "bugs": { + "url": "https://github.com/chaijs/chai/issues" + }, + "main": "./index", + "exports": { + ".": { + "require": "./index.js", + "import": "./index.mjs" + }, + "./*": "./*" + }, + "scripts": { + "test": "make test" + }, + "engines": { + "node": ">=4" + }, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.0.8" + }, + "devDependencies": { + "browserify": "^16.5.2", + "bump-cli": "^2.7.1", + "codecov": "^3.8.3", + "istanbul": "^0.4.5", + "karma": "^6.4.2", + "karma-chrome-launcher": "^2.2.0", + "karma-firefox-launcher": "^1.3.0", + "karma-mocha": "^2.0.1", + "karma-sauce-launcher": "^4.1.4", + "mocha": "^10.2.0" + } +} diff --git a/web/node_modules/chai/register-assert.js b/web/node_modules/chai/register-assert.js new file mode 100644 index 0000000000000000000000000000000000000000..f80cb4deda772a405d0c6ff26f91b41590a395ac --- /dev/null +++ b/web/node_modules/chai/register-assert.js @@ -0,0 +1 @@ +global.assert = require('./').assert; diff --git a/web/node_modules/chai/register-expect.js b/web/node_modules/chai/register-expect.js new file mode 100644 index 0000000000000000000000000000000000000000..f905c3a207699485fa3b0cbc37fad38c48c9a801 --- /dev/null +++ b/web/node_modules/chai/register-expect.js @@ -0,0 +1 @@ +global.expect = require('./').expect; diff --git a/web/node_modules/chai/register-should.js b/web/node_modules/chai/register-should.js new file mode 100644 index 0000000000000000000000000000000000000000..5dab96fc5e17ec9a8ccfd09ffcd45fc8450ddea3 --- /dev/null +++ b/web/node_modules/chai/register-should.js @@ -0,0 +1 @@ +global.should = require('./').should(); diff --git a/web/node_modules/chai/sauce.browsers.js b/web/node_modules/chai/sauce.browsers.js new file mode 100644 index 0000000000000000000000000000000000000000..328f0c70588d92e73049cf4ca7a20c8ce5f497c2 --- /dev/null +++ b/web/node_modules/chai/sauce.browsers.js @@ -0,0 +1,106 @@ + +/*! + * Chrome + */ + +exports['SL_Chrome'] = { + base: 'SauceLabs' + , browserName: 'chrome' +}; + +/*! + * Firefox + */ + + exports['SL_Firefox'] = { + base: 'SauceLabs' + , browserName: 'firefox' + }; + + exports['SL_Firefox_ESR'] = { + base: 'SauceLabs' + , browserName: 'firefox' + , version: 38 + }; + +/*! + * Internet Explorer + */ + +exports['SL_IE'] = { + base: 'SauceLabs' + , browserName: 'internet explorer' +}; + +/*! + * TODO: fails because of Uint8Array support + * +exports['SL_IE_Old'] = { + base: 'SauceLabs' + , browserName: 'internet explorer' + , version: 10 +}; +*/ + +exports['SL_Edge'] = { + base: 'SauceLabs' + , browserName: 'microsoftedge' +}; + +/*! + * Safari + */ + +exports['SL_Safari'] = { + base: 'SauceLabs' + , browserName: 'safari' + , platform: 'Mac 10.11' +}; + +/*! + * iPhone + */ + +/*! + * TODO: These take forever to boot or shut down. Causes timeout. + * + +exports['SL_iPhone_6'] = { + base: 'SauceLabs' + , browserName: 'iphone' + , platform: 'Mac 10.8' + , version: '6' +}; + +exports['SL_iPhone_5-1'] = { + base: 'SauceLabs' + , browserName: 'iphone' + , platform: 'Mac 10.8' + , version: '5.1' +}; + +exports['SL_iPhone_5'] = { + base: 'SauceLabs' + , browserName: 'iphone' + , platform: 'Mac 10.6' + , version: '5' +}; + +*/ + +/*! + * Android + */ + +/*! + * TODO: fails because of error serialization + * + +exports['SL_Android_4'] = { + base: 'SauceLabs' + , browserName: 'android' + , platform: 'Linux' + , version: '4' +}; + +*/ diff --git a/web/node_modules/check-error/LICENSE b/web/node_modules/check-error/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7ea799f0ef4a80112178975b5f15d97c4863e09e --- /dev/null +++ b/web/node_modules/check-error/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Jake Luer (http://alogicalparadox.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/web/node_modules/check-error/README.md b/web/node_modules/check-error/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1fa64c3d7fa919de26f4b3beb7cb942e59e4491f --- /dev/null +++ b/web/node_modules/check-error/README.md @@ -0,0 +1,207 @@ +

+ + ChaiJS check-error + +

+ +

+ Error comparison and information related utility for node and the browser. +

+ +

+ + license:mit + + + tag:? + + + build:? + + + coverage:? + + + npm:? + + + dependencies:? + + + devDependencies:? + +
+ + Selenium Test Status + +
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is Check-Error? + +Check-Error is a module which you can use to retrieve an Error's information such as its `message` or `constructor` name and also to check whether two Errors are compatible based on their messages, constructors or even instances. + +## Installation + +### Node.js + +`check-error` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install check-error + +### Browsers + +You can also use it within the browser; install via npm and use the `check-error.js` file found within the download. For example: + +```html + +``` + +## Usage + +The primary export of `check-error` is an object which has the following methods: + +* `compatibleInstance(err, errorLike)` - Checks if an error is compatible with another `errorLike` object. If `errorLike` is an error instance we do a strict comparison, otherwise we return `false` by default, because instances of objects can only be compatible if they're both error instances. +* `compatibleConstructor(err, errorLike)` - Checks if an error's constructor is compatible with another `errorLike` object. If `err` has the same constructor as `errorLike` or if `err` is an instance of `errorLike`. +* `compatibleMessage(err, errMatcher)` - Checks if an error message is compatible with an `errMatcher` RegExp or String (we check if the message contains the String). +* `getConstructorName(errorLike)` - Retrieves the name of a constructor, an error's constructor or `errorLike` itself if it's not an error instance or constructor. +* `getMessage(err)` - Retrieves the message of an error or `err` itself if it's a String. If `err` or `err.message` is undefined we return an empty String. + +```js +var checkError = require('check-error'); +``` + +#### .compatibleInstance(err, errorLike) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.compatibleInstance(caughtErr, sameInstance); // true +checkError.compatibleInstance(caughtErr, new TypeError('Another error')); // false +``` + +#### .compatibleConstructor(err, errorLike) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +checkError.compatibleConstructor(caughtErr, Error); // true +checkError.compatibleConstructor(caughtErr, TypeError); // true +checkError.compatibleConstructor(caughtErr, RangeError); // false +``` + +#### .compatibleMessage(err, errMatcher) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.compatibleMessage(caughtErr, /TypeError$/); // true +checkError.compatibleMessage(caughtErr, 'I am a'); // true +checkError.compatibleMessage(caughtErr, /unicorn/); // false +checkError.compatibleMessage(caughtErr, 'I do not exist'); // false +``` + +#### .getConstructorName(errorLike) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.getConstructorName(caughtErr) // 'TypeError' +``` + +#### .getMessage(err) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.getMessage(caughtErr) // 'I am a TypeError' +``` diff --git a/web/node_modules/check-error/check-error.js b/web/node_modules/check-error/check-error.js new file mode 100644 index 0000000000000000000000000000000000000000..0070ed4586ce0473ac2034cb9150db29759269e9 --- /dev/null +++ b/web/node_modules/check-error/check-error.js @@ -0,0 +1 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * MIT Licensed + */ + +var getFunctionName = require('get-func-name'); +/** + * ### .checkError + * + * Checks that an error conforms to a given set of criteria and/or retrieves information about it. + * + * @api public + */ + +/** + * ### .compatibleInstance(thrown, errorLike) + * + * Checks if two instances are compatible (strict equal). + * Returns false if errorLike is not an instance of Error, because instances + * can only be compatible if they're both error instances. + * + * @name compatibleInstance + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleInstance(thrown, errorLike) { + return errorLike instanceof Error && thrown === errorLike; +} + +/** + * ### .compatibleConstructor(thrown, errorLike) + * + * Checks if two constructors are compatible. + * This function can receive either an error constructor or + * an error instance as the `errorLike` argument. + * Constructors are compatible if they're the same or if one is + * an instance of another. + * + * @name compatibleConstructor + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleConstructor(thrown, errorLike) { + if (errorLike instanceof Error) { + // If `errorLike` is an instance of any error we compare their constructors + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if (errorLike.prototype instanceof Error || errorLike === Error) { + // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + + return false; +} + +/** + * ### .compatibleMessage(thrown, errMatcher) + * + * Checks if an error's message is compatible with a matcher (String or RegExp). + * If the message contains the String or passes the RegExp test, + * it is considered compatible. + * + * @name compatibleMessage + * @param {Error} thrown error + * @param {String|RegExp} errMatcher to look for into the message + * @namespace Utils + * @api public + */ + +function compatibleMessage(thrown, errMatcher) { + var comparisonString = typeof thrown === 'string' ? thrown : thrown.message; + if (errMatcher instanceof RegExp) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === 'string') { + return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers + } + + return false; +} + +/** + * ### .getConstructorName(errorLike) + * + * Gets the constructor name for an Error instance or constructor itself. + * + * @name getConstructorName + * @param {Error|ErrorConstructor} errorLike + * @namespace Utils + * @api public + */ + +function getConstructorName(errorLike) { + var constructorName = errorLike; + if (errorLike instanceof Error) { + constructorName = getFunctionName(errorLike.constructor); + } else if (typeof errorLike === 'function') { + // If `err` is not an instance of Error it is an error constructor itself or another function. + // If we've got a common function we get its name, otherwise we may need to create a new instance + // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. + constructorName = getFunctionName(errorLike); + if (constructorName === '') { + var newConstructorName = getFunctionName(new errorLike()); // eslint-disable-line new-cap + constructorName = newConstructorName || constructorName; + } + } + + return constructorName; +} + +/** + * ### .getMessage(errorLike) + * + * Gets the error message from an error. + * If `err` is a String itself, we return it. + * If the error has no message, we return an empty string. + * + * @name getMessage + * @param {Error|String} errorLike + * @namespace Utils + * @api public + */ + +function getMessage(errorLike) { + var msg = ''; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === 'string') { + msg = errorLike; + } + + return msg; +} + +module.exports = { + compatibleInstance: compatibleInstance, + compatibleConstructor: compatibleConstructor, + compatibleMessage: compatibleMessage, + getMessage: getMessage, + getConstructorName: getConstructorName, +}; diff --git a/web/node_modules/check-error/package.json b/web/node_modules/check-error/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4084f78c299fe09a775f34ad3d05902f8e746f17 --- /dev/null +++ b/web/node_modules/check-error/package.json @@ -0,0 +1,87 @@ +{ + "name": "check-error", + "description": "Error comparison and information related utility for node and the browser", + "keywords": [ + "check-error", + "error", + "chai util" + ], + "license": "MIT", + "author": "Jake Luer (http://alogicalparadox.com)", + "contributors": [ + "David Losert (https://github.com/davelosert)", + "Keith Cirkel (https://github.com/keithamus)", + "Miroslav Bajtoš (https://github.com/bajtos)", + "Lucas Fernandes da Costa (https://github.com/lucasfcosta)" + ], + "files": [ + "index.js", + "check-error.js" + ], + "main": "./index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/chaijs/check-error.git" + }, + "scripts": { + "build": "browserify --bare $npm_package_main --standalone checkError -o check-error.js", + "lint": "eslint --ignore-path .gitignore .", + "prepublish": "npm run build", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser && npm run upload-coverage", + "test:browser": "karma start --singleRun=true", + "test:node": "istanbul cover _mocha", + "upload-coverage": "lcov-result-merger 'coverage/**/lcov.info' | coveralls; exit 0" + }, + "config": { + "ghooks": { + "commit-msg": "validate-commit-msg" + } + }, + "eslintConfig": { + "extends": [ + "strict/es5" + ], + "env": { + "es6": true + }, + "globals": { + "HTMLElement": false + }, + "rules": { + "complexity": 0, + "max-statements": 0 + } + }, + "dependencies": { + "get-func-name": "^2.0.2" + }, + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^1.0.0", + "coveralls": "2.11.9", + "eslint": "^2.4.0", + "eslint-config-strict": "^8.5.0", + "eslint-plugin-filenames": "^0.2.0", + "ghooks": "^1.0.1", + "istanbul": "^0.4.2", + "karma": "^0.13.22", + "karma-browserify": "^5.0.2", + "karma-coverage": "^0.5.5", + "karma-mocha": "^0.2.2", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sauce-launcher": "^0.3.1", + "lcov-result-merger": "^1.0.2", + "mocha": "^2.4.5", + "phantomjs-prebuilt": "^2.1.5", + "semantic-release": "^4.3.5", + "simple-assert": "^1.0.0", + "travis-after-all": "^1.4.4", + "validate-commit-msg": "^2.3.1" + }, + "engines": { + "node": "*" + }, + "version": "1.0.3" +} diff --git a/web/node_modules/cross-spawn/CHANGELOG.md b/web/node_modules/cross-spawn/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d07c9e5c310e6968e983346557288e96c085a082 --- /dev/null +++ b/web/node_modules/cross-spawn/CHANGELOG.md @@ -0,0 +1,130 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [7.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.2...v7.0.3) (2020-05-25) + + +### Bug Fixes + +* detect path key based on correct environment ([#133](https://github.com/moxystudio/node-cross-spawn/issues/133)) ([159e7e9](https://github.com/moxystudio/node-cross-spawn/commit/159e7e9785e57451cba034ae51719f97135074ae)) + +### [7.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.1...v7.0.2) (2020-04-04) + + +### Bug Fixes + +* fix worker threads in Node >=11.10.0 ([#132](https://github.com/moxystudio/node-cross-spawn/issues/132)) ([6c5b4f0](https://github.com/moxystudio/node-cross-spawn/commit/6c5b4f015814a6c4f6b33230dfd1a860aedc0aaf)) + +### [7.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.0...v7.0.1) (2019-10-07) + + +### Bug Fixes + +* **core:** support worker threads ([#127](https://github.com/moxystudio/node-cross-spawn/issues/127)) ([cfd49c9](https://github.com/moxystudio/node-cross-spawn/commit/cfd49c9)) + +## [7.0.0](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.5...v7.0.0) (2019-09-03) + + +### ⚠ BREAKING CHANGES + +* drop support for Node.js < 8 + +* drop support for versions below Node.js 8 ([#125](https://github.com/moxystudio/node-cross-spawn/issues/125)) ([16feb53](https://github.com/moxystudio/node-cross-spawn/commit/16feb53)) + + +## [6.0.5](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.4...v6.0.5) (2018-03-02) + + +### Bug Fixes + +* avoid using deprecated Buffer constructor ([#94](https://github.com/moxystudio/node-cross-spawn/issues/94)) ([d5770df](https://github.com/moxystudio/node-cross-spawn/commit/d5770df)), closes [/nodejs.org/api/deprecations.html#deprecations_dep0005](https://github.com//nodejs.org/api/deprecations.html/issues/deprecations_dep0005) + + + + +## [6.0.4](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.3...v6.0.4) (2018-01-31) + + +### Bug Fixes + +* fix paths being incorrectly normalized on unix ([06ee3c6](https://github.com/moxystudio/node-cross-spawn/commit/06ee3c6)), closes [#90](https://github.com/moxystudio/node-cross-spawn/issues/90) + + + + +## [6.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.2...v6.0.3) (2018-01-23) + + + + +## [6.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.1...v6.0.2) (2018-01-23) + + + + +## [6.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.0...v6.0.1) (2018-01-23) + + + + +# [6.0.0](https://github.com/moxystudio/node-cross-spawn/compare/5.1.0...6.0.0) (2018-01-23) + + +### Bug Fixes + +* fix certain arguments not being correctly escaped or causing batch syntax error ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)), closes [#82](https://github.com/moxystudio/node-cross-spawn/issues/82) [#51](https://github.com/moxystudio/node-cross-spawn/issues/51) +* fix commands as posix relatixe paths not working correctly, e.g.: `./my-command` ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* fix `options` argument being mutated ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* fix commands resolution when PATH was actually Path ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) + + +### Features + +* improve compliance with node's ENOENT errors ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) +* improve detection of node's shell option support ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)) + + +### Chores + +* upgrade tooling +* upgrate project to es6 (node v4) + + +### BREAKING CHANGES + +* remove support for older nodejs versions, only `node >= 4` is supported + + + +## [5.1.0](https://github.com/moxystudio/node-cross-spawn/compare/5.0.1...5.1.0) (2017-02-26) + + +### Bug Fixes + +* fix `options.shell` support for NodeJS [v4.8](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V4.md#4.8.0) + + + +## [5.0.1](https://github.com/moxystudio/node-cross-spawn/compare/5.0.0...5.0.1) (2016-11-04) + + +### Bug Fixes + +* fix `options.shell` support for NodeJS v7 + + + +# [5.0.0](https://github.com/moxystudio/node-cross-spawn/compare/4.0.2...5.0.0) (2016-10-30) + + +## Features + +* add support for `options.shell` +* improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module + + +## Chores + +* refactor some code to make it more clear +* update README caveats diff --git a/web/node_modules/cross-spawn/LICENSE b/web/node_modules/cross-spawn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8407b9a30f51b0da9eaac366bdde18d900e951ba --- /dev/null +++ b/web/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/web/node_modules/cross-spawn/README.md b/web/node_modules/cross-spawn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a4da8447fb5b16972f9462cef037be3aa1d813 --- /dev/null +++ b/web/node_modules/cross-spawn/README.md @@ -0,0 +1,96 @@ +# cross-spawn + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-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 +[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn +[travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.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 +[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn +[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg +[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn +[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg +[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev +[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.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/web/node_modules/cross-spawn/index.js b/web/node_modules/cross-spawn/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5509742ca9fa8f500a66e6e7195037a7c1d5e49e --- /dev/null +++ b/web/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/web/node_modules/cross-spawn/lib/enoent.js b/web/node_modules/cross-spawn/lib/enoent.js new file mode 100644 index 0000000000000000000000000000000000000000..14df9b623d0a203e124a95dae7c2c53390aa7a2f --- /dev/null +++ b/web/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, 'spawn'); + + 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/web/node_modules/cross-spawn/lib/parse.js b/web/node_modules/cross-spawn/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..0129d74774a8a08d8c5e92c2d602114e590d8db8 --- /dev/null +++ b/web/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/web/node_modules/cross-spawn/lib/util/escape.js b/web/node_modules/cross-spawn/lib/util/escape.js new file mode 100644 index 0000000000000000000000000000000000000000..b0bb84c3a14092cfbbd1b860eb8c5f41fcc3c165 --- /dev/null +++ b/web/node_modules/cross-spawn/lib/util/escape.js @@ -0,0 +1,45 @@ +'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 + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/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'); + + // 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/web/node_modules/cross-spawn/lib/util/readShebang.js b/web/node_modules/cross-spawn/lib/util/readShebang.js new file mode 100644 index 0000000000000000000000000000000000000000..5e83733fef260f23f865d9cafa42b1192b91c9f8 --- /dev/null +++ b/web/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/web/node_modules/cross-spawn/lib/util/resolveCommand.js b/web/node_modules/cross-spawn/lib/util/resolveCommand.js new file mode 100644 index 0000000000000000000000000000000000000000..7972455008e917b651c1ca9a9a232ad61b0dc833 --- /dev/null +++ b/web/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/web/node_modules/cross-spawn/package.json b/web/node_modules/cross-spawn/package.json new file mode 100644 index 0000000000000000000000000000000000000000..232ff97e04b213543c550d8fe1d9b0860b9c2662 --- /dev/null +++ b/web/node_modules/cross-spawn/package.json @@ -0,0 +1,73 @@ +{ + "name": "cross-spawn", + "version": "7.0.3", + "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": "^7.0.0" + }, + "engines": { + "node": ">= 8" + } +} diff --git a/web/node_modules/debug/LICENSE b/web/node_modules/debug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1a9820e262b26b60fe71a4dcd9bc9cfd0a01f26e --- /dev/null +++ b/web/node_modules/debug/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/web/node_modules/debug/README.md b/web/node_modules/debug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9c3e047c2b22aacd54f096af48f918217e06d84 --- /dev/null +++ b/web/node_modules/debug/README.md @@ -0,0 +1,481 @@ +# debug +[![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. + + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +`disable()` + +Will disable all namespaces. The functions returns the namespaces currently +enabled (and skipped). This can be useful if you want to disable debugging +temporarily without knowing what was enabled to begin with. + +For example: + +```js +let debug = require('debug'); +debug.enable('foo:*,-foo:bar'); +let namespaces = debug.disable(); +debug.enable(namespaces); +``` + +Note: There is no guarantee that the string will be identical to the initial +enable string, but semantically they will be identical. + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + +## Usage in child processes + +Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. +For example: + +```javascript +worker = fork(WORKER_WRAP_PATH, [workerPath], { + stdio: [ + /* stdin: */ 0, + /* stdout: */ 'pipe', + /* stderr: */ 'pipe', + 'ipc', + ], + env: Object.assign({}, process.env, { + DEBUG_COLORS: 1 // without this settings, colors won't be shown + }), +}); + +worker.stderr.pipe(process.stderr, { end: false }); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + - Josh Junon + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/web/node_modules/debug/package.json b/web/node_modules/debug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3bcdc242fc0675883ce46ba5dca919d116c46a83 --- /dev/null +++ b/web/node_modules/debug/package.json @@ -0,0 +1,59 @@ +{ + "name": "debug", + "version": "4.3.4", + "repository": { + "type": "git", + "url": "git://github.com/debug-js/debug.git" + }, + "description": "Lightweight debugging utility for Node.js and the browser", + "keywords": [ + "debug", + "log", + "debugger" + ], + "files": [ + "src", + "LICENSE", + "README.md" + ], + "author": "Josh Junon ", + "contributors": [ + "TJ Holowaychuk ", + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "scripts": { + "lint": "xo", + "test": "npm run test:node && npm run test:browser && npm run lint", + "test:node": "istanbul cover _mocha -- test.js", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls" + }, + "dependencies": { + "ms": "2.1.2" + }, + "devDependencies": { + "brfs": "^2.0.1", + "browserify": "^16.2.3", + "coveralls": "^3.0.2", + "istanbul": "^0.4.5", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "xo": "^0.23.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "engines": { + "node": ">=6.0" + } +} diff --git a/web/node_modules/debug/src/browser.js b/web/node_modules/debug/src/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..cd0fc35d1ee11e0d6e15421021a54c18958e04d9 --- /dev/null +++ b/web/node_modules/debug/src/browser.js @@ -0,0 +1,269 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/web/node_modules/debug/src/common.js b/web/node_modules/debug/src/common.js new file mode 100644 index 0000000000000000000000000000000000000000..e3291b20faa1a61fa5acff50d84dba10a97cc3b6 --- /dev/null +++ b/web/node_modules/debug/src/common.js @@ -0,0 +1,274 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/web/node_modules/debug/src/index.js b/web/node_modules/debug/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bf4c57f259df2e16761b45e2636db307c89ba419 --- /dev/null +++ b/web/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/web/node_modules/debug/src/node.js b/web/node_modules/debug/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..79bc085cb0230c69aaeb76bbc1374f43ab6414f4 --- /dev/null +++ b/web/node_modules/debug/src/node.js @@ -0,0 +1,263 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/web/node_modules/deep-eql/LICENSE b/web/node_modules/deep-eql/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7ea799f0ef4a80112178975b5f15d97c4863e09e --- /dev/null +++ b/web/node_modules/deep-eql/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Jake Luer (http://alogicalparadox.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/web/node_modules/deep-eql/README.md b/web/node_modules/deep-eql/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f6e1b85cf79a26d1d625542cef5926b6bf124c0a --- /dev/null +++ b/web/node_modules/deep-eql/README.md @@ -0,0 +1,93 @@ +

+ + deep-eql + +

+ +

+ Improved deep equality testing for node and the browser. +

+ +

+ + build:? + + coverage:? + + dependencies:? + + devDependencies:? + +
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is Deep-Eql? + +Deep Eql is a module which you can use to determine if two objects are "deeply" equal - that is, rather than having referential equality (`a === b`), this module checks an object's keys recursively, until it finds primitives to check for referential equality. For more on equality in JavaScript, read [the comparison operators article on mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators). + +As an example, take the following: + +```js +1 === 1 // These are primitives, they hold the same reference - they are strictly equal +1 == '1' // These are two different primitives, through type coercion they hold the same value - they are loosely equal +{ a: 1 } !== { a: 1 } // These are two different objects, they hold different references and so are not strictly equal - even though they hold the same values inside +{ a: 1 } != { a: 1 } // They have the same type, meaning loose equality performs the same check as strict equality - they are still not equal. + +var deepEql = require("deep-eql"); +deepEql({ a: 1 }, { a: 1 }) === true // deepEql can determine that they share the same keys and those keys share the same values, therefore they are deeply equal! +``` + +## Installation + +### Node.js + +`deep-eql` is available on [npm](http://npmjs.org). + + $ npm install deep-eql + +## Usage + +The primary export of `deep-eql` is function that can be given two objects to compare. It will always return a boolean which can be used to determine if two objects are deeply equal. + +### Rules + +- Strict equality for non-traversable nodes according to [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is): + - `eql(NaN, NaN).should.be.true;` + - `eql(-0, +0).should.be.false;` +- All own and inherited enumerable properties are considered: + - `eql(Object.create({ foo: { a: 1 } }), Object.create({ foo: { a: 1 } })).should.be.true;` + - `eql(Object.create({ foo: { a: 1 } }), Object.create({ foo: { a: 2 } })).should.be.false;` +- When comparing `Error` objects, only `name`, `message`, and `code` properties are considered, regardless of enumerability: + - `eql(Error('foo'), Error('foo')).should.be.true;` + - `eql(Error('foo'), Error('bar')).should.be.false;` + - `eql(Error('foo'), TypeError('foo')).should.be.false;` + - `eql(Object.assign(Error('foo'), { code: 42 }), Object.assign(Error('foo'), { code: 42 })).should.be.true;` + - `eql(Object.assign(Error('foo'), { code: 42 }), Object.assign(Error('foo'), { code: 13 })).should.be.false;` + - `eql(Object.assign(Error('foo'), { otherProp: 42 }), Object.assign(Error('foo'), { otherProp: 13 })).should.be.true;` +- Arguments are not Arrays: + - `eql([], arguments).should.be.false;` + - `eql([], Array.prototype.slice.call(arguments)).should.be.true;` diff --git a/web/node_modules/deep-eql/deep-eql.js b/web/node_modules/deep-eql/deep-eql.js new file mode 100644 index 0000000000000000000000000000000000000000..0070ed4586ce0473ac2034cb9150db29759269e9 --- /dev/null +++ b/web/node_modules/deep-eql/deep-eql.js @@ -0,0 +1 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * MIT Licensed + */ + +var type = require('type-detect'); +function FakeMap() { + this._key = 'chai/deep-eql__' + Math.random() + Date.now(); +} + +FakeMap.prototype = { + get: function get(key) { + return key[this._key]; + }, + set: function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value: value, + configurable: true, + }); + } + }, +}; + +var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; +/*! + * Check to see if the MemoizeMap has recorded a result of the two operands + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @returns {Boolean|null} result +*/ +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === 'boolean') { + return result; + } + } + return null; +} + +/*! + * Set the result of the equality into the MemoizeMap + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @param {Boolean} result +*/ +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} + +/*! + * Primary Export + */ + +module.exports = deepEqual; +module.exports.MemoizeMap = MemoizeMap; + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + */ +function deepEqual(leftHandOperand, rightHandOperand, options) { + // If we have a comparator, we can't assume anything; so bail to its check first. + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + + // Deeper comparisons are pushed through to a larger function + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} + +/** + * Many comparisons can be canceled out early via simple equality or primitive checks. + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @return {Boolean|null} equal match + */ +function simpleEqual(leftHandOperand, rightHandOperand) { + // Equal references (except for Numbers) can be returned early + if (leftHandOperand === rightHandOperand) { + // Handle +-0 cases + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + + // handle NaN cases + if ( + leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare + ) { + return true; + } + + // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, + // strings, and undefined, can be compared by reference. + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + // Easy out b/c it would have passed the first equality check + return false; + } + return null; +} + +/*! + * The main logic of the `deepEqual` function. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match +*/ +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + + // Check if a memoized result exists. + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + + // If a comparator is present, use it. + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + // Comparators may return null, in which case we want to go back to default behavior. + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide + // what to do, we need to make sure to return the basic tests first before we move on. + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + // Don't memoize this, it takes longer to set/retrieve than to just compare. + return simpleResult; + } + } + + var leftHandType = type(leftHandOperand); + if (leftHandType !== type(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + + // Temporarily set the operands in the memoize object to prevent blowing the stack + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} + +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case 'String': + case 'Number': + case 'Boolean': + case 'Date': + // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case 'Promise': + case 'Symbol': + case 'function': + case 'WeakMap': + case 'WeakSet': + return leftHandOperand === rightHandOperand; + case 'Error': + return keysEqual(leftHandOperand, rightHandOperand, [ 'name', 'message', 'code' ], options); + case 'Arguments': + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'Array': + return iterableEqual(leftHandOperand, rightHandOperand, options); + case 'RegExp': + return regexpEqual(leftHandOperand, rightHandOperand); + case 'Generator': + return generatorEqual(leftHandOperand, rightHandOperand, options); + case 'DataView': + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case 'ArrayBuffer': + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case 'Set': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Map': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Temporal.PlainDate': + case 'Temporal.PlainTime': + case 'Temporal.PlainDateTime': + case 'Temporal.Instant': + case 'Temporal.ZonedDateTime': + case 'Temporal.PlainYearMonth': + case 'Temporal.PlainMonthDay': + return leftHandOperand.equals(rightHandOperand); + case 'Temporal.Duration': + return leftHandOperand.total('nanoseconds') === rightHandOperand.total('nanoseconds'); + case 'Temporal.TimeZone': + case 'Temporal.Calendar': + return leftHandOperand.toString() === rightHandOperand.toString(); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} + +/*! + * Compare two Regular Expressions for equality. + * + * @param {RegExp} leftHandOperand + * @param {RegExp} rightHandOperand + * @return {Boolean} result + */ + +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} + +/*! + * Compare two Sets/Maps for equality. Faster than other equality functions. + * + * @param {Set} leftHandOperand + * @param {Set} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function entriesEqual(leftHandOperand, rightHandOperand, options) { + // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(function gatherEntries(key, value) { + leftHandItems.push([ key, value ]); + }); + rightHandOperand.forEach(function gatherEntries(key, value) { + rightHandItems.push([ key, value ]); + }); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} + +/*! + * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} + +/*! + * Simple equality for generator objects such as those returned by generator functions. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} + +/*! + * Determine if the given object has an @@iterator function. + * + * @param {Object} target + * @return {Boolean} `true` if the object has an @@iterator function. + */ +function hasIteratorFunction(target) { + return typeof Symbol !== 'undefined' && + typeof target === 'object' && + typeof Symbol.iterator !== 'undefined' && + typeof target[Symbol.iterator] === 'function'; +} + +/*! + * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. + * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * + * @param {Object} target + * @returns {Array} an array of entries from the @@iterator function + */ +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} + +/*! + * Gets all entries from a Generator. This will consume the generator - which could have side effects. + * + * @param {Generator} target + * @returns {Array} an array of entries from the Generator. + */ +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [ generatorResult.value ]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} + +/*! + * Gets all own and inherited enumerable keys from a target. + * + * @param {Object} target + * @returns {Array} an array of own and inherited enumerable keys from the target. + */ +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} + +function getEnumerableSymbols(target) { + var keys = []; + var allKeys = Object.getOwnPropertySymbols(target); + for (var i = 0; i < allKeys.length; i += 1) { + var key = allKeys[i]; + if (Object.getOwnPropertyDescriptor(target, key).enumerable) { + keys.push(key); + } + } + return keys; +} + +/*! + * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of + * each key. If any value of the given key is not equal, the function will return false (early). + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} + +/*! + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + var leftHandSymbols = getEnumerableSymbols(leftHandOperand); + var rightHandSymbols = getEnumerableSymbols(rightHandOperand); + leftHandKeys = leftHandKeys.concat(leftHandSymbols); + rightHandKeys = rightHandKeys.concat(rightHandSymbols); + + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + if (iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + + if (leftHandKeys.length === 0 && + leftHandEntries.length === 0 && + rightHandKeys.length === 0 && + rightHandEntries.length === 0) { + return true; + } + + return false; +} + +/*! + * Returns true if the argument is a primitive. + * + * This intentionally returns true for all objects that can be compared by reference, + * including functions and symbols. + * + * @param {Mixed} value + * @return {Boolean} result + */ +function isPrimitive(value) { + return value === null || typeof value !== 'object'; +} + +function mapSymbols(arr) { + return arr.map(function mapSymbol(entry) { + if (typeof entry === 'symbol') { + return entry.toString(); + } + + return entry; + }); +} diff --git a/web/node_modules/deep-eql/package.json b/web/node_modules/deep-eql/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dc1b9aaaf6911df5fbf71554afcfa3a1a50b3606 --- /dev/null +++ b/web/node_modules/deep-eql/package.json @@ -0,0 +1,79 @@ +{ + "name": "deep-eql", + "version": "4.1.3", + "description": "Improved deep equality testing for Node.js and the browser.", + "keywords": [ + "chai util", + "deep equal", + "object equal", + "testing" + ], + "repository": { + "type": "git", + "url": "git@github.com:chaijs/deep-eql.git" + }, + "license": "MIT", + "author": "Jake Luer ", + "contributors": [ + "Keith Cirkel (https://github.com/keithamus)", + "dougluce (https://github.com/dougluce)", + "Lorenz Leutgeb (https://github.com/flowlo)" + ], + "main": "./index", + "files": [ + "index.js", + "deep-eql.js" + ], + "scripts": { + "bench": "node bench", + "build": "browserify $npm_package_main --standalone deepEqual -o deep-eql.js", + "lint": "eslint --ignore-path .gitignore .", + "prepublish": "npm run build", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser", + "test:browser": "karma start --singleRun=true", + "test:node": "istanbul cover _mocha", + "upload-coverage": "lcov-result-merger 'coverage/**/lcov.info' | coveralls; exit 0", + "watch": "karma start --auto-watch --singleRun=false" + }, + "eslintConfig": { + "extends": [ + "strict/es5" + ], + "rules": { + "complexity": 0, + "no-underscore-dangle": 0, + "no-use-before-define": 0, + "spaced-comment": 0 + } + }, + "dependencies": { + "type-detect": "^4.0.0" + }, + "devDependencies": { + "@js-temporal/polyfill": "^0.4.1", + "benchmark": "^2.1.0", + "browserify": "^17.0.0", + "browserify-istanbul": "^3.0.1", + "coveralls": "^3.1.1", + "eslint": "^7.32.0", + "eslint-config-strict": "^14.0.1", + "eslint-plugin-filenames": "^1.3.2", + "istanbul": "^0.4.2", + "karma": "^6.3.4", + "karma-browserify": "^8.1.0", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage": "^2.0.3", + "karma-mocha": "^2.0.1", + "karma-sauce-launcher": "^4.1.4", + "kewlr": "^0.4.1", + "lcov-result-merger": "^1.0.2", + "lodash.isequal": "^4.4.0", + "mocha": "^9.1.1", + "simple-assert": "^1.0.0" + }, + "engines": { + "node": ">=6" + } +} diff --git a/web/node_modules/diff-sequences/LICENSE b/web/node_modules/diff-sequences/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b93be90515ccd0b9daedaa589e42bf5929693f1f --- /dev/null +++ b/web/node_modules/diff-sequences/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +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/web/node_modules/diff-sequences/README.md b/web/node_modules/diff-sequences/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fd5b99bea05a9f98260d39b23af0b1c290e23537 --- /dev/null +++ b/web/node_modules/diff-sequences/README.md @@ -0,0 +1,404 @@ +# diff-sequences + +Compare items in two sequences to find a **longest common subsequence**. + +The items not in common are the items to delete or insert in a **shortest edit script**. + +To maximize flexibility and minimize memory, you write **callback** functions as configuration: + +**Input** function `isCommon(aIndex, bIndex)` compares items at indexes in the sequences and returns a truthy/falsey value. This package might call your function more than once for some pairs of indexes. + +- Because your function encapsulates **comparison**, this package can compare items according to `===` operator, `Object.is` method, or other criterion. +- Because your function encapsulates **sequences**, this package can find differences in arrays, strings, or other data. + +**Output** function `foundSubsequence(nCommon, aCommon, bCommon)` receives the number of adjacent items and starting indexes of each common subsequence. If sequences do not have common items, then this package does not call your function. + +If N is the sum of lengths of sequences and L is length of a longest common subsequence, then D = N – 2L is the number of **differences** in the corresponding shortest edit script. + +[_An O(ND) Difference Algorithm and Its Variations_](http://xmailserver.org/diff2.pdf) by Eugene W. Myers is fast when sequences have **few** differences. + +This package implements the **linear space** variation with optimizations so it is fast even when sequences have **many** differences. + +## Usage + +To add this package as a dependency of a project, do either of the following: + +- `npm install diff-sequences` +- `yarn add diff-sequences` + +To use `diff` as the name of the default export from this package, do either of the following: + +- `var diff = require('diff-sequences').default; // CommonJS modules` +- `import diff from 'diff-sequences'; // ECMAScript modules` + +Call `diff` with the **lengths** of sequences and your **callback** functions: + +```js +const a = ['a', 'b', 'c', 'a', 'b', 'b', 'a']; +const b = ['c', 'b', 'a', 'b', 'a', 'c']; + +function isCommon(aIndex, bIndex) { + return a[aIndex] === b[bIndex]; +} +function foundSubsequence(nCommon, aCommon, bCommon) { + // see examples +} + +diff(a.length, b.length, isCommon, foundSubsequence); +``` + +## Example of longest common subsequence + +Some sequences (for example, `a` and `b` in the example of usage) have more than one longest common subsequence. + +This package finds the following common items: + +| comparisons of common items | values | output arguments | +| :------------------------------- | :--------- | --------------------------: | +| `a[2] === b[0]` | `'c'` | `foundSubsequence(1, 2, 0)` | +| `a[4] === b[1]` | `'b'` | `foundSubsequence(1, 4, 1)` | +| `a[5] === b[3] && a[6] === b[4]` | `'b', 'a'` | `foundSubsequence(2, 5, 3)` | + +The “edit graph” analogy in the Myers paper shows the following common items: + +| comparisons of common items | values | +| :------------------------------- | :--------- | +| `a[2] === b[0]` | `'c'` | +| `a[3] === b[2] && a[4] === b[3]` | `'a', 'b'` | +| `a[6] === b[4]` | `'a'` | + +Various packages which implement the Myers algorithm will **always agree** on the **length** of a longest common subsequence, but might **sometimes disagree** on which **items** are in it. + +## Example of callback functions to count common items + +```js +// Return length of longest common subsequence according to === operator. +function countCommonItems(a, b) { + let n = 0; + function isCommon(aIndex, bIndex) { + return a[aIndex] === b[bIndex]; + } + function foundSubsequence(nCommon) { + n += nCommon; + } + + diff(a.length, b.length, isCommon, foundSubsequence); + + return n; +} + +const commonLength = countCommonItems( + ['a', 'b', 'c', 'a', 'b', 'b', 'a'], + ['c', 'b', 'a', 'b', 'a', 'c'], +); +``` + +| category of items | expression | value | +| :----------------- | ------------------------: | ----: | +| in common | `commonLength` | `4` | +| to delete from `a` | `a.length - commonLength` | `3` | +| to insert from `b` | `b.length - commonLength` | `2` | + +If the length difference `b.length - a.length` is: + +- negative: its absolute value is the minimum number of items to **delete** from `a` +- positive: it is the minimum number of items to **insert** from `b` +- zero: there is an **equal** number of items to delete from `a` and insert from `b` +- non-zero: there is an equal number of **additional** items to delete from `a` and insert from `b` + +In this example, `6 - 7` is: + +- negative: `1` is the minimum number of items to **delete** from `a` +- non-zero: `2` is the number of **additional** items to delete from `a` and insert from `b` + +## Example of callback functions to find common items + +```js +// Return array of items in longest common subsequence according to Object.is method. +const findCommonItems = (a, b) => { + const array = []; + diff( + a.length, + b.length, + (aIndex, bIndex) => Object.is(a[aIndex], b[bIndex]), + (nCommon, aCommon) => { + for (; nCommon !== 0; nCommon -= 1, aCommon += 1) { + array.push(a[aCommon]); + } + }, + ); + return array; +}; + +const commonItems = findCommonItems( + ['a', 'b', 'c', 'a', 'b', 'b', 'a'], + ['c', 'b', 'a', 'b', 'a', 'c'], +); +``` + +| `i` | `commonItems[i]` | `aIndex` | +| --: | :--------------- | -------: | +| `0` | `'c'` | `2` | +| `1` | `'b'` | `4` | +| `2` | `'b'` | `5` | +| `3` | `'a'` | `6` | + +## Example of callback functions to diff index intervals + +Instead of slicing array-like objects, you can adjust indexes in your callback functions. + +```js +// Diff index intervals that are half open [start, end) like array slice method. +const diffIndexIntervals = (a, aStart, aEnd, b, bStart, bEnd) => { + // Validate: 0 <= aStart and aStart <= aEnd and aEnd <= a.length + // Validate: 0 <= bStart and bStart <= bEnd and bEnd <= b.length + + diff( + aEnd - aStart, + bEnd - bStart, + (aIndex, bIndex) => Object.is(a[aStart + aIndex], b[bStart + bIndex]), + (nCommon, aCommon, bCommon) => { + // aStart + aCommon, bStart + bCommon + }, + ); + + // After the last common subsequence, do any remaining work. +}; +``` + +## Example of callback functions to emulate diff command + +Linux or Unix has a `diff` command to compare files line by line. Its output is a **shortest edit script**: + +- **c**hange adjacent lines from the first file to lines from the second file +- **d**elete lines from the first file +- **a**ppend or insert lines from the second file + +```js +// Given zero-based half-open range [start, end) of array indexes, +// return one-based closed range [start + 1, end] as string. +const getRange = (start, end) => + start + 1 === end ? `${start + 1}` : `${start + 1},${end}`; + +// Given index intervals of lines to delete or insert, or both, or neither, +// push formatted diff lines onto array. +const pushDelIns = (aLines, aIndex, aEnd, bLines, bIndex, bEnd, array) => { + const deleteLines = aIndex !== aEnd; + const insertLines = bIndex !== bEnd; + const changeLines = deleteLines && insertLines; + if (changeLines) { + array.push(`${getRange(aIndex, aEnd)}c${getRange(bIndex, bEnd)}`); + } else if (deleteLines) { + array.push(`${getRange(aIndex, aEnd)}d${String(bIndex)}`); + } else if (insertLines) { + array.push(`${String(aIndex)}a${getRange(bIndex, bEnd)}`); + } else { + return; + } + + for (; aIndex !== aEnd; aIndex += 1) { + array.push(`< ${aLines[aIndex]}`); // delete is less than + } + + if (changeLines) { + array.push('---'); + } + + for (; bIndex !== bEnd; bIndex += 1) { + array.push(`> ${bLines[bIndex]}`); // insert is greater than + } +}; + +// Given content of two files, return emulated output of diff utility. +const findShortestEditScript = (a, b) => { + const aLines = a.split('\n'); + const bLines = b.split('\n'); + const aLength = aLines.length; + const bLength = bLines.length; + + const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; + + let aIndex = 0; + let bIndex = 0; + const array = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + pushDelIns(aLines, aIndex, aCommon, bLines, bIndex, bCommon, array); + aIndex = aCommon + nCommon; // number of lines compared in a + bIndex = bCommon + nCommon; // number of lines compared in b + }; + + diff(aLength, bLength, isCommon, foundSubsequence); + + // After the last common subsequence, push remaining change lines. + pushDelIns(aLines, aIndex, aLength, bLines, bIndex, bLength, array); + + return array.length === 0 ? '' : `${array.join('\n')}\n`; +}; +``` + +## Example of callback functions to format diff lines + +Here is simplified code to format **changed and unchanged lines** in expected and received values after a test fails in Jest: + +```js +// Format diff with minus or plus for change lines and space for common lines. +const formatDiffLines = (a, b) => { + // Jest depends on pretty-format package to serialize objects as strings. + // Unindented for comparison to avoid distracting differences: + const aLinesUn = format(a, {indent: 0 /*, other options*/}).split('\n'); + const bLinesUn = format(b, {indent: 0 /*, other options*/}).split('\n'); + // Indented to display changed and unchanged lines: + const aLinesIn = format(a, {indent: 2 /*, other options*/}).split('\n'); + const bLinesIn = format(b, {indent: 2 /*, other options*/}).split('\n'); + + const aLength = aLinesIn.length; // Validate: aLinesUn.length === aLength + const bLength = bLinesIn.length; // Validate: bLinesUn.length === bLength + + const isCommon = (aIndex, bIndex) => aLinesUn[aIndex] === bLinesUn[bIndex]; + + // Only because the GitHub Flavored Markdown doc collapses adjacent spaces, + // this example code and the following table represent spaces as middle dots. + let aIndex = 0; + let bIndex = 0; + const array = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + for (; aIndex !== aCommon; aIndex += 1) { + array.push(`-·${aLinesIn[aIndex]}`); // delete is minus + } + for (; bIndex !== bCommon; bIndex += 1) { + array.push(`+·${bLinesIn[bIndex]}`); // insert is plus + } + for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { + // For common lines, received indentation seems more intuitive. + array.push(`··${bLinesIn[bIndex]}`); // common is space + } + }; + + diff(aLength, bLength, isCommon, foundSubsequence); + + // After the last common subsequence, push remaining change lines. + for (; aIndex !== aLength; aIndex += 1) { + array.push(`-·${aLinesIn[aIndex]}`); + } + for (; bIndex !== bLength; bIndex += 1) { + array.push(`+·${bLinesIn[bIndex]}`); + } + + return array; +}; + +const expected = { + searching: '', + sorting: { + ascending: true, + fieldKey: 'what', + }, +}; +const received = { + searching: '', + sorting: [ + { + descending: false, + fieldKey: 'what', + }, + ], +}; + +const diffLines = formatDiffLines(expected, received); +``` + +If N is the sum of lengths of sequences and L is length of a longest common subsequence, then N – L is length of an array of diff lines. In this example, N is 7 + 9, L is 5, and N – L is 11. + +| `i` | `diffLines[i]` | `aIndex` | `bIndex` | +| ---: | :--------------------------------- | -------: | -------: | +| `0` | `'··Object {'` | `0` | `0` | +| `1` | `'····"searching": "",'` | `1` | `1` | +| `2` | `'-···"sorting": Object {'` | `2` | | +| `3` | `'-·····"ascending": true,'` | `3` | | +| `4` | `'+·····"sorting": Array ['` | | `2` | +| `5` | `'+·······Object {'` | | `3` | +| `6` | `'+·········"descending": false,'` | | `4` | +| `7` | `'··········"fieldKey": "what",'` | `4` | `5` | +| `8` | `'········},'` | `5` | `6` | +| `9` | `'+·····],'` | | `7` | +| `10` | `'··}'` | `6` | `8` | + +## Example of callback functions to find diff items + +Here is simplified code to find changed and unchanged substrings **within adjacent changed lines** in expected and received values after a test fails in Jest: + +```js +// Return diff items for strings (compatible with diff-match-patch package). +const findDiffItems = (a, b) => { + const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; + + let aIndex = 0; + let bIndex = 0; + const array = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + if (aIndex !== aCommon) { + array.push([-1, a.slice(aIndex, aCommon)]); // delete is -1 + } + if (bIndex !== bCommon) { + array.push([1, b.slice(bIndex, bCommon)]); // insert is 1 + } + + aIndex = aCommon + nCommon; // number of characters compared in a + bIndex = bCommon + nCommon; // number of characters compared in b + array.push([0, a.slice(aCommon, aIndex)]); // common is 0 + }; + + diff(a.length, b.length, isCommon, foundSubsequence); + + // After the last common subsequence, push remaining change items. + if (aIndex !== a.length) { + array.push([-1, a.slice(aIndex)]); + } + if (bIndex !== b.length) { + array.push([1, b.slice(bIndex)]); + } + + return array; +}; + +const expectedDeleted = ['"sorting": Object {', '"ascending": true,'].join( + '\n', +); +const receivedInserted = [ + '"sorting": Array [', + 'Object {', + '"descending": false,', +].join('\n'); + +const diffItems = findDiffItems(expectedDeleted, receivedInserted); +``` + +| `i` | `diffItems[i][0]` | `diffItems[i][1]` | +| --: | ----------------: | :---------------- | +| `0` | `0` | `'"sorting": '` | +| `1` | `1` | `'Array [\n'` | +| `2` | `0` | `'Object {\n"'` | +| `3` | `-1` | `'a'` | +| `4` | `1` | `'de'` | +| `5` | `0` | `'scending": '` | +| `6` | `-1` | `'tru'` | +| `7` | `1` | `'fals'` | +| `8` | `0` | `'e,'` | + +The length difference `b.length - a.length` is equal to the sum of `diffItems[i][0]` values times `diffItems[i][1]` lengths. In this example, the difference `48 - 38` is equal to the sum `10`. + +| category of diff item | `[0]` | `[1]` lengths | subtotal | +| :-------------------- | ----: | -----------------: | -------: | +| in common | `0` | `11 + 10 + 11 + 2` | `0` | +| to delete from `a` | `–1` | `1 + 3` | `-4` | +| to insert from `b` | `1` | `8 + 2 + 4` | `14` | + +Instead of formatting the changed substrings with escape codes for colors in the `foundSubsequence` function to save memory, this example spends memory to **gain flexibility** before formatting, so a separate heuristic algorithm might modify the generic array of diff items to show changes more clearly: + +| `i` | `diffItems[i][0]` | `diffItems[i][1]` | +| --: | ----------------: | :---------------- | +| `6` | `-1` | `'true'` | +| `7` | `1` | `'false'` | +| `8` | `0` | `','` | + +For expected and received strings of serialized data, the result of finding changed **lines**, and then finding changed **substrings** within adjacent changed lines (as in the preceding two examples) sometimes displays the changes in a more intuitive way than the result of finding changed substrings, and then splitting them into changed and unchanged lines. diff --git a/web/node_modules/diff-sequences/build/index.d.ts b/web/node_modules/diff-sequences/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e9c3db85e80f83d977ccded067376acef3aa7b3 --- /dev/null +++ b/web/node_modules/diff-sequences/build/index.d.ts @@ -0,0 +1,38 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type Callbacks = { + foundSubsequence: FoundSubsequence; + isCommon: IsCommon; +}; + +declare function diffSequence( + aLength: number, + bLength: number, + isCommon: IsCommon, + foundSubsequence: FoundSubsequence, +): void; +export default diffSequence; + +declare type FoundSubsequence = ( + nCommon: number, // caller can assume: 0 < nCommon + aCommon: number, // caller can assume: 0 <= aCommon && aCommon < aLength + bCommon: number, +) => void; + +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +declare type IsCommon = ( + aIndex: number, // caller can assume: 0 <= aIndex && aIndex < aLength + bIndex: number, +) => boolean; + +export {}; diff --git a/web/node_modules/diff-sequences/build/index.js b/web/node_modules/diff-sequences/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b0a1ff6c78d03244e83ff3452121bf164eec0c85 --- /dev/null +++ b/web/node_modules/diff-sequences/build/index.js @@ -0,0 +1,798 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = diffSequence; +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +// This diff-sequences package implements the linear space variation in +// An O(ND) Difference Algorithm and Its Variations by Eugene W. Myers + +// Relationship in notation between Myers paper and this package: +// A is a +// N is aLength, aEnd - aStart, and so on +// x is aIndex, aFirst, aLast, and so on +// B is b +// M is bLength, bEnd - bStart, and so on +// y is bIndex, bFirst, bLast, and so on +// Δ = N - M is negative of baDeltaLength = bLength - aLength +// D is d +// k is kF +// k + Δ is kF = kR - baDeltaLength +// V is aIndexesF or aIndexesR (see comment below about Indexes type) +// index intervals [1, N] and [1, M] are [0, aLength) and [0, bLength) +// starting point in forward direction (0, 0) is (-1, -1) +// starting point in reverse direction (N + 1, M + 1) is (aLength, bLength) + +// The “edit graph” for sequences a and b corresponds to items: +// in a on the horizontal axis +// in b on the vertical axis +// +// Given a-coordinate of a point in a diagonal, you can compute b-coordinate. +// +// Forward diagonals kF: +// zero diagonal intersects top left corner +// positive diagonals intersect top edge +// negative diagonals insersect left edge +// +// Reverse diagonals kR: +// zero diagonal intersects bottom right corner +// positive diagonals intersect right edge +// negative diagonals intersect bottom edge + +// The graph contains a directed acyclic graph of edges: +// horizontal: delete an item from a +// vertical: insert an item from b +// diagonal: common item in a and b +// +// The algorithm solves dual problems in the graph analogy: +// Find longest common subsequence: path with maximum number of diagonal edges +// Find shortest edit script: path with minimum number of non-diagonal edges + +// Input callback function compares items at indexes in the sequences. + +// Output callback function receives the number of adjacent items +// and starting indexes of each common subsequence. +// Either original functions or wrapped to swap indexes if graph is transposed. +// Indexes in sequence a of last point of forward or reverse paths in graph. +// Myers algorithm indexes by diagonal k which for negative is bad deopt in V8. +// This package indexes by iF and iR which are greater than or equal to zero. +// and also updates the index arrays in place to cut memory in half. +// kF = 2 * iF - d +// kR = d - 2 * iR +// Division of index intervals in sequences a and b at the middle change. +// Invariant: intervals do not have common items at the start or end. +const pkg = 'diff-sequences'; // for error messages +const NOT_YET_SET = 0; // small int instead of undefined to avoid deopt in V8 + +// Return the number of common items that follow in forward direction. +// The length of what Myers paper calls a “snake” in a forward path. +const countCommonItemsF = (aIndex, aEnd, bIndex, bEnd, isCommon) => { + let nCommon = 0; + while (aIndex < aEnd && bIndex < bEnd && isCommon(aIndex, bIndex)) { + aIndex += 1; + bIndex += 1; + nCommon += 1; + } + return nCommon; +}; + +// Return the number of common items that precede in reverse direction. +// The length of what Myers paper calls a “snake” in a reverse path. +const countCommonItemsR = (aStart, aIndex, bStart, bIndex, isCommon) => { + let nCommon = 0; + while (aStart <= aIndex && bStart <= bIndex && isCommon(aIndex, bIndex)) { + aIndex -= 1; + bIndex -= 1; + nCommon += 1; + } + return nCommon; +}; + +// A simple function to extend forward paths from (d - 1) to d changes +// when forward and reverse paths cannot yet overlap. +const extendPathsF = ( + d, + aEnd, + bEnd, + bF, + isCommon, + aIndexesF, + iMaxF // return the value because optimization might decrease it +) => { + // Unroll the first iteration. + let iF = 0; + let kF = -d; // kF = 2 * iF - d + let aFirst = aIndexesF[iF]; // in first iteration always insert + let aIndexPrev1 = aFirst; // prev value of [iF - 1] in next iteration + aIndexesF[iF] += countCommonItemsF( + aFirst + 1, + aEnd, + bF + aFirst - kF + 1, + bEnd, + isCommon + ); + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nF = d < iMaxF ? d : iMaxF; + + // The diagonals kF are odd when d is odd and even when d is even. + for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { + // To get first point of path segment, move one change in forward direction + // from last point of previous path segment in an adjacent diagonal. + // In last possible iteration when iF === d and kF === d always delete. + if (iF !== d && aIndexPrev1 < aIndexesF[iF]) { + aFirst = aIndexesF[iF]; // vertical to insert from b + } else { + aFirst = aIndexPrev1 + 1; // horizontal to delete from a + + if (aEnd <= aFirst) { + // Optimization: delete moved past right of graph. + return iF - 1; + } + } + + // To get last point of path segment, move along diagonal of common items. + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = + aFirst + + countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); + } + return iMaxF; +}; + +// A simple function to extend reverse paths from (d - 1) to d changes +// when reverse and forward paths cannot yet overlap. +const extendPathsR = ( + d, + aStart, + bStart, + bR, + isCommon, + aIndexesR, + iMaxR // return the value because optimization might decrease it +) => { + // Unroll the first iteration. + let iR = 0; + let kR = d; // kR = d - 2 * iR + let aFirst = aIndexesR[iR]; // in first iteration always insert + let aIndexPrev1 = aFirst; // prev value of [iR - 1] in next iteration + aIndexesR[iR] -= countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bR + aFirst - kR - 1, + isCommon + ); + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nR = d < iMaxR ? d : iMaxR; + + // The diagonals kR are odd when d is odd and even when d is even. + for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { + // To get first point of path segment, move one change in reverse direction + // from last point of previous path segment in an adjacent diagonal. + // In last possible iteration when iR === d and kR === -d always delete. + if (iR !== d && aIndexesR[iR] < aIndexPrev1) { + aFirst = aIndexesR[iR]; // vertical to insert from b + } else { + aFirst = aIndexPrev1 - 1; // horizontal to delete from a + + if (aFirst < aStart) { + // Optimization: delete moved past left of graph. + return iR - 1; + } + } + + // To get last point of path segment, move along diagonal of common items. + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = + aFirst - + countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bR + aFirst - kR - 1, + isCommon + ); + } + return iMaxR; +}; + +// A complete function to extend forward paths from (d - 1) to d changes. +// Return true if a path overlaps reverse path of (d - 1) changes in its diagonal. +const extendOverlappablePathsF = ( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division // update prop values if return true +) => { + const bF = bStart - aStart; // bIndex = bF + aIndex - kF + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + const baDeltaLength = bLength - aLength; // kF = kR - baDeltaLength + + // Range of diagonals in which forward and reverse paths might overlap. + const kMinOverlapF = -baDeltaLength - (d - 1); // -(d - 1) <= kR + const kMaxOverlapF = -baDeltaLength + (d - 1); // kR <= (d - 1) + + let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nF = d < iMaxF ? d : iMaxF; + + // The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even. + for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { + // To get first point of path segment, move one change in forward direction + // from last point of previous path segment in an adjacent diagonal. + // In first iteration when iF === 0 and kF === -d always insert. + // In last possible iteration when iF === d and kF === d always delete. + const insert = iF === 0 || (iF !== d && aIndexPrev1 < aIndexesF[iF]); + const aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1; + const aFirst = insert + ? aLastPrev // vertical to insert from b + : aLastPrev + 1; // horizontal to delete from a + + // To get last point of path segment, move along diagonal of common items. + const bFirst = bF + aFirst - kF; + const nCommonF = countCommonItemsF( + aFirst + 1, + aEnd, + bFirst + 1, + bEnd, + isCommon + ); + const aLast = aFirst + nCommonF; + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = aLast; + if (kMinOverlapF <= kF && kF <= kMaxOverlapF) { + // Solve for iR of reverse path with (d - 1) changes in diagonal kF: + // kR = kF + baDeltaLength + // kR = (d - 1) - 2 * iR + const iR = (d - 1 - (kF + baDeltaLength)) / 2; + + // If this forward path overlaps the reverse path in this diagonal, + // then this is the middle change of the index intervals. + if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) { + // Unlike the Myers algorithm which finds only the middle “snake” + // this package can find two common subsequences per division. + // Last point of previous path segment is on an adjacent diagonal. + const bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1); + + // Because of invariant that intervals preceding the middle change + // cannot have common items at the end, + // move in reverse direction along a diagonal of common items. + const nCommonR = countCommonItemsR( + aStart, + aLastPrev, + bStart, + bLastPrev, + isCommon + ); + const aIndexPrevFirst = aLastPrev - nCommonR; + const bIndexPrevFirst = bLastPrev - nCommonR; + const aEndPreceding = aIndexPrevFirst + 1; + const bEndPreceding = bIndexPrevFirst + 1; + division.nChangePreceding = d - 1; + if (d - 1 === aEndPreceding + bEndPreceding - aStart - bStart) { + // Optimization: number of preceding changes in forward direction + // is equal to number of items in preceding interval, + // therefore it cannot contain any common items. + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aEndPreceding; + division.bEndPreceding = bEndPreceding; + } + division.nCommonPreceding = nCommonR; + if (nCommonR !== 0) { + division.aCommonPreceding = aEndPreceding; + division.bCommonPreceding = bEndPreceding; + } + division.nCommonFollowing = nCommonF; + if (nCommonF !== 0) { + division.aCommonFollowing = aFirst + 1; + division.bCommonFollowing = bFirst + 1; + } + const aStartFollowing = aLast + 1; + const bStartFollowing = bFirst + nCommonF + 1; + division.nChangeFollowing = d - 1; + if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { + // Optimization: number of changes in reverse direction + // is equal to number of items in following interval, + // therefore it cannot contain any common items. + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + return true; + } + } + } + return false; +}; + +// A complete function to extend reverse paths from (d - 1) to d changes. +// Return true if a path overlaps forward path of d changes in its diagonal. +const extendOverlappablePathsR = ( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division // update prop values if return true +) => { + const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + const baDeltaLength = bLength - aLength; // kR = kF + baDeltaLength + + // Range of diagonals in which forward and reverse paths might overlap. + const kMinOverlapR = baDeltaLength - d; // -d <= kF + const kMaxOverlapR = baDeltaLength + d; // kF <= d + + let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nR = d < iMaxR ? d : iMaxR; + + // The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even. + for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { + // To get first point of path segment, move one change in reverse direction + // from last point of previous path segment in an adjacent diagonal. + // In first iteration when iR === 0 and kR === d always insert. + // In last possible iteration when iR === d and kR === -d always delete. + const insert = iR === 0 || (iR !== d && aIndexesR[iR] < aIndexPrev1); + const aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1; + const aFirst = insert + ? aLastPrev // vertical to insert from b + : aLastPrev - 1; // horizontal to delete from a + + // To get last point of path segment, move along diagonal of common items. + const bFirst = bR + aFirst - kR; + const nCommonR = countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bFirst - 1, + isCommon + ); + const aLast = aFirst - nCommonR; + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = aLast; + if (kMinOverlapR <= kR && kR <= kMaxOverlapR) { + // Solve for iF of forward path with d changes in diagonal kR: + // kF = kR - baDeltaLength + // kF = 2 * iF - d + const iF = (d + (kR - baDeltaLength)) / 2; + + // If this reverse path overlaps the forward path in this diagonal, + // then this is a middle change of the index intervals. + if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) { + const bLast = bFirst - nCommonR; + division.nChangePreceding = d; + if (d === aLast + bLast - aStart - bStart) { + // Optimization: number of changes in reverse direction + // is equal to number of items in preceding interval, + // therefore it cannot contain any common items. + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aLast; + division.bEndPreceding = bLast; + } + division.nCommonPreceding = nCommonR; + if (nCommonR !== 0) { + // The last point of reverse path segment is start of common subsequence. + division.aCommonPreceding = aLast; + division.bCommonPreceding = bLast; + } + division.nChangeFollowing = d - 1; + if (d === 1) { + // There is no previous path segment. + division.nCommonFollowing = 0; + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + // Unlike the Myers algorithm which finds only the middle “snake” + // this package can find two common subsequences per division. + // Last point of previous path segment is on an adjacent diagonal. + const bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1); + + // Because of invariant that intervals following the middle change + // cannot have common items at the start, + // move in forward direction along a diagonal of common items. + const nCommonF = countCommonItemsF( + aLastPrev, + aEnd, + bLastPrev, + bEnd, + isCommon + ); + division.nCommonFollowing = nCommonF; + if (nCommonF !== 0) { + // The last point of reverse path segment is start of common subsequence. + division.aCommonFollowing = aLastPrev; + division.bCommonFollowing = bLastPrev; + } + const aStartFollowing = aLastPrev + nCommonF; // aFirstPrev + const bStartFollowing = bLastPrev + nCommonF; // bFirstPrev + + if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { + // Optimization: number of changes in forward direction + // is equal to number of items in following interval, + // therefore it cannot contain any common items. + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + } + return true; + } + } + } + return false; +}; + +// Given index intervals and input function to compare items at indexes, +// divide at the middle change. +// +// DO NOT CALL if start === end, because interval cannot contain common items +// and because this function will throw the “no overlap” error. +const divide = ( + nChange, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + aIndexesR, + division // output +) => { + const bF = bStart - aStart; // bIndex = bF + aIndex - kF + const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + + // Because graph has square or portrait orientation, + // length difference is minimum number of items to insert from b. + // Corresponding forward and reverse diagonals in graph + // depend on length difference of the sequences: + // kF = kR - baDeltaLength + // kR = kF + baDeltaLength + const baDeltaLength = bLength - aLength; + + // Optimization: max diagonal in graph intersects corner of shorter side. + let iMaxF = aLength; + let iMaxR = aLength; + + // Initialize no changes yet in forward or reverse direction: + aIndexesF[0] = aStart - 1; // at open start of interval, outside closed start + aIndexesR[0] = aEnd; // at open end of interval + + if (baDeltaLength % 2 === 0) { + // The number of changes in paths is 2 * d if length difference is even. + const dMin = (nChange || baDeltaLength) / 2; + const dMax = (aLength + bLength) / 2; + for (let d = 1; d <= dMax; d += 1) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + if (d < dMin) { + iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); + } else if ( + // If a reverse path overlaps a forward path in the same diagonal, + // return a division of the index intervals at the middle change. + extendOverlappablePathsR( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division + ) + ) { + return; + } + } + } else { + // The number of changes in paths is 2 * d - 1 if length difference is odd. + const dMin = ((nChange || baDeltaLength) + 1) / 2; + const dMax = (aLength + bLength + 1) / 2; + + // Unroll first half iteration so loop extends the relevant pairs of paths. + // Because of invariant that intervals have no common items at start or end, + // and limitation not to call divide with empty intervals, + // therefore it cannot be called if a forward path with one change + // would overlap a reverse path with no changes, even if dMin === 1. + let d = 1; + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + for (d += 1; d <= dMax; d += 1) { + iMaxR = extendPathsR( + d - 1, + aStart, + bStart, + bR, + isCommon, + aIndexesR, + iMaxR + ); + if (d < dMin) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + } else if ( + // If a forward path overlaps a reverse path in the same diagonal, + // return a division of the index intervals at the middle change. + extendOverlappablePathsF( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division + ) + ) { + return; + } + } + } + + /* istanbul ignore next */ + throw new Error( + `${pkg}: no overlap aStart=${aStart} aEnd=${aEnd} bStart=${bStart} bEnd=${bEnd}` + ); +}; + +// Given index intervals and input function to compare items at indexes, +// return by output function the number of adjacent items and starting indexes +// of each common subsequence. Divide and conquer with only linear space. +// +// The index intervals are half open [start, end) like array slice method. +// DO NOT CALL if start === end, because interval cannot contain common items +// and because divide function will throw the “no overlap” error. +const findSubsequences = ( + nChange, + aStart, + aEnd, + bStart, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division // temporary memory, not input nor output +) => { + if (bEnd - bStart < aEnd - aStart) { + // Transpose graph so it has portrait instead of landscape orientation. + // Always compare shorter to longer sequence for consistency and optimization. + transposed = !transposed; + if (transposed && callbacks.length === 1) { + // Lazily wrap callback functions to swap args if graph is transposed. + const {foundSubsequence, isCommon} = callbacks[0]; + callbacks[1] = { + foundSubsequence: (nCommon, bCommon, aCommon) => { + foundSubsequence(nCommon, aCommon, bCommon); + }, + isCommon: (bIndex, aIndex) => isCommon(aIndex, bIndex) + }; + } + const tStart = aStart; + const tEnd = aEnd; + aStart = bStart; + aEnd = bEnd; + bStart = tStart; + bEnd = tEnd; + } + const {foundSubsequence, isCommon} = callbacks[transposed ? 1 : 0]; + + // Divide the index intervals at the middle change. + divide( + nChange, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + aIndexesR, + division + ); + const { + nChangePreceding, + aEndPreceding, + bEndPreceding, + nCommonPreceding, + aCommonPreceding, + bCommonPreceding, + nCommonFollowing, + aCommonFollowing, + bCommonFollowing, + nChangeFollowing, + aStartFollowing, + bStartFollowing + } = division; + + // Unless either index interval is empty, they might contain common items. + if (aStart < aEndPreceding && bStart < bEndPreceding) { + // Recursely find and return common subsequences preceding the division. + findSubsequences( + nChangePreceding, + aStart, + aEndPreceding, + bStart, + bEndPreceding, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + + // Return common subsequences that are adjacent to the middle change. + if (nCommonPreceding !== 0) { + foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding); + } + if (nCommonFollowing !== 0) { + foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing); + } + + // Unless either index interval is empty, they might contain common items. + if (aStartFollowing < aEnd && bStartFollowing < bEnd) { + // Recursely find and return common subsequences following the division. + findSubsequences( + nChangeFollowing, + aStartFollowing, + aEnd, + bStartFollowing, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } +}; +const validateLength = (name, arg) => { + if (typeof arg !== 'number') { + throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`); + } + if (!Number.isSafeInteger(arg)) { + throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`); + } + if (arg < 0) { + throw new RangeError(`${pkg}: ${name} value ${arg} is a negative integer`); + } +}; +const validateCallback = (name, arg) => { + const type = typeof arg; + if (type !== 'function') { + throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`); + } +}; + +// Compare items in two sequences to find a longest common subsequence. +// Given lengths of sequences and input function to compare items at indexes, +// return by output function the number of adjacent items and starting indexes +// of each common subsequence. +function diffSequence(aLength, bLength, isCommon, foundSubsequence) { + validateLength('aLength', aLength); + validateLength('bLength', bLength); + validateCallback('isCommon', isCommon); + validateCallback('foundSubsequence', foundSubsequence); + + // Count common items from the start in the forward direction. + const nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon); + if (nCommonF !== 0) { + foundSubsequence(nCommonF, 0, 0); + } + + // Unless both sequences consist of common items only, + // find common items in the half-trimmed index intervals. + if (aLength !== nCommonF || bLength !== nCommonF) { + // Invariant: intervals do not have common items at the start. + // The start of an index interval is closed like array slice method. + const aStart = nCommonF; + const bStart = nCommonF; + + // Count common items from the end in the reverse direction. + const nCommonR = countCommonItemsR( + aStart, + aLength - 1, + bStart, + bLength - 1, + isCommon + ); + + // Invariant: intervals do not have common items at the end. + // The end of an index interval is open like array slice method. + const aEnd = aLength - nCommonR; + const bEnd = bLength - nCommonR; + + // Unless one sequence consists of common items only, + // therefore the other trimmed index interval consists of changes only, + // find common items in the trimmed index intervals. + const nCommonFR = nCommonF + nCommonR; + if (aLength !== nCommonFR && bLength !== nCommonFR) { + const nChange = 0; // number of change items is not yet known + const transposed = false; // call the original unwrapped functions + const callbacks = [ + { + foundSubsequence, + isCommon + } + ]; + + // Indexes in sequence a of last points in furthest reaching paths + // from outside the start at top left in the forward direction: + const aIndexesF = [NOT_YET_SET]; + // from the end at bottom right in the reverse direction: + const aIndexesR = [NOT_YET_SET]; + + // Initialize one object as output of all calls to divide function. + const division = { + aCommonFollowing: NOT_YET_SET, + aCommonPreceding: NOT_YET_SET, + aEndPreceding: NOT_YET_SET, + aStartFollowing: NOT_YET_SET, + bCommonFollowing: NOT_YET_SET, + bCommonPreceding: NOT_YET_SET, + bEndPreceding: NOT_YET_SET, + bStartFollowing: NOT_YET_SET, + nChangeFollowing: NOT_YET_SET, + nChangePreceding: NOT_YET_SET, + nCommonFollowing: NOT_YET_SET, + nCommonPreceding: NOT_YET_SET + }; + + // Find and return common subsequences in the trimmed index intervals. + findSubsequences( + nChange, + aStart, + aEnd, + bStart, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + if (nCommonR !== 0) { + foundSubsequence(nCommonR, aEnd, bEnd); + } + } +} diff --git a/web/node_modules/diff-sequences/package.json b/web/node_modules/diff-sequences/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0324babcbe8fb8f0e720e7f4b342b507b559536d --- /dev/null +++ b/web/node_modules/diff-sequences/package.json @@ -0,0 +1,39 @@ +{ + "name": "diff-sequences", + "version": "29.6.3", + "repository": { + "type": "git", + "url": "https://github.com/jestjs/jest.git", + "directory": "packages/diff-sequences" + }, + "license": "MIT", + "description": "Compare items in two sequences to find a longest common subsequence", + "keywords": [ + "fast", + "linear", + "space", + "callback", + "diff" + ], + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "devDependencies": { + "@fast-check/jest": "^1.3.0", + "benchmark": "^2.1.4", + "diff": "^5.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b" +} diff --git a/web/node_modules/esbuild/LICENSE.md b/web/node_modules/esbuild/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..2027e8dcf3787f5aac9fcd835e2b80cb75a39211 --- /dev/null +++ b/web/node_modules/esbuild/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evan Wallace + +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/web/node_modules/esbuild/README.md b/web/node_modules/esbuild/README.md new file mode 100644 index 0000000000000000000000000000000000000000..93863d198004eae1c7b17aef26d829dfca4a314f --- /dev/null +++ b/web/node_modules/esbuild/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details. diff --git a/web/node_modules/esbuild/bin/esbuild b/web/node_modules/esbuild/bin/esbuild new file mode 100644 index 0000000000000000000000000000000000000000..f316219bc8220d02288b33555d946519b82f8366 --- /dev/null +++ b/web/node_modules/esbuild/bin/esbuild @@ -0,0 +1,222 @@ +#!/usr/bin/env node +"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 __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 +)); + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var packageDarwin_arm64 = "@esbuild/darwin-arm64"; +var packageDarwin_x64 = "@esbuild/darwin-x64"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM2 = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM2 = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM: isWASM2 }; +} +function pkgForSomeOtherPlatform() { + const libMainJS = require.resolve("esbuild"); + const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); + if (path.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownUnixlikePackages) { + try { + const pkg = knownUnixlikePackages[unixKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) + return pkg; + } catch { + } + } + for (const windowsKey in knownWindowsPackages) { + try { + const pkg = knownWindowsPackages[windowsKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) + return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} +function generateBinPath() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; + } + } + const { pkg, subpath, isWASM: isWASM2 } = pkgAndSubpathForCurrentPlatform(); + let binPath2; + try { + binPath2 = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath2 = downloadedBinPath(pkg, subpath); + if (!fs.existsSync(binPath2)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + let suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild on Windows or macOS and copying "node_modules" +into a Docker image that runs Linux, or by copying "node_modules" between +Windows and WSL environments. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead of npm which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { + suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild with npm running inside of Rosetta 2 and then +trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta +2 is Apple's on-the-fly x86_64-to-arm64 translation service). + +If you are installing with npm, you can try ensuring that both npm and node are +not running under Rosetta 2 and then reinstalling esbuild. This likely involves +changing how you installed npm and/or node. For example, installing node with +the universal installer here should work: https://nodejs.org/en/download/. Or +you could consider using yarn instead of npm which has built-in support for +installing a package on multiple platforms simultaneously. + +If you are installing with yarn, you can try listing both "arm64" and "x64" +in your ".yarnrc.yml" file using the "supportedArchitectures" feature: +https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + } + throw new Error(` +You installed esbuild for another platform than the one you're currently using. +This won't work because esbuild is written with native code and needs to +install a platform-specific binary executable. +${suggestions} +Another alternative is to use the "esbuild-wasm" package instead, which works +the same way on all platforms. But it comes with a heavy performance cost and +can sometimes be 10x slower than the "esbuild" package, so you may also not +want to do that. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. + +If you are installing esbuild with npm, make sure that you don't specify the +"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature +of "package.json" is used by esbuild to install the correct binary executable +for your current platform.`); + } + throw e; + } + } + if (/\.zip\//.test(binPath2)) { + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = path.join( + root, + "node_modules", + ".cache", + "esbuild", + `pnpapi-${pkg.replace("/", "-")}-${"0.19.12"}-${path.basename(subpath)}` + ); + if (!fs.existsSync(binTargetPath)) { + fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); + fs.copyFileSync(binPath2, binTargetPath); + fs.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath, isWASM: isWASM2 }; + } + } + return { binPath: binPath2, isWASM: isWASM2 }; +} + +// lib/npm/node-shim.ts +var { binPath, isWASM } = generateBinPath(); +if (isWASM) { + require("child_process").execFileSync("node", [binPath].concat(process.argv.slice(2)), { stdio: "inherit" }); +} else { + require("child_process").execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" }); +} diff --git a/web/node_modules/esbuild/install.js b/web/node_modules/esbuild/install.js new file mode 100644 index 0000000000000000000000000000000000000000..6031a0d963acacc7550602f63282b86ad846e689 --- /dev/null +++ b/web/node_modules/esbuild/install.js @@ -0,0 +1,288 @@ +"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 __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 +)); + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM }; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} + +// lib/npm/node-install.ts +var fs2 = require("fs"); +var os2 = require("os"); +var path2 = require("path"); +var zlib = require("zlib"); +var https = require("https"); +var child_process = require("child_process"); +var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version; +var toPath = path2.join(__dirname, "bin", "esbuild"); +var isToPathJS = true; +function validateBinaryVersion(...command) { + command.push("--version"); + let stdout; + try { + stdout = child_process.execFileSync(command.shift(), command, { + // Without this, this install script strangely crashes with the error + // "EACCES: permission denied, write" but only on Ubuntu Linux when node is + // installed from the Snap Store. This is not a problem when you download + // the official version of node. The problem appears to be that stderr + // (i.e. file descriptor 2) isn't writable? + // + // More info: + // - https://snapcraft.io/ (what the Snap Store is) + // - https://nodejs.org/dist/ (download the official version of node) + // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035 + // + stdio: "pipe" + }).toString().trim(); + } catch (err) { + if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) { + let os3 = "this version of macOS"; + try { + os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim(); + } catch { + } + throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated. + +The Go compiler (which esbuild relies on) no longer supports ${os3}, +which means the "esbuild" binary executable can't be run. You can either: + + * Update your version of macOS to one that the Go compiler supports + * Use the "esbuild-wasm" package instead of the "esbuild" package + * Build esbuild yourself using an older version of the Go compiler +`); + } + throw err; + } + if (stdout !== versionFromPackageJSON) { + throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`); + } +} +function isYarn() { + const { npm_config_user_agent } = process.env; + if (npm_config_user_agent) { + return /\byarn\//.test(npm_config_user_agent); + } + return false; +} +function fetch(url) { + return new Promise((resolve, reject) => { + https.get(url, (res) => { + if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location) + return fetch(res.headers.location).then(resolve, reject); + if (res.statusCode !== 200) + return reject(new Error(`Server responded with ${res.statusCode}`)); + let chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => resolve(Buffer.concat(chunks))); + }).on("error", reject); + }); +} +function extractFileFromTarGzip(buffer, subpath) { + try { + buffer = zlib.unzipSync(buffer); + } catch (err) { + throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`); + } + let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, ""); + let offset = 0; + subpath = `package/${subpath}`; + while (offset < buffer.length) { + let name = str(offset, 100); + let size = parseInt(str(offset + 124, 12), 8); + offset += 512; + if (!isNaN(size)) { + if (name === subpath) + return buffer.subarray(offset, offset + size); + offset += size + 511 & ~511; + } + } + throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`); +} +function installUsingNPM(pkg, subpath, binPath) { + const env = { ...process.env, npm_config_global: void 0 }; + const esbuildLibDir = path2.dirname(require.resolve("esbuild")); + const installDir = path2.join(esbuildLibDir, "npm-install"); + fs2.mkdirSync(installDir); + try { + fs2.writeFileSync(path2.join(installDir, "package.json"), "{}"); + child_process.execSync( + `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`, + { cwd: installDir, stdio: "pipe", env } + ); + const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath); + fs2.renameSync(installedBinPath, binPath); + } finally { + try { + removeRecursive(installDir); + } catch { + } + } +} +function removeRecursive(dir) { + for (const entry of fs2.readdirSync(dir)) { + const entryPath = path2.join(dir, entry); + let stats; + try { + stats = fs2.lstatSync(entryPath); + } catch { + continue; + } + if (stats.isDirectory()) + removeRecursive(entryPath); + else + fs2.unlinkSync(entryPath); + } + fs2.rmdirSync(dir); +} +function applyManualBinaryPathOverride(overridePath) { + const pathString = JSON.stringify(overridePath); + fs2.writeFileSync(toPath, `#!/usr/bin/env node +require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' }); +`); + const libMain = path2.join(__dirname, "lib", "main.js"); + const code = fs2.readFileSync(libMain, "utf8"); + fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString}; +${code}`); +} +function maybeOptimizePackage(binPath) { + if (os2.platform() !== "win32" && !isYarn()) { + const tempPath = path2.join(__dirname, "bin-esbuild"); + try { + fs2.linkSync(binPath, tempPath); + fs2.renameSync(tempPath, toPath); + isToPathJS = false; + fs2.unlinkSync(tempPath); + } catch { + } + } +} +async function downloadDirectlyFromNPM(pkg, subpath, binPath) { + const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`; + console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`); + try { + fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath)); + fs2.chmodSync(binPath, 493); + } catch (e) { + console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`); + throw e; + } +} +async function checkAndPreparePackage() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs2.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + applyManualBinaryPathOverride(ESBUILD_BINARY_PATH); + return; + } + } + const { pkg, subpath } = pkgAndSubpathForCurrentPlatform(); + let binPath; + try { + binPath = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + console.error(`[esbuild] Failed to find package "${pkg}" on the file system + +This can happen if you use the "--no-optional" flag. The "optionalDependencies" +package.json feature is used by esbuild to install the correct binary executable +for your current platform. This install script will now attempt to work around +this. If that fails, you need to remove the "--no-optional" flag to use esbuild. +`); + binPath = downloadedBinPath(pkg, subpath); + try { + console.error(`[esbuild] Trying to install package "${pkg}" using npm`); + installUsingNPM(pkg, subpath, binPath); + } catch (e2) { + console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`); + try { + await downloadDirectlyFromNPM(pkg, subpath, binPath); + } catch (e3) { + throw new Error(`Failed to install package "${pkg}"`); + } + } + } + maybeOptimizePackage(binPath); +} +checkAndPreparePackage().then(() => { + if (isToPathJS) { + validateBinaryVersion(process.execPath, toPath); + } else { + validateBinaryVersion(toPath); + } +}); diff --git a/web/node_modules/esbuild/lib/main.d.ts b/web/node_modules/esbuild/lib/main.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b398f845bc46d69c00b430442e3a150fed693f51 --- /dev/null +++ b/web/node_modules/esbuild/lib/main.d.ts @@ -0,0 +1,676 @@ +export type Platform = 'browser' | 'node' | 'neutral' +export type Format = 'iife' | 'cjs' | 'esm' +export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx' +export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent' +export type Charset = 'ascii' | 'utf8' +export type Drop = 'console' | 'debugger' + +interface CommonOptions { + /** Documentation: https://esbuild.github.io/api/#sourcemap */ + sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both' + /** Documentation: https://esbuild.github.io/api/#legal-comments */ + legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external' + /** Documentation: https://esbuild.github.io/api/#source-root */ + sourceRoot?: string + /** Documentation: https://esbuild.github.io/api/#sources-content */ + sourcesContent?: boolean + + /** Documentation: https://esbuild.github.io/api/#format */ + format?: Format + /** Documentation: https://esbuild.github.io/api/#global-name */ + globalName?: string + /** Documentation: https://esbuild.github.io/api/#target */ + target?: string | string[] + /** Documentation: https://esbuild.github.io/api/#supported */ + supported?: Record + /** Documentation: https://esbuild.github.io/api/#platform */ + platform?: Platform + + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleProps?: RegExp + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + reserveProps?: RegExp + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleQuoted?: boolean + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleCache?: Record + /** Documentation: https://esbuild.github.io/api/#drop */ + drop?: Drop[] + /** Documentation: https://esbuild.github.io/api/#drop-labels */ + dropLabels?: string[] + /** Documentation: https://esbuild.github.io/api/#minify */ + minify?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifyWhitespace?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifyIdentifiers?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifySyntax?: boolean + /** Documentation: https://esbuild.github.io/api/#line-limit */ + lineLimit?: number + /** Documentation: https://esbuild.github.io/api/#charset */ + charset?: Charset + /** Documentation: https://esbuild.github.io/api/#tree-shaking */ + treeShaking?: boolean + /** Documentation: https://esbuild.github.io/api/#ignore-annotations */ + ignoreAnnotations?: boolean + + /** Documentation: https://esbuild.github.io/api/#jsx */ + jsx?: 'transform' | 'preserve' | 'automatic' + /** Documentation: https://esbuild.github.io/api/#jsx-factory */ + jsxFactory?: string + /** Documentation: https://esbuild.github.io/api/#jsx-fragment */ + jsxFragment?: string + /** Documentation: https://esbuild.github.io/api/#jsx-import-source */ + jsxImportSource?: string + /** Documentation: https://esbuild.github.io/api/#jsx-development */ + jsxDev?: boolean + /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */ + jsxSideEffects?: boolean + + /** Documentation: https://esbuild.github.io/api/#define */ + define?: { [key: string]: string } + /** Documentation: https://esbuild.github.io/api/#pure */ + pure?: string[] + /** Documentation: https://esbuild.github.io/api/#keep-names */ + keepNames?: boolean + + /** Documentation: https://esbuild.github.io/api/#color */ + color?: boolean + /** Documentation: https://esbuild.github.io/api/#log-level */ + logLevel?: LogLevel + /** Documentation: https://esbuild.github.io/api/#log-limit */ + logLimit?: number + /** Documentation: https://esbuild.github.io/api/#log-override */ + logOverride?: Record + + /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */ + tsconfigRaw?: string | TsconfigRaw +} + +export interface TsconfigRaw { + compilerOptions?: { + alwaysStrict?: boolean + baseUrl?: string + experimentalDecorators?: boolean + importsNotUsedAsValues?: 'remove' | 'preserve' | 'error' + jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev' + jsxFactory?: string + jsxFragmentFactory?: string + jsxImportSource?: string + paths?: Record + preserveValueImports?: boolean + strict?: boolean + target?: string + useDefineForClassFields?: boolean + verbatimModuleSyntax?: boolean + } +} + +export interface BuildOptions extends CommonOptions { + /** Documentation: https://esbuild.github.io/api/#bundle */ + bundle?: boolean + /** Documentation: https://esbuild.github.io/api/#splitting */ + splitting?: boolean + /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */ + preserveSymlinks?: boolean + /** Documentation: https://esbuild.github.io/api/#outfile */ + outfile?: string + /** Documentation: https://esbuild.github.io/api/#metafile */ + metafile?: boolean + /** Documentation: https://esbuild.github.io/api/#outdir */ + outdir?: string + /** Documentation: https://esbuild.github.io/api/#outbase */ + outbase?: string + /** Documentation: https://esbuild.github.io/api/#external */ + external?: string[] + /** Documentation: https://esbuild.github.io/api/#packages */ + packages?: 'external' + /** Documentation: https://esbuild.github.io/api/#alias */ + alias?: Record + /** Documentation: https://esbuild.github.io/api/#loader */ + loader?: { [ext: string]: Loader } + /** Documentation: https://esbuild.github.io/api/#resolve-extensions */ + resolveExtensions?: string[] + /** Documentation: https://esbuild.github.io/api/#main-fields */ + mainFields?: string[] + /** Documentation: https://esbuild.github.io/api/#conditions */ + conditions?: string[] + /** Documentation: https://esbuild.github.io/api/#write */ + write?: boolean + /** Documentation: https://esbuild.github.io/api/#allow-overwrite */ + allowOverwrite?: boolean + /** Documentation: https://esbuild.github.io/api/#tsconfig */ + tsconfig?: string + /** Documentation: https://esbuild.github.io/api/#out-extension */ + outExtension?: { [ext: string]: string } + /** Documentation: https://esbuild.github.io/api/#public-path */ + publicPath?: string + /** Documentation: https://esbuild.github.io/api/#entry-names */ + entryNames?: string + /** Documentation: https://esbuild.github.io/api/#chunk-names */ + chunkNames?: string + /** Documentation: https://esbuild.github.io/api/#asset-names */ + assetNames?: string + /** Documentation: https://esbuild.github.io/api/#inject */ + inject?: string[] + /** Documentation: https://esbuild.github.io/api/#banner */ + banner?: { [type: string]: string } + /** Documentation: https://esbuild.github.io/api/#footer */ + footer?: { [type: string]: string } + /** Documentation: https://esbuild.github.io/api/#entry-points */ + entryPoints?: string[] | Record | { in: string, out: string }[] + /** Documentation: https://esbuild.github.io/api/#stdin */ + stdin?: StdinOptions + /** Documentation: https://esbuild.github.io/plugins/ */ + plugins?: Plugin[] + /** Documentation: https://esbuild.github.io/api/#working-directory */ + absWorkingDir?: string + /** Documentation: https://esbuild.github.io/api/#node-paths */ + nodePaths?: string[]; // The "NODE_PATH" variable from Node.js +} + +export interface StdinOptions { + contents: string | Uint8Array + resolveDir?: string + sourcefile?: string + loader?: Loader +} + +export interface Message { + id: string + pluginName: string + text: string + location: Location | null + notes: Note[] + + /** + * Optional user-specified data that is passed through unmodified. You can + * use this to stash the original error, for example. + */ + detail: any +} + +export interface Note { + text: string + location: Location | null +} + +export interface Location { + file: string + namespace: string + /** 1-based */ + line: number + /** 0-based, in bytes */ + column: number + /** in bytes */ + length: number + lineText: string + suggestion: string +} + +export interface OutputFile { + path: string + contents: Uint8Array + hash: string + /** "contents" as text (changes automatically with "contents") */ + readonly text: string +} + +export interface BuildResult { + errors: Message[] + warnings: Message[] + /** Only when "write: false" */ + outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined) + /** Only when "metafile: true" */ + metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined) + /** Only when "mangleCache" is present */ + mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) +} + +export interface BuildFailure extends Error { + errors: Message[] + warnings: Message[] +} + +/** Documentation: https://esbuild.github.io/api/#serve-arguments */ +export interface ServeOptions { + port?: number + host?: string + servedir?: string + keyfile?: string + certfile?: string + fallback?: string + onRequest?: (args: ServeOnRequestArgs) => void +} + +export interface ServeOnRequestArgs { + remoteAddress: string + method: string + path: string + status: number + /** The time to generate the response, not to send it */ + timeInMS: number +} + +/** Documentation: https://esbuild.github.io/api/#serve-return-values */ +export interface ServeResult { + port: number + host: string +} + +export interface TransformOptions extends CommonOptions { + /** Documentation: https://esbuild.github.io/api/#sourcefile */ + sourcefile?: string + /** Documentation: https://esbuild.github.io/api/#loader */ + loader?: Loader + /** Documentation: https://esbuild.github.io/api/#banner */ + banner?: string + /** Documentation: https://esbuild.github.io/api/#footer */ + footer?: string +} + +export interface TransformResult { + code: string + map: string + warnings: Message[] + /** Only when "mangleCache" is present */ + mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) + /** Only when "legalComments" is "external" */ + legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) +} + +export interface TransformFailure extends Error { + errors: Message[] + warnings: Message[] +} + +export interface Plugin { + name: string + setup: (build: PluginBuild) => (void | Promise) +} + +export interface PluginBuild { + /** Documentation: https://esbuild.github.io/plugins/#build-options */ + initialOptions: BuildOptions + + /** Documentation: https://esbuild.github.io/plugins/#resolve */ + resolve(path: string, options?: ResolveOptions): Promise + + /** Documentation: https://esbuild.github.io/plugins/#on-start */ + onStart(callback: () => + (OnStartResult | null | void | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-end */ + onEnd(callback: (result: BuildResult) => + (OnEndResult | null | void | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-resolve */ + onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => + (OnResolveResult | null | undefined | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-load */ + onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => + (OnLoadResult | null | undefined | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-dispose */ + onDispose(callback: () => void): void + + // This is a full copy of the esbuild library in case you need it + esbuild: { + context: typeof context, + build: typeof build, + buildSync: typeof buildSync, + transform: typeof transform, + transformSync: typeof transformSync, + formatMessages: typeof formatMessages, + formatMessagesSync: typeof formatMessagesSync, + analyzeMetafile: typeof analyzeMetafile, + analyzeMetafileSync: typeof analyzeMetafileSync, + initialize: typeof initialize, + version: typeof version, + } +} + +/** Documentation: https://esbuild.github.io/plugins/#resolve-options */ +export interface ResolveOptions { + pluginName?: string + importer?: string + namespace?: string + resolveDir?: string + kind?: ImportKind + pluginData?: any +} + +/** Documentation: https://esbuild.github.io/plugins/#resolve-results */ +export interface ResolveResult { + errors: Message[] + warnings: Message[] + + path: string + external: boolean + sideEffects: boolean + namespace: string + suffix: string + pluginData: any +} + +export interface OnStartResult { + errors?: PartialMessage[] + warnings?: PartialMessage[] +} + +export interface OnEndResult { + errors?: PartialMessage[] + warnings?: PartialMessage[] +} + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */ +export interface OnResolveOptions { + filter: RegExp + namespace?: string +} + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */ +export interface OnResolveArgs { + path: string + importer: string + namespace: string + resolveDir: string + kind: ImportKind + pluginData: any +} + +export type ImportKind = + | 'entry-point' + + // JS + | 'import-statement' + | 'require-call' + | 'dynamic-import' + | 'require-resolve' + + // CSS + | 'import-rule' + | 'composes-from' + | 'url-token' + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */ +export interface OnResolveResult { + pluginName?: string + + errors?: PartialMessage[] + warnings?: PartialMessage[] + + path?: string + external?: boolean + sideEffects?: boolean + namespace?: string + suffix?: string + pluginData?: any + + watchFiles?: string[] + watchDirs?: string[] +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-options */ +export interface OnLoadOptions { + filter: RegExp + namespace?: string +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */ +export interface OnLoadArgs { + path: string + namespace: string + suffix: string + pluginData: any + with: Record +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-results */ +export interface OnLoadResult { + pluginName?: string + + errors?: PartialMessage[] + warnings?: PartialMessage[] + + contents?: string | Uint8Array + resolveDir?: string + loader?: Loader + pluginData?: any + + watchFiles?: string[] + watchDirs?: string[] +} + +export interface PartialMessage { + id?: string + pluginName?: string + text?: string + location?: Partial | null + notes?: PartialNote[] + detail?: any +} + +export interface PartialNote { + text?: string + location?: Partial | null +} + +/** Documentation: https://esbuild.github.io/api/#metafile */ +export interface Metafile { + inputs: { + [path: string]: { + bytes: number + imports: { + path: string + kind: ImportKind + external?: boolean + original?: string + with?: Record + }[] + format?: 'cjs' | 'esm' + with?: Record + } + } + outputs: { + [path: string]: { + bytes: number + inputs: { + [path: string]: { + bytesInOutput: number + } + } + imports: { + path: string + kind: ImportKind | 'file-loader' + external?: boolean + }[] + exports: string[] + entryPoint?: string + cssBundle?: string + } + } +} + +export interface FormatMessagesOptions { + kind: 'error' | 'warning' + color?: boolean + terminalWidth?: number +} + +export interface AnalyzeMetafileOptions { + color?: boolean + verbose?: boolean +} + +export interface WatchOptions { +} + +export interface BuildContext { + /** Documentation: https://esbuild.github.io/api/#rebuild */ + rebuild(): Promise> + + /** Documentation: https://esbuild.github.io/api/#watch */ + watch(options?: WatchOptions): Promise + + /** Documentation: https://esbuild.github.io/api/#serve */ + serve(options?: ServeOptions): Promise + + cancel(): Promise + dispose(): Promise +} + +// This is a TypeScript type-level function which replaces any keys in "In" +// that aren't in "Out" with "never". We use this to reject properties with +// typos in object literals. See: https://stackoverflow.com/questions/49580725 +type SameShape = In & { [Key in Exclude]: never } + +/** + * This function invokes the "esbuild" command-line tool for you. It returns a + * promise that either resolves with a "BuildResult" object or rejects with a + * "BuildFailure" object. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function build(options: SameShape): Promise> + +/** + * This is the advanced long-running form of "build" that supports additional + * features such as watch mode and a local development server. + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function context(options: SameShape): Promise> + +/** + * This function transforms a single JavaScript file. It can be used to minify + * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript + * to older JavaScript. It returns a promise that is either resolved with a + * "TransformResult" object or rejected with a "TransformFailure" object. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#transform + */ +export declare function transform(input: string | Uint8Array, options?: SameShape): Promise> + +/** + * Converts log messages to formatted message strings suitable for printing in + * the terminal. This allows you to reuse the built-in behavior of esbuild's + * log message formatter. This is a batch-oriented API for efficiency. + * + * - Works in node: yes + * - Works in browser: yes + */ +export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise + +/** + * Pretty-prints an analysis of the metafile JSON to a string. This is just for + * convenience to be able to match esbuild's pretty-printing exactly. If you want + * to customize it, you can just inspect the data in the metafile yourself. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#analyze + */ +export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise + +/** + * A synchronous version of "build". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function buildSync(options: SameShape): BuildResult + +/** + * A synchronous version of "transform". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#transform + */ +export declare function transformSync(input: string | Uint8Array, options?: SameShape): TransformResult + +/** + * A synchronous version of "formatMessages". + * + * - Works in node: yes + * - Works in browser: no + */ +export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[] + +/** + * A synchronous version of "analyzeMetafile". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#analyze + */ +export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string + +/** + * This configures the browser-based version of esbuild. It is necessary to + * call this first and wait for the returned promise to be resolved before + * making other API calls when using esbuild in the browser. + * + * - Works in node: yes + * - Works in browser: yes ("options" is required) + * + * Documentation: https://esbuild.github.io/api/#browser + */ +export declare function initialize(options: InitializeOptions): Promise + +export interface InitializeOptions { + /** + * The URL of the "esbuild.wasm" file. This must be provided when running + * esbuild in the browser. + */ + wasmURL?: string | URL + + /** + * The result of calling "new WebAssembly.Module(buffer)" where "buffer" + * is a typed array or ArrayBuffer containing the binary code of the + * "esbuild.wasm" file. + * + * You can use this as an alternative to "wasmURL" for environments where it's + * not possible to download the WebAssembly module. + */ + wasmModule?: WebAssembly.Module + + /** + * By default esbuild runs the WebAssembly-based browser API in a web worker + * to avoid blocking the UI thread. This can be disabled by setting "worker" + * to false. + */ + worker?: boolean +} + +export let version: string + +// Call this function to terminate esbuild's child process. The child process +// is not terminated and re-created for each API call because it's more +// efficient to keep it around when there are multiple API calls. +// +// In node this happens automatically before the parent node process exits. So +// you only need to call this if you know you will not make any more esbuild +// API calls and you want to clean up resources. +// +// Unlike node, Deno lacks the necessary APIs to clean up child processes +// automatically. You must manually call stop() in Deno when you're done +// using esbuild or Deno will continue running forever. +export declare function stop(): void; diff --git a/web/node_modules/esbuild/lib/main.js b/web/node_modules/esbuild/lib/main.js new file mode 100644 index 0000000000000000000000000000000000000000..4449440fc9d8aaf53221d12addc3310b18662aab --- /dev/null +++ b/web/node_modules/esbuild/lib/main.js @@ -0,0 +1,2435 @@ +"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 __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); + +// lib/npm/node.ts +var node_exports = {}; +__export(node_exports, { + analyzeMetafile: () => analyzeMetafile, + analyzeMetafileSync: () => analyzeMetafileSync, + build: () => build, + buildSync: () => buildSync, + context: () => context, + default: () => node_default, + formatMessages: () => formatMessages, + formatMessagesSync: () => formatMessagesSync, + initialize: () => initialize, + stop: () => stop, + transform: () => transform, + transformSync: () => transformSync, + version: () => version +}); +module.exports = __toCommonJS(node_exports); + +// lib/shared/stdio_protocol.ts +function encodePacket(packet) { + let visit = (value) => { + if (value === null) { + bb.write8(0); + } else if (typeof value === "boolean") { + bb.write8(1); + bb.write8(+value); + } else if (typeof value === "number") { + bb.write8(2); + bb.write32(value | 0); + } else if (typeof value === "string") { + bb.write8(3); + bb.write(encodeUTF8(value)); + } else if (value instanceof Uint8Array) { + bb.write8(4); + bb.write(value); + } else if (value instanceof Array) { + bb.write8(5); + bb.write32(value.length); + for (let item of value) { + visit(item); + } + } else { + let keys = Object.keys(value); + bb.write8(6); + bb.write32(keys.length); + for (let key of keys) { + bb.write(encodeUTF8(key)); + visit(value[key]); + } + } + }; + let bb = new ByteBuffer(); + bb.write32(0); + bb.write32(packet.id << 1 | +!packet.isRequest); + visit(packet.value); + writeUInt32LE(bb.buf, bb.len - 4, 0); + return bb.buf.subarray(0, bb.len); +} +function decodePacket(bytes) { + let visit = () => { + switch (bb.read8()) { + case 0: + return null; + case 1: + return !!bb.read8(); + case 2: + return bb.read32(); + case 3: + return decodeUTF8(bb.read()); + case 4: + return bb.read(); + case 5: { + let count = bb.read32(); + let value2 = []; + for (let i = 0; i < count; i++) { + value2.push(visit()); + } + return value2; + } + case 6: { + let count = bb.read32(); + let value2 = {}; + for (let i = 0; i < count; i++) { + value2[decodeUTF8(bb.read())] = visit(); + } + return value2; + } + default: + throw new Error("Invalid packet"); + } + }; + let bb = new ByteBuffer(bytes); + let id = bb.read32(); + let isRequest = (id & 1) === 0; + id >>>= 1; + let value = visit(); + if (bb.ptr !== bytes.length) { + throw new Error("Invalid packet"); + } + return { id, isRequest, value }; +} +var ByteBuffer = class { + constructor(buf = new Uint8Array(1024)) { + this.buf = buf; + this.len = 0; + this.ptr = 0; + } + _write(delta) { + if (this.len + delta > this.buf.length) { + let clone = new Uint8Array((this.len + delta) * 2); + clone.set(this.buf); + this.buf = clone; + } + this.len += delta; + return this.len - delta; + } + write8(value) { + let offset = this._write(1); + this.buf[offset] = value; + } + write32(value) { + let offset = this._write(4); + writeUInt32LE(this.buf, value, offset); + } + write(bytes) { + let offset = this._write(4 + bytes.length); + writeUInt32LE(this.buf, bytes.length, offset); + this.buf.set(bytes, offset + 4); + } + _read(delta) { + if (this.ptr + delta > this.buf.length) { + throw new Error("Invalid packet"); + } + this.ptr += delta; + return this.ptr - delta; + } + read8() { + return this.buf[this._read(1)]; + } + read32() { + return readUInt32LE(this.buf, this._read(4)); + } + read() { + let length = this.read32(); + let bytes = new Uint8Array(length); + let ptr = this._read(bytes.length); + bytes.set(this.buf.subarray(ptr, ptr + length)); + return bytes; + } +}; +var encodeUTF8; +var decodeUTF8; +var encodeInvariant; +if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { + let encoder = new TextEncoder(); + let decoder = new TextDecoder(); + encodeUTF8 = (text) => encoder.encode(text); + decodeUTF8 = (bytes) => decoder.decode(bytes); + encodeInvariant = 'new TextEncoder().encode("")'; +} else if (typeof Buffer !== "undefined") { + encodeUTF8 = (text) => Buffer.from(text); + decodeUTF8 = (bytes) => { + let { buffer, byteOffset, byteLength } = bytes; + return Buffer.from(buffer, byteOffset, byteLength).toString(); + }; + encodeInvariant = 'Buffer.from("")'; +} else { + throw new Error("No UTF-8 codec found"); +} +if (!(encodeUTF8("") instanceof Uint8Array)) + throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false + +This indicates that your JavaScript environment is broken. You cannot use +esbuild in this environment because esbuild relies on this invariant. This +is not a problem with esbuild. You need to fix your environment instead. +`); +function readUInt32LE(buffer, offset) { + return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24; +} +function writeUInt32LE(buffer, value, offset) { + buffer[offset++] = value; + buffer[offset++] = value >> 8; + buffer[offset++] = value >> 16; + buffer[offset++] = value >> 24; +} + +// lib/shared/common.ts +var quote = JSON.stringify; +var buildLogLevelDefault = "warning"; +var transformLogLevelDefault = "silent"; +function validateTarget(target) { + validateStringValue(target, "target"); + if (target.indexOf(",") >= 0) + throw new Error(`Invalid target: ${target}`); + return target; +} +var canBeAnything = () => null; +var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; +var mustBeString = (value) => typeof value === "string" ? null : "a string"; +var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; +var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; +var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; +var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; +var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; +var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object"; +var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; +var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; +var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; +var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; +var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array"; +var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; +var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL"; +function getFlag(object, keys, key, mustBeFn) { + let value = object[key]; + keys[key + ""] = true; + if (value === void 0) + return void 0; + let mustBe = mustBeFn(value); + if (mustBe !== null) + throw new Error(`${quote(key)} must be ${mustBe}`); + return value; +} +function checkForInvalidFlags(object, keys, where) { + for (let key in object) { + if (!(key in keys)) { + throw new Error(`Invalid option ${where}: ${quote(key)}`); + } + } +} +function validateInitializeOptions(options) { + let keys = /* @__PURE__ */ Object.create(null); + let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL); + let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule); + let worker = getFlag(options, keys, "worker", mustBeBoolean); + checkForInvalidFlags(options, keys, "in initialize() call"); + return { + wasmURL, + wasmModule, + worker + }; +} +function validateMangleCache(mangleCache) { + let validated; + if (mangleCache !== void 0) { + validated = /* @__PURE__ */ Object.create(null); + for (let key in mangleCache) { + let value = mangleCache[key]; + if (typeof value === "string" || value === false) { + validated[key] = value; + } else { + throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`); + } + } + } + return validated; +} +function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { + let color = getFlag(options, keys, "color", mustBeBoolean); + let logLevel = getFlag(options, keys, "logLevel", mustBeString); + let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); + if (color !== void 0) + flags.push(`--color=${color}`); + else if (isTTY2) + flags.push(`--color=true`); + flags.push(`--log-level=${logLevel || logLevelDefault}`); + flags.push(`--log-limit=${logLimit || 0}`); +} +function validateStringValue(value, what, key) { + if (typeof value !== "string") { + throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`); + } + return value; +} +function pushCommonFlags(flags, options, keys) { + let legalComments = getFlag(options, keys, "legalComments", mustBeString); + let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString); + let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); + let target = getFlag(options, keys, "target", mustBeStringOrArray); + let format = getFlag(options, keys, "format", mustBeString); + let globalName = getFlag(options, keys, "globalName", mustBeString); + let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp); + let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp); + let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean); + let minify = getFlag(options, keys, "minify", mustBeBoolean); + let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); + let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); + let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); + let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger); + let drop = getFlag(options, keys, "drop", mustBeArray); + let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray); + let charset = getFlag(options, keys, "charset", mustBeString); + let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean); + let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean); + let jsx = getFlag(options, keys, "jsx", mustBeString); + let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); + let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); + let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString); + let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean); + let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean); + let define = getFlag(options, keys, "define", mustBeObject); + let logOverride = getFlag(options, keys, "logOverride", mustBeObject); + let supported = getFlag(options, keys, "supported", mustBeObject); + let pure = getFlag(options, keys, "pure", mustBeArray); + let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); + let platform = getFlag(options, keys, "platform", mustBeString); + let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); + if (legalComments) + flags.push(`--legal-comments=${legalComments}`); + if (sourceRoot !== void 0) + flags.push(`--source-root=${sourceRoot}`); + if (sourcesContent !== void 0) + flags.push(`--sources-content=${sourcesContent}`); + if (target) { + if (Array.isArray(target)) + flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`); + else + flags.push(`--target=${validateTarget(target)}`); + } + if (format) + flags.push(`--format=${format}`); + if (globalName) + flags.push(`--global-name=${globalName}`); + if (platform) + flags.push(`--platform=${platform}`); + if (tsconfigRaw) + flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); + if (minify) + flags.push("--minify"); + if (minifySyntax) + flags.push("--minify-syntax"); + if (minifyWhitespace) + flags.push("--minify-whitespace"); + if (minifyIdentifiers) + flags.push("--minify-identifiers"); + if (lineLimit) + flags.push(`--line-limit=${lineLimit}`); + if (charset) + flags.push(`--charset=${charset}`); + if (treeShaking !== void 0) + flags.push(`--tree-shaking=${treeShaking}`); + if (ignoreAnnotations) + flags.push(`--ignore-annotations`); + if (drop) + for (let what of drop) + flags.push(`--drop:${validateStringValue(what, "drop")}`); + if (dropLabels) + flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`); + if (mangleProps) + flags.push(`--mangle-props=${mangleProps.source}`); + if (reserveProps) + flags.push(`--reserve-props=${reserveProps.source}`); + if (mangleQuoted !== void 0) + flags.push(`--mangle-quoted=${mangleQuoted}`); + if (jsx) + flags.push(`--jsx=${jsx}`); + if (jsxFactory) + flags.push(`--jsx-factory=${jsxFactory}`); + if (jsxFragment) + flags.push(`--jsx-fragment=${jsxFragment}`); + if (jsxImportSource) + flags.push(`--jsx-import-source=${jsxImportSource}`); + if (jsxDev) + flags.push(`--jsx-dev`); + if (jsxSideEffects) + flags.push(`--jsx-side-effects`); + if (define) { + for (let key in define) { + if (key.indexOf("=") >= 0) + throw new Error(`Invalid define: ${key}`); + flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); + } + } + if (logOverride) { + for (let key in logOverride) { + if (key.indexOf("=") >= 0) + throw new Error(`Invalid log override: ${key}`); + flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); + } + } + if (supported) { + for (let key in supported) { + if (key.indexOf("=") >= 0) + throw new Error(`Invalid supported: ${key}`); + const value = supported[key]; + if (typeof value !== "boolean") + throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`); + flags.push(`--supported:${key}=${value}`); + } + } + if (pure) + for (let fn of pure) + flags.push(`--pure:${validateStringValue(fn, "pure")}`); + if (keepNames) + flags.push(`--keep-names`); +} +function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { + var _a2; + let flags = []; + let entries = []; + let keys = /* @__PURE__ */ Object.create(null); + let stdinContents = null; + let stdinResolveDir = null; + pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); + pushCommonFlags(flags, options, keys); + let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); + let bundle = getFlag(options, keys, "bundle", mustBeBoolean); + let splitting = getFlag(options, keys, "splitting", mustBeBoolean); + let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); + let metafile = getFlag(options, keys, "metafile", mustBeBoolean); + let outfile = getFlag(options, keys, "outfile", mustBeString); + let outdir = getFlag(options, keys, "outdir", mustBeString); + let outbase = getFlag(options, keys, "outbase", mustBeString); + let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); + let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray); + let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray); + let mainFields = getFlag(options, keys, "mainFields", mustBeArray); + let conditions = getFlag(options, keys, "conditions", mustBeArray); + let external = getFlag(options, keys, "external", mustBeArray); + let packages = getFlag(options, keys, "packages", mustBeString); + let alias = getFlag(options, keys, "alias", mustBeObject); + let loader = getFlag(options, keys, "loader", mustBeObject); + let outExtension = getFlag(options, keys, "outExtension", mustBeObject); + let publicPath = getFlag(options, keys, "publicPath", mustBeString); + let entryNames = getFlag(options, keys, "entryNames", mustBeString); + let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); + let assetNames = getFlag(options, keys, "assetNames", mustBeString); + let inject = getFlag(options, keys, "inject", mustBeArray); + let banner = getFlag(options, keys, "banner", mustBeObject); + let footer = getFlag(options, keys, "footer", mustBeObject); + let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints); + let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); + let stdin = getFlag(options, keys, "stdin", mustBeObject); + let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault; + let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean); + let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); + keys.plugins = true; + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (sourcemap) + flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); + if (bundle) + flags.push("--bundle"); + if (allowOverwrite) + flags.push("--allow-overwrite"); + if (splitting) + flags.push("--splitting"); + if (preserveSymlinks) + flags.push("--preserve-symlinks"); + if (metafile) + flags.push(`--metafile`); + if (outfile) + flags.push(`--outfile=${outfile}`); + if (outdir) + flags.push(`--outdir=${outdir}`); + if (outbase) + flags.push(`--outbase=${outbase}`); + if (tsconfig) + flags.push(`--tsconfig=${tsconfig}`); + if (packages) + flags.push(`--packages=${packages}`); + if (resolveExtensions) { + let values = []; + for (let value of resolveExtensions) { + validateStringValue(value, "resolve extension"); + if (value.indexOf(",") >= 0) + throw new Error(`Invalid resolve extension: ${value}`); + values.push(value); + } + flags.push(`--resolve-extensions=${values.join(",")}`); + } + if (publicPath) + flags.push(`--public-path=${publicPath}`); + if (entryNames) + flags.push(`--entry-names=${entryNames}`); + if (chunkNames) + flags.push(`--chunk-names=${chunkNames}`); + if (assetNames) + flags.push(`--asset-names=${assetNames}`); + if (mainFields) { + let values = []; + for (let value of mainFields) { + validateStringValue(value, "main field"); + if (value.indexOf(",") >= 0) + throw new Error(`Invalid main field: ${value}`); + values.push(value); + } + flags.push(`--main-fields=${values.join(",")}`); + } + if (conditions) { + let values = []; + for (let value of conditions) { + validateStringValue(value, "condition"); + if (value.indexOf(",") >= 0) + throw new Error(`Invalid condition: ${value}`); + values.push(value); + } + flags.push(`--conditions=${values.join(",")}`); + } + if (external) + for (let name of external) + flags.push(`--external:${validateStringValue(name, "external")}`); + if (alias) { + for (let old in alias) { + if (old.indexOf("=") >= 0) + throw new Error(`Invalid package name in alias: ${old}`); + flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`); + } + } + if (banner) { + for (let type in banner) { + if (type.indexOf("=") >= 0) + throw new Error(`Invalid banner file type: ${type}`); + flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); + } + } + if (footer) { + for (let type in footer) { + if (type.indexOf("=") >= 0) + throw new Error(`Invalid footer file type: ${type}`); + flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); + } + } + if (inject) + for (let path3 of inject) + flags.push(`--inject:${validateStringValue(path3, "inject")}`); + if (loader) { + for (let ext in loader) { + if (ext.indexOf("=") >= 0) + throw new Error(`Invalid loader extension: ${ext}`); + flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`); + } + } + if (outExtension) { + for (let ext in outExtension) { + if (ext.indexOf("=") >= 0) + throw new Error(`Invalid out extension: ${ext}`); + flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`); + } + } + if (entryPoints) { + if (Array.isArray(entryPoints)) { + for (let i = 0, n = entryPoints.length; i < n; i++) { + let entryPoint = entryPoints[i]; + if (typeof entryPoint === "object" && entryPoint !== null) { + let entryPointKeys = /* @__PURE__ */ Object.create(null); + let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); + let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); + checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); + if (input === void 0) + throw new Error('Missing property "in" for entry point at index ' + i); + if (output === void 0) + throw new Error('Missing property "out" for entry point at index ' + i); + entries.push([output, input]); + } else { + entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); + } + } + } else { + for (let key in entryPoints) { + entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); + } + } + } + if (stdin) { + let stdinKeys = /* @__PURE__ */ Object.create(null); + let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); + let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); + let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); + let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); + checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); + if (sourcefile) + flags.push(`--sourcefile=${sourcefile}`); + if (loader2) + flags.push(`--loader=${loader2}`); + if (resolveDir) + stdinResolveDir = resolveDir; + if (typeof contents === "string") + stdinContents = encodeUTF8(contents); + else if (contents instanceof Uint8Array) + stdinContents = contents; + } + let nodePaths = []; + if (nodePathsInput) { + for (let value of nodePathsInput) { + value += ""; + nodePaths.push(value); + } + } + return { + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir, + nodePaths, + mangleCache: validateMangleCache(mangleCache) + }; +} +function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) { + let flags = []; + let keys = /* @__PURE__ */ Object.create(null); + pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); + pushCommonFlags(flags, options, keys); + let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); + let sourcefile = getFlag(options, keys, "sourcefile", mustBeString); + let loader = getFlag(options, keys, "loader", mustBeString); + let banner = getFlag(options, keys, "banner", mustBeString); + let footer = getFlag(options, keys, "footer", mustBeString); + let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (sourcemap) + flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); + if (sourcefile) + flags.push(`--sourcefile=${sourcefile}`); + if (loader) + flags.push(`--loader=${loader}`); + if (banner) + flags.push(`--banner=${banner}`); + if (footer) + flags.push(`--footer=${footer}`); + return { + flags, + mangleCache: validateMangleCache(mangleCache) + }; +} +function createChannel(streamIn) { + const requestCallbacksByKey = {}; + const closeData = { didClose: false, reason: "" }; + let responseCallbacks = {}; + let nextRequestID = 0; + let nextBuildKey = 0; + let stdout = new Uint8Array(16 * 1024); + let stdoutUsed = 0; + let readFromStdout = (chunk) => { + let limit = stdoutUsed + chunk.length; + if (limit > stdout.length) { + let swap = new Uint8Array(limit * 2); + swap.set(stdout); + stdout = swap; + } + stdout.set(chunk, stdoutUsed); + stdoutUsed += chunk.length; + let offset = 0; + while (offset + 4 <= stdoutUsed) { + let length = readUInt32LE(stdout, offset); + if (offset + 4 + length > stdoutUsed) { + break; + } + offset += 4; + handleIncomingPacket(stdout.subarray(offset, offset + length)); + offset += length; + } + if (offset > 0) { + stdout.copyWithin(0, offset, stdoutUsed); + stdoutUsed -= offset; + } + }; + let afterClose = (error) => { + closeData.didClose = true; + if (error) + closeData.reason = ": " + (error.message || error); + const text = "The service was stopped" + closeData.reason; + for (let id in responseCallbacks) { + responseCallbacks[id](text, null); + } + responseCallbacks = {}; + }; + let sendRequest = (refs, value, callback) => { + if (closeData.didClose) + return callback("The service is no longer running" + closeData.reason, null); + let id = nextRequestID++; + responseCallbacks[id] = (error, response) => { + try { + callback(error, response); + } finally { + if (refs) + refs.unref(); + } + }; + if (refs) + refs.ref(); + streamIn.writeToStdin(encodePacket({ id, isRequest: true, value })); + }; + let sendResponse = (id, value) => { + if (closeData.didClose) + throw new Error("The service is no longer running" + closeData.reason); + streamIn.writeToStdin(encodePacket({ id, isRequest: false, value })); + }; + let handleRequest = async (id, request) => { + try { + if (request.command === "ping") { + sendResponse(id, {}); + return; + } + if (typeof request.key === "number") { + const requestCallbacks = requestCallbacksByKey[request.key]; + if (!requestCallbacks) { + return; + } + const callback = requestCallbacks[request.command]; + if (callback) { + await callback(id, request); + return; + } + } + throw new Error(`Invalid command: ` + request.command); + } catch (e) { + const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")]; + try { + sendResponse(id, { errors }); + } catch { + } + } + }; + let isFirstPacket = true; + let handleIncomingPacket = (bytes) => { + if (isFirstPacket) { + isFirstPacket = false; + let binaryVersion = String.fromCharCode(...bytes); + if (binaryVersion !== "0.19.12") { + throw new Error(`Cannot start service: Host version "${"0.19.12"}" does not match binary version ${quote(binaryVersion)}`); + } + return; + } + let packet = decodePacket(bytes); + if (packet.isRequest) { + handleRequest(packet.id, packet.value); + } else { + let callback = responseCallbacks[packet.id]; + delete responseCallbacks[packet.id]; + if (packet.value.error) + callback(packet.value.error, {}); + else + callback(null, packet.value); + } + }; + let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => { + let refCount = 0; + const buildKey = nextBuildKey++; + const requestCallbacks = {}; + const buildRefs = { + ref() { + if (++refCount === 1) { + if (refs) + refs.ref(); + } + }, + unref() { + if (--refCount === 0) { + delete requestCallbacksByKey[buildKey]; + if (refs) + refs.unref(); + } + } + }; + requestCallbacksByKey[buildKey] = requestCallbacks; + buildRefs.ref(); + buildOrContextImpl( + callName, + buildKey, + sendRequest, + sendResponse, + buildRefs, + streamIn, + requestCallbacks, + options, + isTTY2, + defaultWD2, + (err, res) => { + try { + callback(err, res); + } finally { + buildRefs.unref(); + } + } + ); + }; + let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => { + const details = createObjectStash(); + let start = (inputPath) => { + try { + if (typeof input !== "string" && !(input instanceof Uint8Array)) + throw new Error('The input to "transform" must be a string or a Uint8Array'); + let { + flags, + mangleCache + } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault); + let request = { + command: "transform", + flags, + inputFS: inputPath !== null, + input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input + }; + if (mangleCache) + request.mangleCache = mangleCache; + sendRequest(refs, request, (error, response) => { + if (error) + return callback(new Error(error), null); + let errors = replaceDetailsInMessages(response.errors, details); + let warnings = replaceDetailsInMessages(response.warnings, details); + let outstanding = 1; + let next = () => { + if (--outstanding === 0) { + let result = { + warnings, + code: response.code, + map: response.map, + mangleCache: void 0, + legalComments: void 0 + }; + if ("legalComments" in response) + result.legalComments = response == null ? void 0 : response.legalComments; + if (response.mangleCache) + result.mangleCache = response == null ? void 0 : response.mangleCache; + callback(null, result); + } + }; + if (errors.length > 0) + return callback(failureErrorWithLog("Transform failed", errors, warnings), null); + if (response.codeFS) { + outstanding++; + fs3.readFile(response.code, (err, contents) => { + if (err !== null) { + callback(err, null); + } else { + response.code = contents; + next(); + } + }); + } + if (response.mapFS) { + outstanding++; + fs3.readFile(response.map, (err, contents) => { + if (err !== null) { + callback(err, null); + } else { + response.map = contents; + next(); + } + }); + } + next(); + }); + } catch (e) { + let flags = []; + try { + pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault); + } catch { + } + const error = extractErrorMessageV8(e, streamIn, details, void 0, ""); + sendRequest(refs, { command: "error", flags, error }, () => { + error.detail = details.load(error.detail); + callback(failureErrorWithLog("Transform failed", [error], []), null); + }); + } + }; + if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) { + let next = start; + start = () => fs3.writeFile(input, next); + } + start(null); + }; + let formatMessages2 = ({ callName, refs, messages, options, callback }) => { + if (!options) + throw new Error(`Missing second argument in ${callName}() call`); + let keys = {}; + let kind = getFlag(options, keys, "kind", mustBeString); + let color = getFlag(options, keys, "color", mustBeBoolean); + let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (kind === void 0) + throw new Error(`Missing "kind" in ${callName}() call`); + if (kind !== "error" && kind !== "warning") + throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`); + let request = { + command: "format-msgs", + messages: sanitizeMessages(messages, "messages", null, "", terminalWidth), + isWarning: kind === "warning" + }; + if (color !== void 0) + request.color = color; + if (terminalWidth !== void 0) + request.terminalWidth = terminalWidth; + sendRequest(refs, request, (error, response) => { + if (error) + return callback(new Error(error), null); + callback(null, response.messages); + }); + }; + let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => { + if (options === void 0) + options = {}; + let keys = {}; + let color = getFlag(options, keys, "color", mustBeBoolean); + let verbose = getFlag(options, keys, "verbose", mustBeBoolean); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + let request = { + command: "analyze-metafile", + metafile + }; + if (color !== void 0) + request.color = color; + if (verbose !== void 0) + request.verbose = verbose; + sendRequest(refs, request, (error, response) => { + if (error) + return callback(new Error(error), null); + callback(null, response.result); + }); + }; + return { + readFromStdout, + afterClose, + service: { + buildOrContext, + transform: transform2, + formatMessages: formatMessages2, + analyzeMetafile: analyzeMetafile2 + } + }; +} +function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) { + const details = createObjectStash(); + const isContext = callName === "context"; + const handleError = (e, pluginName) => { + const flags = []; + try { + pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault); + } catch { + } + const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName); + sendRequest(refs, { command: "error", flags, error: message }, () => { + message.detail = details.load(message.detail); + callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null); + }); + }; + let plugins; + if (typeof options === "object") { + const value = options.plugins; + if (value !== void 0) { + if (!Array.isArray(value)) + return handleError(new Error(`"plugins" must be an array`), ""); + plugins = value; + } + } + if (plugins && plugins.length > 0) { + if (streamIn.isSync) + return handleError(new Error("Cannot use plugins in synchronous API calls"), ""); + handlePlugins( + buildKey, + sendRequest, + sendResponse, + refs, + streamIn, + requestCallbacks, + options, + plugins, + details + ).then( + (result) => { + if (!result.ok) + return handleError(result.error, result.pluginName); + try { + buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks); + } catch (e) { + handleError(e, ""); + } + }, + (e) => handleError(e, "") + ); + return; + } + try { + buildOrContextContinue(null, (result, done) => done([], []), () => { + }); + } catch (e) { + handleError(e, ""); + } + function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) { + const writeDefault = streamIn.hasFS; + const { + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir, + nodePaths, + mangleCache + } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault); + if (write && !streamIn.hasFS) + throw new Error(`The "write" option is unavailable in this environment`); + const request = { + command: "build", + key: buildKey, + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir: absWorkingDir || defaultWD2, + nodePaths, + context: isContext + }; + if (requestPlugins) + request.plugins = requestPlugins; + if (mangleCache) + request.mangleCache = mangleCache; + const buildResponseToResult = (response, callback2) => { + const result = { + errors: replaceDetailsInMessages(response.errors, details), + warnings: replaceDetailsInMessages(response.warnings, details), + outputFiles: void 0, + metafile: void 0, + mangleCache: void 0 + }; + const originalErrors = result.errors.slice(); + const originalWarnings = result.warnings.slice(); + if (response.outputFiles) + result.outputFiles = response.outputFiles.map(convertOutputFiles); + if (response.metafile) + result.metafile = JSON.parse(response.metafile); + if (response.mangleCache) + result.mangleCache = response.mangleCache; + if (response.writeToStdout !== void 0) + console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); + runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { + if (originalErrors.length > 0 || onEndErrors.length > 0) { + const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)); + return callback2(error, null, onEndErrors, onEndWarnings); + } + callback2(null, result, onEndErrors, onEndWarnings); + }); + }; + let latestResultPromise; + let provideLatestResult; + if (isContext) + requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => { + buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => { + const response = { + errors: onEndErrors, + warnings: onEndWarnings + }; + if (provideLatestResult) + provideLatestResult(err, result); + latestResultPromise = void 0; + provideLatestResult = void 0; + sendResponse(id, response); + resolve(); + }); + }); + sendRequest(refs, request, (error, response) => { + if (error) + return callback(new Error(error), null); + if (!isContext) { + return buildResponseToResult(response, (err, res) => { + scheduleOnDisposeCallbacks(); + return callback(err, res); + }); + } + if (response.errors.length > 0) { + return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null); + } + let didDispose = false; + const result = { + rebuild: () => { + if (!latestResultPromise) + latestResultPromise = new Promise((resolve, reject) => { + let settlePromise; + provideLatestResult = (err, result2) => { + if (!settlePromise) + settlePromise = () => err ? reject(err) : resolve(result2); + }; + const triggerAnotherBuild = () => { + const request2 = { + command: "rebuild", + key: buildKey + }; + sendRequest(refs, request2, (error2, response2) => { + if (error2) { + reject(new Error(error2)); + } else if (settlePromise) { + settlePromise(); + } else { + triggerAnotherBuild(); + } + }); + }; + triggerAnotherBuild(); + }); + return latestResultPromise; + }, + watch: (options2 = {}) => new Promise((resolve, reject) => { + if (!streamIn.hasFS) + throw new Error(`Cannot use the "watch" API in this environment`); + const keys = {}; + checkForInvalidFlags(options2, keys, `in watch() call`); + const request2 = { + command: "watch", + key: buildKey + }; + sendRequest(refs, request2, (error2) => { + if (error2) + reject(new Error(error2)); + else + resolve(void 0); + }); + }), + serve: (options2 = {}) => new Promise((resolve, reject) => { + if (!streamIn.hasFS) + throw new Error(`Cannot use the "serve" API in this environment`); + const keys = {}; + const port = getFlag(options2, keys, "port", mustBeInteger); + const host = getFlag(options2, keys, "host", mustBeString); + const servedir = getFlag(options2, keys, "servedir", mustBeString); + const keyfile = getFlag(options2, keys, "keyfile", mustBeString); + const certfile = getFlag(options2, keys, "certfile", mustBeString); + const fallback = getFlag(options2, keys, "fallback", mustBeString); + const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction); + checkForInvalidFlags(options2, keys, `in serve() call`); + const request2 = { + command: "serve", + key: buildKey, + onRequest: !!onRequest + }; + if (port !== void 0) + request2.port = port; + if (host !== void 0) + request2.host = host; + if (servedir !== void 0) + request2.servedir = servedir; + if (keyfile !== void 0) + request2.keyfile = keyfile; + if (certfile !== void 0) + request2.certfile = certfile; + if (fallback !== void 0) + request2.fallback = fallback; + sendRequest(refs, request2, (error2, response2) => { + if (error2) + return reject(new Error(error2)); + if (onRequest) { + requestCallbacks["serve-request"] = (id, request3) => { + onRequest(request3.args); + sendResponse(id, {}); + }; + } + resolve(response2); + }); + }), + cancel: () => new Promise((resolve) => { + if (didDispose) + return resolve(); + const request2 = { + command: "cancel", + key: buildKey + }; + sendRequest(refs, request2, () => { + resolve(); + }); + }), + dispose: () => new Promise((resolve) => { + if (didDispose) + return resolve(); + didDispose = true; + const request2 = { + command: "dispose", + key: buildKey + }; + sendRequest(refs, request2, () => { + resolve(); + scheduleOnDisposeCallbacks(); + refs.unref(); + }); + }) + }; + refs.ref(); + callback(null, result); + }); + } +} +var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => { + let onStartCallbacks = []; + let onEndCallbacks = []; + let onResolveCallbacks = {}; + let onLoadCallbacks = {}; + let onDisposeCallbacks = []; + let nextCallbackID = 0; + let i = 0; + let requestPlugins = []; + let isSetupDone = false; + plugins = [...plugins]; + for (let item of plugins) { + let keys = {}; + if (typeof item !== "object") + throw new Error(`Plugin at index ${i} must be an object`); + const name = getFlag(item, keys, "name", mustBeString); + if (typeof name !== "string" || name === "") + throw new Error(`Plugin at index ${i} is missing a name`); + try { + let setup = getFlag(item, keys, "setup", mustBeFunction); + if (typeof setup !== "function") + throw new Error(`Plugin is missing a setup function`); + checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`); + let plugin = { + name, + onStart: false, + onEnd: false, + onResolve: [], + onLoad: [] + }; + i++; + let resolve = (path3, options = {}) => { + if (!isSetupDone) + throw new Error('Cannot call "resolve" before plugin setup has completed'); + if (typeof path3 !== "string") + throw new Error(`The path to resolve must be a string`); + let keys2 = /* @__PURE__ */ Object.create(null); + let pluginName = getFlag(options, keys2, "pluginName", mustBeString); + let importer = getFlag(options, keys2, "importer", mustBeString); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString); + let kind = getFlag(options, keys2, "kind", mustBeString); + let pluginData = getFlag(options, keys2, "pluginData", canBeAnything); + checkForInvalidFlags(options, keys2, "in resolve() call"); + return new Promise((resolve2, reject) => { + const request = { + command: "resolve", + path: path3, + key: buildKey, + pluginName: name + }; + if (pluginName != null) + request.pluginName = pluginName; + if (importer != null) + request.importer = importer; + if (namespace != null) + request.namespace = namespace; + if (resolveDir != null) + request.resolveDir = resolveDir; + if (kind != null) + request.kind = kind; + else + throw new Error(`Must specify "kind" when calling "resolve"`); + if (pluginData != null) + request.pluginData = details.store(pluginData); + sendRequest(refs, request, (error, response) => { + if (error !== null) + reject(new Error(error)); + else + resolve2({ + errors: replaceDetailsInMessages(response.errors, details), + warnings: replaceDetailsInMessages(response.warnings, details), + path: response.path, + external: response.external, + sideEffects: response.sideEffects, + namespace: response.namespace, + suffix: response.suffix, + pluginData: details.load(response.pluginData) + }); + }); + }); + }; + let promise = setup({ + initialOptions, + resolve, + onStart(callback) { + let registeredText = `This error came from the "onStart" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart"); + onStartCallbacks.push({ name, callback, note: registeredNote }); + plugin.onStart = true; + }, + onEnd(callback) { + let registeredText = `This error came from the "onEnd" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd"); + onEndCallbacks.push({ name, callback, note: registeredNote }); + plugin.onEnd = true; + }, + onResolve(options, callback) { + let registeredText = `This error came from the "onResolve" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); + let keys2 = {}; + let filter = getFlag(options, keys2, "filter", mustBeRegExp); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`); + if (filter == null) + throw new Error(`onResolve() call is missing a filter`); + let id = nextCallbackID++; + onResolveCallbacks[id] = { name, callback, note: registeredNote }; + plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" }); + }, + onLoad(options, callback) { + let registeredText = `This error came from the "onLoad" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); + let keys2 = {}; + let filter = getFlag(options, keys2, "filter", mustBeRegExp); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`); + if (filter == null) + throw new Error(`onLoad() call is missing a filter`); + let id = nextCallbackID++; + onLoadCallbacks[id] = { name, callback, note: registeredNote }; + plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" }); + }, + onDispose(callback) { + onDisposeCallbacks.push(callback); + }, + esbuild: streamIn.esbuild + }); + if (promise) + await promise; + requestPlugins.push(plugin); + } catch (e) { + return { ok: false, error: e, pluginName: name }; + } + } + requestCallbacks["on-start"] = async (id, request) => { + let response = { errors: [], warnings: [] }; + await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => { + try { + let result = await callback(); + if (result != null) { + if (typeof result !== "object") + throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`); + if (errors != null) + response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0)); + if (warnings != null) + response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0)); + } + } catch (e) { + response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name)); + } + })); + sendResponse(id, response); + }; + requestCallbacks["on-resolve"] = async (id, request) => { + let response = {}, name = "", callback, note; + for (let id2 of request.ids) { + try { + ({ name, callback, note } = onResolveCallbacks[id2]); + let result = await callback({ + path: request.path, + importer: request.importer, + namespace: request.namespace, + resolveDir: request.resolveDir, + kind: request.kind, + pluginData: details.load(request.pluginData) + }); + if (result != null) { + if (typeof result !== "object") + throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let pluginName = getFlag(result, keys, "pluginName", mustBeString); + let path3 = getFlag(result, keys, "path", mustBeString); + let namespace = getFlag(result, keys, "namespace", mustBeString); + let suffix = getFlag(result, keys, "suffix", mustBeString); + let external = getFlag(result, keys, "external", mustBeBoolean); + let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean); + let pluginData = getFlag(result, keys, "pluginData", canBeAnything); + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); + let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); + checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`); + response.id = id2; + if (pluginName != null) + response.pluginName = pluginName; + if (path3 != null) + response.path = path3; + if (namespace != null) + response.namespace = namespace; + if (suffix != null) + response.suffix = suffix; + if (external != null) + response.external = external; + if (sideEffects != null) + response.sideEffects = sideEffects; + if (pluginData != null) + response.pluginData = details.store(pluginData); + if (errors != null) + response.errors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) + response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + if (watchFiles != null) + response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); + if (watchDirs != null) + response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); + break; + } + } catch (e) { + response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; + break; + } + } + sendResponse(id, response); + }; + requestCallbacks["on-load"] = async (id, request) => { + let response = {}, name = "", callback, note; + for (let id2 of request.ids) { + try { + ({ name, callback, note } = onLoadCallbacks[id2]); + let result = await callback({ + path: request.path, + namespace: request.namespace, + suffix: request.suffix, + pluginData: details.load(request.pluginData), + with: request.with + }); + if (result != null) { + if (typeof result !== "object") + throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let pluginName = getFlag(result, keys, "pluginName", mustBeString); + let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); + let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); + let pluginData = getFlag(result, keys, "pluginData", canBeAnything); + let loader = getFlag(result, keys, "loader", mustBeString); + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); + let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); + checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`); + response.id = id2; + if (pluginName != null) + response.pluginName = pluginName; + if (contents instanceof Uint8Array) + response.contents = contents; + else if (contents != null) + response.contents = encodeUTF8(contents); + if (resolveDir != null) + response.resolveDir = resolveDir; + if (pluginData != null) + response.pluginData = details.store(pluginData); + if (loader != null) + response.loader = loader; + if (errors != null) + response.errors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) + response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + if (watchFiles != null) + response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); + if (watchDirs != null) + response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); + break; + } + } catch (e) { + response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; + break; + } + } + sendResponse(id, response); + }; + let runOnEndCallbacks = (result, done) => done([], []); + if (onEndCallbacks.length > 0) { + runOnEndCallbacks = (result, done) => { + (async () => { + const onEndErrors = []; + const onEndWarnings = []; + for (const { name, callback, note } of onEndCallbacks) { + let newErrors; + let newWarnings; + try { + const value = await callback(result); + if (value != null) { + if (typeof value !== "object") + throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let errors = getFlag(value, keys, "errors", mustBeArray); + let warnings = getFlag(value, keys, "warnings", mustBeArray); + checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`); + if (errors != null) + newErrors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) + newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + } + } catch (e) { + newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)]; + } + if (newErrors) { + onEndErrors.push(...newErrors); + try { + result.errors.push(...newErrors); + } catch { + } + } + if (newWarnings) { + onEndWarnings.push(...newWarnings); + try { + result.warnings.push(...newWarnings); + } catch { + } + } + } + done(onEndErrors, onEndWarnings); + })(); + }; + } + let scheduleOnDisposeCallbacks = () => { + for (const cb of onDisposeCallbacks) { + setTimeout(() => cb(), 0); + } + }; + isSetupDone = true; + return { + ok: true, + requestPlugins, + runOnEndCallbacks, + scheduleOnDisposeCallbacks + }; +}; +function createObjectStash() { + const map = /* @__PURE__ */ new Map(); + let nextID = 0; + return { + load(id) { + return map.get(id); + }, + store(value) { + if (value === void 0) + return -1; + const id = nextID++; + map.set(id, value); + return id; + } + }; +} +function extractCallerV8(e, streamIn, ident) { + let note; + let tried = false; + return () => { + if (tried) + return note; + tried = true; + try { + let lines = (e.stack + "").split("\n"); + lines.splice(1, 1); + let location = parseStackLinesV8(streamIn, lines, ident); + if (location) { + note = { text: e.message, location }; + return note; + } + } catch { + } + }; +} +function extractErrorMessageV8(e, streamIn, stash, note, pluginName) { + let text = "Internal error"; + let location = null; + try { + text = (e && e.message || e) + ""; + } catch { + } + try { + location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), ""); + } catch { + } + return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 }; +} +function parseStackLinesV8(streamIn, lines, ident) { + let at = " at "; + if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { + for (let i = 1; i < lines.length; i++) { + let line = lines[i]; + if (!line.startsWith(at)) + continue; + line = line.slice(at.length); + while (true) { + let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); + if (match) { + line = match[1]; + continue; + } + match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); + if (match) { + line = match[1]; + continue; + } + match = /^(\S+):(\d+):(\d+)$/.exec(line); + if (match) { + let contents; + try { + contents = streamIn.readFileSync(match[1], "utf8"); + } catch { + break; + } + let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || ""; + let column = +match[3] - 1; + let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; + return { + file: match[1], + namespace: "file", + line: +match[2], + column: encodeUTF8(lineText.slice(0, column)).length, + length: encodeUTF8(lineText.slice(column, column + length)).length, + lineText: lineText + "\n" + lines.slice(1).join("\n"), + suggestion: "" + }; + } + break; + } + } + } + return null; +} +function failureErrorWithLog(text, errors, warnings) { + let limit = 5; + text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => { + if (i === limit) + return "\n..."; + if (!e.location) + return ` +error: ${e.text}`; + let { file, line, column } = e.location; + let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : ""; + return ` +${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`; + }).join(""); + let error = new Error(text); + for (const [key, value] of [["errors", errors], ["warnings", warnings]]) { + Object.defineProperty(error, key, { + configurable: true, + enumerable: true, + get: () => value, + set: (value2) => Object.defineProperty(error, key, { + configurable: true, + enumerable: true, + value: value2 + }) + }); + } + return error; +} +function replaceDetailsInMessages(messages, stash) { + for (const message of messages) { + message.detail = stash.load(message.detail); + } + return messages; +} +function sanitizeLocation(location, where, terminalWidth) { + if (location == null) + return null; + let keys = {}; + let file = getFlag(location, keys, "file", mustBeString); + let namespace = getFlag(location, keys, "namespace", mustBeString); + let line = getFlag(location, keys, "line", mustBeInteger); + let column = getFlag(location, keys, "column", mustBeInteger); + let length = getFlag(location, keys, "length", mustBeInteger); + let lineText = getFlag(location, keys, "lineText", mustBeString); + let suggestion = getFlag(location, keys, "suggestion", mustBeString); + checkForInvalidFlags(location, keys, where); + if (lineText) { + const relevantASCII = lineText.slice( + 0, + (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80) + ); + if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { + lineText = relevantASCII; + } + } + return { + file: file || "", + namespace: namespace || "", + line: line || 0, + column: column || 0, + length: length || 0, + lineText: lineText || "", + suggestion: suggestion || "" + }; +} +function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) { + let messagesClone = []; + let index = 0; + for (const message of messages) { + let keys = {}; + let id = getFlag(message, keys, "id", mustBeString); + let pluginName = getFlag(message, keys, "pluginName", mustBeString); + let text = getFlag(message, keys, "text", mustBeString); + let location = getFlag(message, keys, "location", mustBeObjectOrNull); + let notes = getFlag(message, keys, "notes", mustBeArray); + let detail = getFlag(message, keys, "detail", canBeAnything); + let where = `in element ${index} of "${property}"`; + checkForInvalidFlags(message, keys, where); + let notesClone = []; + if (notes) { + for (const note of notes) { + let noteKeys = {}; + let noteText = getFlag(note, noteKeys, "text", mustBeString); + let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); + checkForInvalidFlags(note, noteKeys, where); + notesClone.push({ + text: noteText || "", + location: sanitizeLocation(noteLocation, where, terminalWidth) + }); + } + } + messagesClone.push({ + id: id || "", + pluginName: pluginName || fallbackPluginName, + text: text || "", + location: sanitizeLocation(location, where, terminalWidth), + notes: notesClone, + detail: stash ? stash.store(detail) : -1 + }); + index++; + } + return messagesClone; +} +function sanitizeStringArray(values, property) { + const result = []; + for (const value of values) { + if (typeof value !== "string") + throw new Error(`${quote(property)} must be an array of strings`); + result.push(value); + } + return result; +} +function convertOutputFiles({ path: path3, contents, hash }) { + let text = null; + return { + path: path3, + contents, + hash, + get text() { + const binary = this.contents; + if (text === null || binary !== contents) { + contents = binary; + text = decodeUTF8(binary); + } + return text; + } + }; +} + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var packageDarwin_arm64 = "@esbuild/darwin-arm64"; +var packageDarwin_x64 = "@esbuild/darwin-x64"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM }; +} +function pkgForSomeOtherPlatform() { + const libMainJS = require.resolve("esbuild"); + const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); + if (path.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownUnixlikePackages) { + try { + const pkg = knownUnixlikePackages[unixKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) + return pkg; + } catch { + } + } + for (const windowsKey in knownWindowsPackages) { + try { + const pkg = knownWindowsPackages[windowsKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) + return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} +function generateBinPath() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; + } + } + const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); + let binPath; + try { + binPath = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath = downloadedBinPath(pkg, subpath); + if (!fs.existsSync(binPath)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + let suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild on Windows or macOS and copying "node_modules" +into a Docker image that runs Linux, or by copying "node_modules" between +Windows and WSL environments. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead of npm which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { + suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild with npm running inside of Rosetta 2 and then +trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta +2 is Apple's on-the-fly x86_64-to-arm64 translation service). + +If you are installing with npm, you can try ensuring that both npm and node are +not running under Rosetta 2 and then reinstalling esbuild. This likely involves +changing how you installed npm and/or node. For example, installing node with +the universal installer here should work: https://nodejs.org/en/download/. Or +you could consider using yarn instead of npm which has built-in support for +installing a package on multiple platforms simultaneously. + +If you are installing with yarn, you can try listing both "arm64" and "x64" +in your ".yarnrc.yml" file using the "supportedArchitectures" feature: +https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + } + throw new Error(` +You installed esbuild for another platform than the one you're currently using. +This won't work because esbuild is written with native code and needs to +install a platform-specific binary executable. +${suggestions} +Another alternative is to use the "esbuild-wasm" package instead, which works +the same way on all platforms. But it comes with a heavy performance cost and +can sometimes be 10x slower than the "esbuild" package, so you may also not +want to do that. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. + +If you are installing esbuild with npm, make sure that you don't specify the +"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature +of "package.json" is used by esbuild to install the correct binary executable +for your current platform.`); + } + throw e; + } + } + if (/\.zip\//.test(binPath)) { + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = path.join( + root, + "node_modules", + ".cache", + "esbuild", + `pnpapi-${pkg.replace("/", "-")}-${"0.19.12"}-${path.basename(subpath)}` + ); + if (!fs.existsSync(binTargetPath)) { + fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); + fs.copyFileSync(binPath, binTargetPath); + fs.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath, isWASM }; + } + } + return { binPath, isWASM }; +} + +// lib/npm/node.ts +var child_process = require("child_process"); +var crypto = require("crypto"); +var path2 = require("path"); +var fs2 = require("fs"); +var os2 = require("os"); +var tty = require("tty"); +var worker_threads; +if (process.env.ESBUILD_WORKER_THREADS !== "0") { + try { + worker_threads = require("worker_threads"); + } catch { + } + let [major, minor] = process.versions.node.split("."); + if ( + // { + if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) { + throw new Error( + `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle. + +More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.` + ); + } + if (false) { + return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]]; + } else { + const { binPath, isWASM } = generateBinPath(); + if (isWASM) { + return ["node", [binPath]]; + } else { + return [binPath, []]; + } + } +}; +var isTTY = () => tty.isatty(2); +var fsSync = { + readFile(tempFile, callback) { + try { + let contents = fs2.readFileSync(tempFile, "utf8"); + try { + fs2.unlinkSync(tempFile); + } catch { + } + callback(null, contents); + } catch (err) { + callback(err, null); + } + }, + writeFile(contents, callback) { + try { + let tempFile = randomFileName(); + fs2.writeFileSync(tempFile, contents); + callback(tempFile); + } catch { + callback(null); + } + } +}; +var fsAsync = { + readFile(tempFile, callback) { + try { + fs2.readFile(tempFile, "utf8", (err, contents) => { + try { + fs2.unlink(tempFile, () => callback(err, contents)); + } catch { + callback(err, contents); + } + }); + } catch (err) { + callback(err, null); + } + }, + writeFile(contents, callback) { + try { + let tempFile = randomFileName(); + fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile)); + } catch { + callback(null); + } + } +}; +var version = "0.19.12"; +var build = (options) => ensureServiceIsRunning().build(options); +var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions); +var transform = (input, options) => ensureServiceIsRunning().transform(input, options); +var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options); +var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options); +var buildSync = (options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) + workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.buildSync(options); + } + let result; + runServiceSync((service) => service.buildOrContext({ + callName: "buildSync", + refs: null, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => { + if (err) + throw err; + result = res; + } + })); + return result; +}; +var transformSync = (input, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) + workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.transformSync(input, options); + } + let result; + runServiceSync((service) => service.transform({ + callName: "transformSync", + refs: null, + input, + options: options || {}, + isTTY: isTTY(), + fs: fsSync, + callback: (err, res) => { + if (err) + throw err; + result = res; + } + })); + return result; +}; +var formatMessagesSync = (messages, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) + workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.formatMessagesSync(messages, options); + } + let result; + runServiceSync((service) => service.formatMessages({ + callName: "formatMessagesSync", + refs: null, + messages, + options, + callback: (err, res) => { + if (err) + throw err; + result = res; + } + })); + return result; +}; +var analyzeMetafileSync = (metafile, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) + workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.analyzeMetafileSync(metafile, options); + } + let result; + runServiceSync((service) => service.analyzeMetafile({ + callName: "analyzeMetafileSync", + refs: null, + metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), + options, + callback: (err, res) => { + if (err) + throw err; + result = res; + } + })); + return result; +}; +var stop = () => { + if (stopService) + stopService(); + if (workerThreadService) + workerThreadService.stop(); +}; +var initializeWasCalled = false; +var initialize = (options) => { + options = validateInitializeOptions(options || {}); + if (options.wasmURL) + throw new Error(`The "wasmURL" option only works in the browser`); + if (options.wasmModule) + throw new Error(`The "wasmModule" option only works in the browser`); + if (options.worker) + throw new Error(`The "worker" option only works in the browser`); + if (initializeWasCalled) + throw new Error('Cannot call "initialize" more than once'); + ensureServiceIsRunning(); + initializeWasCalled = true; + return Promise.resolve(); +}; +var defaultWD = process.cwd(); +var longLivedService; +var stopService; +var ensureServiceIsRunning = () => { + if (longLivedService) + return longLivedService; + let [command, args] = esbuildCommandAndArgs(); + let child = child_process.spawn(command, args.concat(`--service=${"0.19.12"}`, "--ping"), { + windowsHide: true, + stdio: ["pipe", "pipe", "inherit"], + cwd: defaultWD + }); + let { readFromStdout, afterClose, service } = createChannel({ + writeToStdin(bytes) { + child.stdin.write(bytes, (err) => { + if (err) + afterClose(err); + }); + }, + readFileSync: fs2.readFileSync, + isSync: false, + hasFS: true, + esbuild: node_exports + }); + child.stdin.on("error", afterClose); + child.on("error", afterClose); + const stdin = child.stdin; + const stdout = child.stdout; + stdout.on("data", readFromStdout); + stdout.on("end", afterClose); + stopService = () => { + stdin.destroy(); + stdout.destroy(); + child.kill(); + initializeWasCalled = false; + longLivedService = void 0; + stopService = void 0; + }; + let refCount = 0; + child.unref(); + if (stdin.unref) { + stdin.unref(); + } + if (stdout.unref) { + stdout.unref(); + } + const refs = { + ref() { + if (++refCount === 1) + child.ref(); + }, + unref() { + if (--refCount === 0) + child.unref(); + } + }; + longLivedService = { + build: (options) => new Promise((resolve, reject) => { + service.buildOrContext({ + callName: "build", + refs, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => err ? reject(err) : resolve(res) + }); + }), + context: (options) => new Promise((resolve, reject) => service.buildOrContext({ + callName: "context", + refs, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + transform: (input, options) => new Promise((resolve, reject) => service.transform({ + callName: "transform", + refs, + input, + options: options || {}, + isTTY: isTTY(), + fs: fsAsync, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({ + callName: "formatMessages", + refs, + messages, + options, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({ + callName: "analyzeMetafile", + refs, + metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), + options, + callback: (err, res) => err ? reject(err) : resolve(res) + })) + }; + return longLivedService; +}; +var runServiceSync = (callback) => { + let [command, args] = esbuildCommandAndArgs(); + let stdin = new Uint8Array(); + let { readFromStdout, afterClose, service } = createChannel({ + writeToStdin(bytes) { + if (stdin.length !== 0) + throw new Error("Must run at most one command"); + stdin = bytes; + }, + isSync: true, + hasFS: true, + esbuild: node_exports + }); + callback(service); + let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.19.12"}`), { + cwd: defaultWD, + windowsHide: true, + input: stdin, + // We don't know how large the output could be. If it's too large, the + // command will fail with ENOBUFS. Reserve 16mb for now since that feels + // like it should be enough. Also allow overriding this with an environment + // variable. + maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 + }); + readFromStdout(stdout); + afterClose(null); +}; +var randomFileName = () => { + return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`); +}; +var workerThreadService = null; +var startWorkerThreadService = (worker_threads2) => { + let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel(); + let worker = new worker_threads2.Worker(__filename, { + workerData: { workerPort, defaultWD, esbuildVersion: "0.19.12" }, + transferList: [workerPort], + // From node's documentation: https://nodejs.org/api/worker_threads.html + // + // Take care when launching worker threads from preload scripts (scripts loaded + // and run using the `-r` command line flag). Unless the `execArgv` option is + // explicitly set, new Worker threads automatically inherit the command line flags + // from the running process and will preload the same preload scripts as the main + // thread. If the preload script unconditionally launches a worker thread, every + // thread spawned will spawn another until the application crashes. + // + execArgv: [] + }); + let nextID = 0; + let fakeBuildError = (text) => { + let error = new Error(`Build failed with 1 error: +error: ${text}`); + let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }]; + error.errors = errors; + error.warnings = []; + return error; + }; + let validateBuildSyncOptions = (options) => { + if (!options) + return; + let plugins = options.plugins; + if (plugins && plugins.length > 0) + throw fakeBuildError(`Cannot use plugins in synchronous API calls`); + }; + let applyProperties = (object, properties) => { + for (let key in properties) { + object[key] = properties[key]; + } + }; + let runCallSync = (command, args) => { + let id = nextID++; + let sharedBuffer = new SharedArrayBuffer(8); + let sharedBufferView = new Int32Array(sharedBuffer); + let msg = { sharedBuffer, id, command, args }; + worker.postMessage(msg); + let status = Atomics.wait(sharedBufferView, 0, 0); + if (status !== "ok" && status !== "not-equal") + throw new Error("Internal error: Atomics.wait() failed: " + status); + let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort); + if (id !== id2) + throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); + if (reject) { + applyProperties(reject, properties); + throw reject; + } + return resolve; + }; + worker.unref(); + return { + buildSync(options) { + validateBuildSyncOptions(options); + return runCallSync("build", [options]); + }, + transformSync(input, options) { + return runCallSync("transform", [input, options]); + }, + formatMessagesSync(messages, options) { + return runCallSync("formatMessages", [messages, options]); + }, + analyzeMetafileSync(metafile, options) { + return runCallSync("analyzeMetafile", [metafile, options]); + }, + stop() { + worker.terminate(); + workerThreadService = null; + } + }; +}; +var startSyncServiceWorker = () => { + let workerPort = worker_threads.workerData.workerPort; + let parentPort = worker_threads.parentPort; + let extractProperties = (object) => { + let properties = {}; + if (object && typeof object === "object") { + for (let key in object) { + properties[key] = object[key]; + } + } + return properties; + }; + try { + let service = ensureServiceIsRunning(); + defaultWD = worker_threads.workerData.defaultWD; + parentPort.on("message", (msg) => { + (async () => { + let { sharedBuffer, id, command, args } = msg; + let sharedBufferView = new Int32Array(sharedBuffer); + try { + switch (command) { + case "build": + workerPort.postMessage({ id, resolve: await service.build(args[0]) }); + break; + case "transform": + workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) }); + break; + case "formatMessages": + workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) }); + break; + case "analyzeMetafile": + workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) }); + break; + default: + throw new Error(`Invalid command: ${command}`); + } + } catch (reject) { + workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); + } + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); + })(); + }); + } catch (reject) { + parentPort.on("message", (msg) => { + let { sharedBuffer, id } = msg; + let sharedBufferView = new Int32Array(sharedBuffer); + workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); + }); + } +}; +if (isInternalWorkerThread) { + startSyncServiceWorker(); +} +var node_default = node_exports; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + analyzeMetafile, + analyzeMetafileSync, + build, + buildSync, + context, + formatMessages, + formatMessagesSync, + initialize, + stop, + transform, + transformSync, + version +}); diff --git a/web/node_modules/esbuild/package.json b/web/node_modules/esbuild/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6ffc368b440d3150a93fc30c7c9c43c9031bcf55 --- /dev/null +++ b/web/node_modules/esbuild/package.json @@ -0,0 +1,43 @@ +{ + "name": "esbuild", + "version": "0.19.12", + "description": "An extremely fast JavaScript and CSS bundler and minifier.", + "repository": "https://github.com/evanw/esbuild", + "scripts": { + "postinstall": "node install.js" + }, + "main": "lib/main.js", + "types": "lib/main.d.ts", + "engines": { + "node": ">=12" + }, + "bin": { + "esbuild": "bin/esbuild" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.19.12", + "@esbuild/android-arm": "0.19.12", + "@esbuild/android-arm64": "0.19.12", + "@esbuild/android-x64": "0.19.12", + "@esbuild/darwin-arm64": "0.19.12", + "@esbuild/darwin-x64": "0.19.12", + "@esbuild/freebsd-arm64": "0.19.12", + "@esbuild/freebsd-x64": "0.19.12", + "@esbuild/linux-arm": "0.19.12", + "@esbuild/linux-arm64": "0.19.12", + "@esbuild/linux-ia32": "0.19.12", + "@esbuild/linux-loong64": "0.19.12", + "@esbuild/linux-mips64el": "0.19.12", + "@esbuild/linux-ppc64": "0.19.12", + "@esbuild/linux-riscv64": "0.19.12", + "@esbuild/linux-s390x": "0.19.12", + "@esbuild/linux-x64": "0.19.12", + "@esbuild/netbsd-x64": "0.19.12", + "@esbuild/openbsd-x64": "0.19.12", + "@esbuild/sunos-x64": "0.19.12", + "@esbuild/win32-arm64": "0.19.12", + "@esbuild/win32-ia32": "0.19.12", + "@esbuild/win32-x64": "0.19.12" + }, + "license": "MIT" +} diff --git a/web/node_modules/estree-walker/LICENSE b/web/node_modules/estree-walker/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..63b62098eea9e1031659a145b1c6d752486ec0fe --- /dev/null +++ b/web/node_modules/estree-walker/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/web/node_modules/estree-walker/README.md b/web/node_modules/estree-walker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d739d1bf1811736d657775bdfdd261801bc92809 --- /dev/null +++ b/web/node_modules/estree-walker/README.md @@ -0,0 +1,48 @@ +# estree-walker + +Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn). + + +## Installation + +```bash +npm i estree-walker +``` + + +## Usage + +```js +var walk = require('estree-walker').walk; +var acorn = require('acorn'); + +ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn + +walk(ast, { + enter(node, parent, prop, index) { + // some code happens + }, + leave(node, parent, prop, index) { + // some code happens + } +}); +``` + +Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called. + +Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one. + +Call `this.remove()` in either `enter` or `leave` to remove the current node. + +## Why not use estraverse? + +The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys. + +estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.) + +None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful. + + +## License + +MIT diff --git a/web/node_modules/estree-walker/package.json b/web/node_modules/estree-walker/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c9f54edd9f394c267429a4b1393d67df42fbbe45 --- /dev/null +++ b/web/node_modules/estree-walker/package.json @@ -0,0 +1,38 @@ +{ + "name": "estree-walker", + "description": "Traverse an ESTree-compliant AST", + "version": "3.0.3", + "private": false, + "author": "Rich Harris", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/estree-walker" + }, + "type": "module", + "module": "./src/index.js", + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./types/index.d.ts", + "import": "./src/index.js" + } + }, + "types": "types/index.d.ts", + "scripts": { + "prepublishOnly": "tsc && npm test", + "test": "uvu test" + }, + "dependencies": { + "@types/estree": "^1.0.0" + }, + "devDependencies": { + "typescript": "^4.9.0", + "uvu": "^0.5.1" + }, + "files": [ + "src", + "types", + "README.md" + ] +} diff --git a/web/node_modules/estree-walker/src/async.js b/web/node_modules/estree-walker/src/async.js new file mode 100644 index 0000000000000000000000000000000000000000..f068c713c4cdb2e57a2e98829b75e0541d943b9d --- /dev/null +++ b/web/node_modules/estree-walker/src/async.js @@ -0,0 +1,152 @@ +import { WalkerBase } from './walker.js'; + +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => Promise} AsyncHandler + */ + +export class AsyncWalker extends WalkerBase { + /** + * + * @param {AsyncHandler} [enter] + * @param {AsyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + + /** @type {AsyncHandler | undefined} */ + this.enter = enter; + + /** @type {AsyncHandler | undefined} */ + this.leave = leave; + } + + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Promise} + */ + async visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + await this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + /** @type {keyof Node} */ + let key; + + for (key in node) { + /** @type {unknown} */ + const value = node[key]; + + if (value && typeof value === 'object') { + if (Array.isArray(value)) { + const nodes = /** @type {Array} */ (value); + for (let i = 0; i < nodes.length; i += 1) { + const item = nodes[i]; + if (isNode(item)) { + if (!(await this.visit(item, node, key, i))) { + // removed + i--; + } + } + } + } else if (isNode(value)) { + await this.visit(value, node, key, null); + } + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + await this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +/** + * Ducktype a node. + * + * @param {unknown} value + * @returns {value is Node} + */ +function isNode(value) { + return ( + value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' + ); +} diff --git a/web/node_modules/estree-walker/src/index.js b/web/node_modules/estree-walker/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..933ea4f28ddb57cc53976aa5504d3ef39bbc0586 --- /dev/null +++ b/web/node_modules/estree-walker/src/index.js @@ -0,0 +1,34 @@ +import { SyncWalker } from './sync.js'; +import { AsyncWalker } from './async.js'; + +/** + * @typedef {import('estree').Node} Node + * @typedef {import('./sync.js').SyncHandler} SyncHandler + * @typedef {import('./async.js').AsyncHandler} AsyncHandler + */ + +/** + * @param {Node} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {Node | null} + */ +export function walk(ast, { enter, leave }) { + const instance = new SyncWalker(enter, leave); + return instance.visit(ast, null); +} + +/** + * @param {Node} ast + * @param {{ + * enter?: AsyncHandler + * leave?: AsyncHandler + * }} walker + * @returns {Promise} + */ +export async function asyncWalk(ast, { enter, leave }) { + const instance = new AsyncWalker(enter, leave); + return await instance.visit(ast, null); +} diff --git a/web/node_modules/estree-walker/src/sync.js b/web/node_modules/estree-walker/src/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..171fb360a76998c7b0e10a4544715a1be095c267 --- /dev/null +++ b/web/node_modules/estree-walker/src/sync.js @@ -0,0 +1,152 @@ +import { WalkerBase } from './walker.js'; + +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => void} SyncHandler + */ + +export class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + + /** @type {SyncHandler | undefined} */ + this.enter = enter; + + /** @type {SyncHandler | undefined} */ + this.leave = leave; + } + + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + /** @type {keyof Node} */ + let key; + + for (key in node) { + /** @type {unknown} */ + const value = node[key]; + + if (value && typeof value === 'object') { + if (Array.isArray(value)) { + const nodes = /** @type {Array} */ (value); + for (let i = 0; i < nodes.length; i += 1) { + const item = nodes[i]; + if (isNode(item)) { + if (!this.visit(item, node, key, i)) { + // removed + i--; + } + } + } + } else if (isNode(value)) { + this.visit(value, node, key, null); + } + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +/** + * Ducktype a node. + * + * @param {unknown} value + * @returns {value is Node} + */ +function isNode(value) { + return ( + value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' + ); +} diff --git a/web/node_modules/estree-walker/src/walker.js b/web/node_modules/estree-walker/src/walker.js new file mode 100644 index 0000000000000000000000000000000000000000..6dc6bd7bbe52ee4713bbfc89c25a8e884e1b205f --- /dev/null +++ b/web/node_modules/estree-walker/src/walker.js @@ -0,0 +1,61 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef {{ + * skip: () => void; + * remove: () => void; + * replace: (node: Node) => void; + * }} WalkerContext + */ + +export class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent, prop, index, node) { + if (parent && prop) { + if (index != null) { + /** @type {Array} */ (parent[prop])[index] = node; + } else { + /** @type {Node} */ (parent[prop]) = node; + } + } + } + + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent, prop, index) { + if (parent && prop) { + if (index !== null && index !== undefined) { + /** @type {Array} */ (parent[prop]).splice(index, 1); + } else { + delete parent[prop]; + } + } + } +} diff --git a/web/node_modules/estree-walker/types/async.d.ts b/web/node_modules/estree-walker/types/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db0825aa7bc81d386b07d4897636ad930ebe3bb5 --- /dev/null +++ b/web/node_modules/estree-walker/types/async.d.ts @@ -0,0 +1,36 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => Promise} AsyncHandler + */ +export class AsyncWalker extends WalkerBase { + /** + * + * @param {AsyncHandler} [enter] + * @param {AsyncHandler} [leave] + */ + constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined); + /** @type {AsyncHandler | undefined} */ + enter: AsyncHandler | undefined; + /** @type {AsyncHandler | undefined} */ + leave: AsyncHandler | undefined; + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Promise} + */ + visit(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise; +} +export type Node = import('estree').Node; +export type WalkerContext = import('./walker.js').WalkerContext; +export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise; +import { WalkerBase } from "./walker.js"; diff --git a/web/node_modules/estree-walker/types/index.d.ts b/web/node_modules/estree-walker/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c25afed98bca5bb3bcffd542a532c121d182d4e1 --- /dev/null +++ b/web/node_modules/estree-walker/types/index.d.ts @@ -0,0 +1,32 @@ +/** + * @typedef {import('estree').Node} Node + * @typedef {import('./sync.js').SyncHandler} SyncHandler + * @typedef {import('./async.js').AsyncHandler} AsyncHandler + */ +/** + * @param {Node} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {Node | null} + */ +export function walk(ast: Node, { enter, leave }: { + enter?: SyncHandler; + leave?: SyncHandler; +}): Node | null; +/** + * @param {Node} ast + * @param {{ + * enter?: AsyncHandler + * leave?: AsyncHandler + * }} walker + * @returns {Promise} + */ +export function asyncWalk(ast: Node, { enter, leave }: { + enter?: AsyncHandler; + leave?: AsyncHandler; +}): Promise; +export type Node = import('estree').Node; +export type SyncHandler = import('./sync.js').SyncHandler; +export type AsyncHandler = import('./async.js').AsyncHandler; diff --git a/web/node_modules/estree-walker/types/sync.d.ts b/web/node_modules/estree-walker/types/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3612b7ff424a6a78edb67f8bb1738443fbabf2a7 --- /dev/null +++ b/web/node_modules/estree-walker/types/sync.d.ts @@ -0,0 +1,36 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => void} SyncHandler + */ +export class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined); + /** @type {SyncHandler | undefined} */ + enter: SyncHandler | undefined; + /** @type {SyncHandler | undefined} */ + leave: SyncHandler | undefined; + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null; +} +export type Node = import('estree').Node; +export type WalkerContext = import('./walker.js').WalkerContext; +export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void; +import { WalkerBase } from "./walker.js"; diff --git a/web/node_modules/estree-walker/types/walker.d.ts b/web/node_modules/estree-walker/types/walker.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3fa29c193ab01bccf4c50495230f7c1a091c375 --- /dev/null +++ b/web/node_modules/estree-walker/types/walker.d.ts @@ -0,0 +1,39 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef {{ + * skip: () => void; + * remove: () => void; + * replace: (node: Node) => void; + * }} WalkerContext + */ +export class WalkerBase { + /** @type {boolean} */ + should_skip: boolean; + /** @type {boolean} */ + should_remove: boolean; + /** @type {Node | null} */ + replacement: Node | null; + /** @type {WalkerContext} */ + context: WalkerContext; + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void; + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void; +} +export type Node = import('estree').Node; +export type WalkerContext = { + skip: () => void; + remove: () => void; + replace: (node: Node) => void; +}; diff --git a/web/node_modules/execa/index.d.ts b/web/node_modules/execa/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cef75476507d759706d7aa64107c755773c74e4 --- /dev/null +++ b/web/node_modules/execa/index.d.ts @@ -0,0 +1,955 @@ +import {type Buffer} from 'node:buffer'; +import {type ChildProcess} from 'node:child_process'; +import {type Stream, type Readable as ReadableStream, type Writable as WritableStream} from 'node:stream'; + +export type StdioOption = + | 'pipe' + | 'overlapped' + | 'ipc' + | 'ignore' + | 'inherit' + | Stream + | number + | undefined; + +type EncodingOption = + | 'utf8' + // eslint-disable-next-line unicorn/text-encoding-identifier-case + | 'utf-8' + | 'utf16le' + | 'utf-16le' + | 'ucs2' + | 'ucs-2' + | 'latin1' + | 'binary' + | 'ascii' + | 'hex' + | 'base64' + | 'base64url' + | 'buffer' + | null + | undefined; +type DefaultEncodingOption = 'utf8'; +type BufferEncodingOption = 'buffer' | null; + +export type CommonOptions = { + /** + Kill the spawned process when the parent process exits unless either: + - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached) + - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit + + @default true + */ + readonly cleanup?: boolean; + + /** + Prefer locally installed binaries when looking for a binary to execute. + + If you `$ npm install foo`, you can then `execa('foo')`. + + @default `true` with `$`, `false` otherwise + */ + readonly preferLocal?: boolean; + + /** + Preferred path to find locally installed binaries in (use with `preferLocal`). + + @default process.cwd() + */ + readonly localDir?: string | URL; + + /** + Path to the Node.js executable to use in child processes. + + This can be either an absolute path or a path relative to the `cwd` option. + + Requires `preferLocal` to be `true`. + + For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process. + + @default process.execPath + */ + readonly execPath?: string; + + /** + Buffer the output from the spawned process. When set to `false`, you must read the output of `stdout` and `stderr` (or `all` if the `all` option is `true`). Otherwise the returned promise will not be resolved/rejected. + + If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data. + + @default true + */ + readonly buffer?: boolean; + + /** + Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + + @default `inherit` with `$`, `pipe` otherwise + */ + readonly stdin?: StdioOption; + + /** + Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + + @default 'pipe' + */ + readonly stdout?: StdioOption; + + /** + Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + + @default 'pipe' + */ + readonly stderr?: StdioOption; + + /** + Setting this to `false` resolves the promise with the error instead of rejecting it. + + @default true + */ + readonly reject?: boolean; + + /** + Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved. + + @default false + */ + readonly all?: boolean; + + /** + Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output. + + @default true + */ + readonly stripFinalNewline?: boolean; + + /** + Set to `false` if you don't want to extend the environment variables when providing the `env` property. + + @default true + */ + readonly extendEnv?: boolean; + + /** + Current working directory of the child process. + + @default process.cwd() + */ + readonly cwd?: string | URL; + + /** + Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this. + + @default process.env + */ + readonly env?: NodeJS.ProcessEnv; + + /** + Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified. + */ + readonly argv0?: string; + + /** + Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration. + + @default 'pipe' + */ + readonly stdio?: 'pipe' | 'overlapped' | 'ignore' | 'inherit' | readonly StdioOption[]; + + /** + Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execaNode()`: + - `json`: Uses `JSON.stringify()` and `JSON.parse()`. + - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value) + + [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization) + + @default 'json' + */ + readonly serialization?: 'json' | 'advanced'; + + /** + Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached). + + @default false + */ + readonly detached?: boolean; + + /** + Sets the user identity of the process. + */ + readonly uid?: number; + + /** + Sets the group identity of the process. + */ + readonly gid?: number; + + /** + If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows. + + We recommend against using this option since it is: + - not cross-platform, encouraging shell-specific syntax. + - slower, because of the additional shell interpretation. + - unsafe, potentially allowing command injection. + + @default false + */ + readonly shell?: boolean | string; + + /** + Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `'buffer'` or `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string. + + @default 'utf8' + */ + readonly encoding?: EncodingType; + + /** + If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds. + + @default 0 + */ + readonly timeout?: number; + + /** + Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB. + + @default 100_000_000 + */ + readonly maxBuffer?: number; + + /** + Signal value to be used when the spawned process will be killed. + + @default 'SIGTERM' + */ + readonly killSignal?: string | number; + + /** + You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). + + When `AbortController.abort()` is called, [`.isCanceled`](https://github.com/sindresorhus/execa#iscanceled) becomes `true`. + + @example + ``` + import {execa} from 'execa'; + + const abortController = new AbortController(); + const subprocess = execa('node', [], {signal: abortController.signal}); + + setTimeout(() => { + abortController.abort(); + }, 1000); + + try { + await subprocess; + } catch (error) { + console.log(subprocess.killed); // true + console.log(error.isCanceled); // true + } + ``` + */ + readonly signal?: AbortSignal; + + /** + If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`. + + @default false + */ + readonly windowsVerbatimArguments?: boolean; + + /** + On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows. + + @default true + */ + readonly windowsHide?: boolean; + + /** + Print each command on `stderr` before executing it. + + This can also be enabled by setting the `NODE_DEBUG=execa` environment variable in the current process. + + @default false + */ + readonly verbose?: boolean; +}; + +export type Options = { + /** + Write some input to the `stdin` of your binary. + + If the input is a file, use the `inputFile` option instead. + */ + readonly input?: string | Buffer | ReadableStream; + + /** + Use a file as input to the the `stdin` of your binary. + + If the input is not a file, use the `input` option instead. + */ + readonly inputFile?: string; +} & CommonOptions; + +export type SyncOptions = { + /** + Write some input to the `stdin` of your binary. + + If the input is a file, use the `inputFile` option instead. + */ + readonly input?: string | Buffer; + + /** + Use a file as input to the the `stdin` of your binary. + + If the input is not a file, use the `input` option instead. + */ + readonly inputFile?: string; +} & CommonOptions; + +export type NodeOptions = { + /** + The Node.js executable to use. + + @default process.execPath + */ + readonly nodePath?: string; + + /** + List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable. + + @default process.execArgv + */ + readonly nodeOptions?: string[]; +} & Options; + +type StdoutStderrAll = string | Buffer | undefined; + +export type ExecaReturnBase = { + /** + The file and arguments that were run, for logging purposes. + + This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`. + */ + command: string; + + /** + Same as `command` but escaped. + + This is meant to be copy and pasted into a shell, for debugging purposes. + Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execaCommand()`. + */ + escapedCommand: string; + + /** + The numeric exit code of the process that was run. + */ + exitCode: number; + + /** + The output of the process on stdout. + */ + stdout: StdoutStderrType; + + /** + The output of the process on stderr. + */ + stderr: StdoutStderrType; + + /** + Whether the process failed to run. + */ + failed: boolean; + + /** + Whether the process timed out. + */ + timedOut: boolean; + + /** + Whether the process was killed. + */ + killed: boolean; + + /** + The name of the signal that was used to terminate the process. For example, `SIGFPE`. + + If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. + */ + signal?: string; + + /** + A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`. + + If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen. + */ + signalDescription?: string; + + /** + The `cwd` of the command if provided in the command options. Otherwise it is `process.cwd()`. + */ + cwd: string; +}; + +export type ExecaSyncReturnValue = { +} & ExecaReturnBase; + +/** +Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance. + +The child process fails when: +- its exit code is not `0` +- it was killed with a signal +- timing out +- being canceled +- there's not enough memory or there are already too many child processes +*/ +export type ExecaReturnValue = { + /** + The output of the process with `stdout` and `stderr` interleaved. + + This is `undefined` if either: + - the `all` option is `false` (default value) + - `execaSync()` was used + */ + all?: StdoutStderrType; + + /** + Whether the process was canceled. + + You can cancel the spawned process using the [`signal`](https://github.com/sindresorhus/execa#signal-1) option. + */ + isCanceled: boolean; +} & ExecaSyncReturnValue; + +export type ExecaSyncError = { + /** + Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored. + + The child process stderr then stdout are appended to the end, separated with newlines and not interleaved. + */ + message: string; + + /** + This is the same as the `message` property except it does not include the child process stdout/stderr. + */ + shortMessage: string; + + /** + Original error message. This is the same as the `message` property except it includes neither the child process stdout/stderr nor some additional information added by Execa. + + This is `undefined` unless the child process exited due to an `error` event or a timeout. + */ + originalMessage?: string; +} & Error & ExecaReturnBase; + +export type ExecaError = { + /** + The output of the process with `stdout` and `stderr` interleaved. + + This is `undefined` if either: + - the `all` option is `false` (default value) + - `execaSync()` was used + */ + all?: StdoutStderrType; + + /** + Whether the process was canceled. + */ + isCanceled: boolean; +} & ExecaSyncError; + +export type KillOptions = { + /** + Milliseconds to wait for the child process to terminate before sending `SIGKILL`. + + Can be disabled with `false`. + + @default 5000 + */ + forceKillAfterTimeout?: number | false; +}; + +export type ExecaChildPromise = { + /** + Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr). + + This is `undefined` if either: + - the `all` option is `false` (the default value) + - both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio) + */ + all?: ReadableStream; + + catch( + onRejected?: (reason: ExecaError) => ResultType | PromiseLike + ): Promise | ResultType>; + + /** + Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`. Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill). + */ + kill(signal?: string, options?: KillOptions): void; + + /** + Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This used to be preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`. But now this is deprecated and you should either use `.kill()` or the `signal` option when creating the child process. + */ + cancel(): void; + + /** + [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be: + - Another `execa()` return value + - A writable stream + - A file path string + + If the `target` is another `execa()` return value, it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the final result. + + The `stdout` option] must be kept as `pipe`, its default value. + */ + pipeStdout?>(target: Target): Target; + pipeStdout?(target: WritableStream | string): ExecaChildProcess; + + /** + Like `pipeStdout()` but piping the child process's `stderr` instead. + + The `stderr` option must be kept as `pipe`, its default value. + */ + pipeStderr?>(target: Target): Target; + pipeStderr?(target: WritableStream | string): ExecaChildProcess; + + /** + Combines both `pipeStdout()` and `pipeStderr()`. + + Either the `stdout` option or the `stderr` option must be kept as `pipe`, their default value. Also, the `all` option must be set to `true`. + */ + pipeAll?>(target: Target): Target; + pipeAll?(target: WritableStream | string): ExecaChildProcess; +}; + +export type ExecaChildProcess = ChildProcess & +ExecaChildPromise & +Promise>; + +/** +Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a `childProcess`. + +Arguments are automatically escaped. They can contain any character, including spaces. + +This is the preferred method when executing single commands. + +@param file - The program/script to execute. +@param arguments - Arguments to pass to `file` on execution. +@returns An `ExecaChildProcess` that is both: + - a `Promise` resolving or rejecting with a `childProcessResult`. + - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties. +@throws A `childProcessResult` error + +@example Promise interface +``` +import {execa} from 'execa'; + +const {stdout} = await execa('echo', ['unicorns']); +console.log(stdout); +//=> 'unicorns' +``` + +@example Redirect output to a file +``` +import {execa} from 'execa'; + +// Similar to `echo unicorns > stdout.txt` in Bash +await execa('echo', ['unicorns']).pipeStdout('stdout.txt'); + +// Similar to `echo unicorns 2> stdout.txt` in Bash +await execa('echo', ['unicorns']).pipeStderr('stderr.txt'); + +// Similar to `echo unicorns &> stdout.txt` in Bash +await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt'); +``` + +@example Redirect input from a file +``` +import {execa} from 'execa'; + +// Similar to `cat < stdin.txt` in Bash +const {stdout} = await execa('cat', {inputFile: 'stdin.txt'}); +console.log(stdout); +//=> 'unicorns' +``` + +@example Save and pipe output from a child process +``` +import {execa} from 'execa'; + +const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout); +// Prints `unicorns` +console.log(stdout); +// Also returns 'unicorns' +``` + +@example Pipe multiple processes +``` +import {execa} from 'execa'; + +// Similar to `echo unicorns | cat` in Bash +const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat')); +console.log(stdout); +//=> 'unicorns' +``` + +@example Handling errors +``` +import {execa} from 'execa'; + +// Catching an error +try { + await execa('unknown', ['command']); +} catch (error) { + console.log(error); + /* + { + message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT', + errno: -2, + code: 'ENOENT', + syscall: 'spawn unknown', + path: 'unknown', + spawnargs: ['command'], + originalMessage: 'spawn unknown ENOENT', + shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT', + command: 'unknown command', + escapedCommand: 'unknown command', + stdout: '', + stderr: '', + failed: true, + timedOut: false, + isCanceled: false, + killed: false, + cwd: '/path/to/cwd' + } + \*\/ +} +``` + +@example Graceful termination +``` +const subprocess = execa('node'); + +setTimeout(() => { + subprocess.kill('SIGTERM', { + forceKillAfterTimeout: 2000 + }); +}, 1000); +``` +*/ +export function execa( + file: string, + arguments?: readonly string[], + options?: Options +): ExecaChildProcess; +export function execa( + file: string, + arguments?: readonly string[], + options?: Options +): ExecaChildProcess; +export function execa(file: string, options?: Options): ExecaChildProcess; +export function execa(file: string, options?: Options): ExecaChildProcess; + +/** +Same as `execa()` but synchronous. + +@param file - The program/script to execute. +@param arguments - Arguments to pass to `file` on execution. +@returns A `childProcessResult` object +@throws A `childProcessResult` error + +@example Promise interface +``` +import {execa} from 'execa'; + +const {stdout} = execaSync('echo', ['unicorns']); +console.log(stdout); +//=> 'unicorns' +``` + +@example Redirect input from a file +``` +import {execa} from 'execa'; + +// Similar to `cat < stdin.txt` in Bash +const {stdout} = execaSync('cat', {inputFile: 'stdin.txt'}); +console.log(stdout); +//=> 'unicorns' +``` + +@example Handling errors +``` +import {execa} from 'execa'; + +// Catching an error +try { + execaSync('unknown', ['command']); +} catch (error) { + console.log(error); + /* + { + message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT', + errno: -2, + code: 'ENOENT', + syscall: 'spawnSync unknown', + path: 'unknown', + spawnargs: ['command'], + originalMessage: 'spawnSync unknown ENOENT', + shortMessage: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT', + command: 'unknown command', + escapedCommand: 'unknown command', + stdout: '', + stderr: '', + failed: true, + timedOut: false, + isCanceled: false, + killed: false, + cwd: '/path/to/cwd' + } + \*\/ +} +``` +*/ +export function execaSync( + file: string, + arguments?: readonly string[], + options?: SyncOptions +): ExecaSyncReturnValue; +export function execaSync( + file: string, + arguments?: readonly string[], + options?: SyncOptions +): ExecaSyncReturnValue; +export function execaSync(file: string, options?: SyncOptions): ExecaSyncReturnValue; +export function execaSync( + file: string, + options?: SyncOptions +): ExecaSyncReturnValue; + +/** +Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a `childProcess`. + +Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`. + +This is the preferred method when executing a user-supplied `command` string, such as in a REPL. + +@param command - The program/script to execute and its arguments. +@returns An `ExecaChildProcess` that is both: + - a `Promise` resolving or rejecting with a `childProcessResult`. + - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties. +@throws A `childProcessResult` error + +@example +``` +import {execaCommand} from 'execa'; + +const {stdout} = await execaCommand('echo unicorns'); +console.log(stdout); +//=> 'unicorns' +``` +*/ +export function execaCommand(command: string, options?: Options): ExecaChildProcess; +export function execaCommand(command: string, options?: Options): ExecaChildProcess; + +/** +Same as `execaCommand()` but synchronous. + +@param command - The program/script to execute and its arguments. +@returns A `childProcessResult` object +@throws A `childProcessResult` error + +@example +``` +import {execaCommandSync} from 'execa'; + +const {stdout} = execaCommandSync('echo unicorns'); +console.log(stdout); +//=> 'unicorns' +``` +*/ +export function execaCommandSync(command: string, options?: SyncOptions): ExecaSyncReturnValue; +export function execaCommandSync(command: string, options?: SyncOptions): ExecaSyncReturnValue; + +type TemplateExpression = + | string + | number + | ExecaReturnValue + | ExecaSyncReturnValue + | Array | ExecaSyncReturnValue>; + +type Execa$ = { + /** + Returns a new instance of `$` but with different default `options`. Consecutive calls are merged to previous ones. + + This can be used to either: + - Set options for a specific command: `` $(options)`command` `` + - Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand` `` + + @param options - Options to set + @returns A new instance of `$` with those `options` set + + @example + ``` + import {$} from 'execa'; + + const $$ = $({stdio: 'inherit'}); + + await $$`echo unicorns`; + //=> 'unicorns' + + await $$`echo rainbows`; + //=> 'rainbows' + ``` + */ + (options: Options): Execa$; + (options: Options): Execa$; + (options: Options): Execa$; + ( + templates: TemplateStringsArray, + ...expressions: TemplateExpression[] + ): ExecaChildProcess; + + /** + Same as $\`command\` but synchronous. + + @returns A `childProcessResult` object + @throws A `childProcessResult` error + + @example Basic + ``` + import {$} from 'execa'; + + const branch = $.sync`git branch --show-current`; + $.sync`dep deploy --branch=${branch}`; + ``` + + @example Multiple arguments + ``` + import {$} from 'execa'; + + const args = ['unicorns', '&', 'rainbows!']; + const {stdout} = $.sync`echo ${args}`; + console.log(stdout); + //=> 'unicorns & rainbows!' + ``` + + @example With options + ``` + import {$} from 'execa'; + + $.sync({stdio: 'inherit'})`echo unicorns`; + //=> 'unicorns' + ``` + + @example Shared options + ``` + import {$} from 'execa'; + + const $$ = $({stdio: 'inherit'}); + + $$.sync`echo unicorns`; + //=> 'unicorns' + + $$.sync`echo rainbows`; + //=> 'rainbows' + ``` + */ + sync( + templates: TemplateStringsArray, + ...expressions: TemplateExpression[] + ): ExecaSyncReturnValue; +}; + +/** +Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a `childProcess`. + +Arguments are automatically escaped. They can contain any character, but spaces must use `${}` like `` $`echo ${'has space'}` ``. + +This is the preferred method when executing multiple commands in a script file. + +The `command` string can inject any `${value}` with the following types: string, number, `childProcess` or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used. + +@returns An `ExecaChildProcess` that is both: + - a `Promise` resolving or rejecting with a `childProcessResult`. + - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties. +@throws A `childProcessResult` error + +@example Basic +``` +import {$} from 'execa'; + +const branch = await $`git branch --show-current`; +await $`dep deploy --branch=${branch}`; +``` + +@example Multiple arguments +``` +import {$} from 'execa'; + +const args = ['unicorns', '&', 'rainbows!']; +const {stdout} = await $`echo ${args}`; +console.log(stdout); +//=> 'unicorns & rainbows!' +``` + +@example With options +``` +import {$} from 'execa'; + +await $({stdio: 'inherit'})`echo unicorns`; +//=> 'unicorns' +``` + +@example Shared options +``` +import {$} from 'execa'; + +const $$ = $({stdio: 'inherit'}); + +await $$`echo unicorns`; +//=> 'unicorns' + +await $$`echo rainbows`; +//=> 'rainbows' +``` +*/ +export const $: Execa$; + +/** +Execute a Node.js script as a child process. + +Arguments are automatically escaped. They can contain any character, including spaces. + +This is the preferred method when executing Node.js files. + +Like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options): + - the current Node version and options are used. This can be overridden using the `nodePath` and `nodeOptions` options. + - the `shell` option cannot be used + - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to `stdio` + +@param scriptPath - Node.js script to execute. +@param arguments - Arguments to pass to `scriptPath` on execution. +@returns An `ExecaChildProcess` that is both: + - a `Promise` resolving or rejecting with a `childProcessResult`. + - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties. +@throws A `childProcessResult` error + +@example +``` +import {execa} from 'execa'; + +await execaNode('scriptPath', ['argument']); +``` +*/ +export function execaNode( + scriptPath: string, + arguments?: readonly string[], + options?: NodeOptions +): ExecaChildProcess; +export function execaNode( + scriptPath: string, + arguments?: readonly string[], + options?: NodeOptions +): ExecaChildProcess; +export function execaNode(scriptPath: string, options?: NodeOptions): ExecaChildProcess; +export function execaNode(scriptPath: string, options?: NodeOptions): ExecaChildProcess; diff --git a/web/node_modules/execa/index.js b/web/node_modules/execa/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fa417620f35b1aa97910897af2c2e092a48d26c9 --- /dev/null +++ b/web/node_modules/execa/index.js @@ -0,0 +1,309 @@ +import {Buffer} from 'node:buffer'; +import path from 'node:path'; +import childProcess from 'node:child_process'; +import process from 'node:process'; +import crossSpawn from 'cross-spawn'; +import stripFinalNewline from 'strip-final-newline'; +import {npmRunPathEnv} from 'npm-run-path'; +import onetime from 'onetime'; +import {makeError} from './lib/error.js'; +import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js'; +import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js'; +import {addPipeMethods} from './lib/pipe.js'; +import {handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js'; +import {mergePromise, getSpawnedPromise} from './lib/promise.js'; +import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js'; +import {logCommand, verboseDefault} from './lib/verbose.js'; + +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; + +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process.env, ...envOption} : envOption; + + if (preferLocal) { + return npmRunPathEnv({env, cwd: localDir, execPath}); + } + + return env; +}; + +const handleArguments = (file, args, options = {}) => { + const parsed = crossSpawn._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process.cwd(), + execPath: process.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + verbose: verboseDefault, + ...options, + }; + + options.env = getEnv(options); + + options.stdio = normalizeStdio(options); + + if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } + + return {file, args, options, parsed}; +}; + +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execaSync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } + + return value; +}; + +export function execa(file, args, options) { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + logCommand(escapedCommand, parsed.options); + + validateTimeout(parsed.options); + + let spawned; + try { + spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false, + })); + mergePromise(dummySpawned, errorPromise); + return dummySpawned; + } + + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); + + const context = {isCanceled: false}; + + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); + + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); + + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + escapedCommand, + parsed, + timedOut, + isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false), + killed: spawned.killed, + }); + + if (!parsed.options.reject) { + return returnedError; + } + + throw returnedError; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false, + }; + }; + + const handlePromiseOnce = onetime(handlePromise); + + handleInput(spawned, parsed.options); + + spawned.all = makeAllStream(spawned, parsed.options); + + addPipeMethods(spawned); + mergePromise(spawned, handlePromiseOnce); + return spawned; +} + +export function execaSync(file, args, options) { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + logCommand(escapedCommand, parsed.options); + + const input = handleInputSync(parsed.options); + + let result; + try { + result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input}); + } catch (error) { + throw makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false, + }); + } + + const stdout = handleOutput(parsed.options, result.stdout, result.error); + const stderr = handleOutput(parsed.options, result.stderr, result.error); + + if (result.error || result.status !== 0 || result.signal !== null) { + const error = makeError({ + stdout, + stderr, + error: result.error, + signal: result.signal, + exitCode: result.status, + command, + escapedCommand, + parsed, + timedOut: result.error && result.error.code === 'ETIMEDOUT', + isCanceled: false, + killed: result.signal !== null, + }); + + if (!parsed.options.reject) { + return error; + } + + throw error; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + failed: false, + timedOut: false, + isCanceled: false, + killed: false, + }; +} + +const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined + ? {stdin: 'inherit'} + : {}; + +const normalizeScriptOptions = (options = {}) => ({ + preferLocal: true, + ...normalizeScriptStdin(options), + ...options, +}); + +function create$(options) { + function $(templatesOrOptions, ...expressions) { + if (!Array.isArray(templatesOrOptions)) { + return create$({...options, ...templatesOrOptions}); + } + + const [file, ...args] = parseTemplates(templatesOrOptions, expressions); + return execa(file, args, normalizeScriptOptions(options)); + } + + $.sync = (templates, ...expressions) => { + if (!Array.isArray(templates)) { + throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.'); + } + + const [file, ...args] = parseTemplates(templates, expressions); + return execaSync(file, args, normalizeScriptOptions(options)); + }; + + return $; +} + +export const $ = create$(); + +export function execaCommand(command, options) { + const [file, ...args] = parseCommand(command); + return execa(file, args, options); +} + +export function execaCommandSync(command, options) { + const [file, ...args] = parseCommand(command); + return execaSync(file, args, options); +} + +export function execaNode(scriptPath, args, options = {}) { + if (args && !Array.isArray(args) && typeof args === 'object') { + options = args; + args = []; + } + + const stdio = normalizeStdioNode(options); + const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); + + const { + nodePath = process.execPath, + nodeOptions = defaultExecArgv, + } = options; + + return execa( + nodePath, + [ + ...nodeOptions, + scriptPath, + ...(Array.isArray(args) ? args : []), + ], + { + ...options, + stdin: undefined, + stdout: undefined, + stderr: undefined, + stdio, + shell: false, + }, + ); +} diff --git a/web/node_modules/execa/lib/command.js b/web/node_modules/execa/lib/command.js new file mode 100644 index 0000000000000000000000000000000000000000..727ce5f589a94431f292c9197fa17222232be6af --- /dev/null +++ b/web/node_modules/execa/lib/command.js @@ -0,0 +1,119 @@ +import {Buffer} from 'node:buffer'; +import {ChildProcess} from 'node:child_process'; + +const normalizeArgs = (file, args = []) => { + if (!Array.isArray(args)) { + return [file]; + } + + return [file, ...args]; +}; + +const NO_ESCAPE_REGEXP = /^[\w.-]+$/; + +const escapeArg = arg => { + if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { + return arg; + } + + return `"${arg.replaceAll('"', '\\"')}"`; +}; + +export const joinCommand = (file, args) => normalizeArgs(file, args).join(' '); + +export const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); + +const SPACES_REGEXP = / +/g; + +// Handle `execaCommand()` +export const parseCommand = command => { + const tokens = []; + for (const token of command.trim().split(SPACES_REGEXP)) { + // Allow spaces to be escaped by a backslash if not meant as a delimiter + const previousToken = tokens.at(-1); + if (previousToken && previousToken.endsWith('\\')) { + // Merge previous token with current one + tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; + } else { + tokens.push(token); + } + } + + return tokens; +}; + +const parseExpression = expression => { + const typeOfExpression = typeof expression; + + if (typeOfExpression === 'string') { + return expression; + } + + if (typeOfExpression === 'number') { + return String(expression); + } + + if ( + typeOfExpression === 'object' + && expression !== null + && !(expression instanceof ChildProcess) + && 'stdout' in expression + ) { + const typeOfStdout = typeof expression.stdout; + + if (typeOfStdout === 'string') { + return expression.stdout; + } + + if (Buffer.isBuffer(expression.stdout)) { + return expression.stdout.toString(); + } + + throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`); + } + + throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`); +}; + +const concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 0 + ? [...tokens, ...nextTokens] + : [ + ...tokens.slice(0, -1), + `${tokens.at(-1)}${nextTokens[0]}`, + ...nextTokens.slice(1), + ]; + +const parseTemplate = ({templates, expressions, tokens, index, template}) => { + const templateString = template ?? templates.raw[index]; + const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean); + const newTokens = concatTokens( + tokens, + templateTokens, + templateString.startsWith(' '), + ); + + if (index === expressions.length) { + return newTokens; + } + + const expression = expressions[index]; + const expressionTokens = Array.isArray(expression) + ? expression.map(expression => parseExpression(expression)) + : [parseExpression(expression)]; + return concatTokens( + newTokens, + expressionTokens, + templateString.endsWith(' '), + ); +}; + +export const parseTemplates = (templates, expressions) => { + let tokens = []; + + for (const [index, template] of templates.entries()) { + tokens = parseTemplate({templates, expressions, tokens, index, template}); + } + + return tokens; +}; + diff --git a/web/node_modules/execa/lib/error.js b/web/node_modules/execa/lib/error.js new file mode 100644 index 0000000000000000000000000000000000000000..5e80c5273beead60094cbac82ee5d20b8a0ee24d --- /dev/null +++ b/web/node_modules/execa/lib/error.js @@ -0,0 +1,87 @@ +import process from 'node:process'; +import {signalsByName} from 'human-signals'; + +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + + if (isCanceled) { + return 'was canceled'; + } + + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } + + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +export const makeError = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + escapedCommand, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout, cwd = process.cwd()}}, +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.escapedCommand = escapedCommand; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + error.cwd = cwd; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; diff --git a/web/node_modules/execa/lib/kill.js b/web/node_modules/execa/lib/kill.js new file mode 100644 index 0000000000000000000000000000000000000000..12ce0a1c9e47f3aa64c6ff05e5c4e4acedfb9805 --- /dev/null +++ b/web/node_modules/execa/lib/kill.js @@ -0,0 +1,102 @@ +import os from 'node:os'; +import {onExit} from 'signal-exit'; + +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; + +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; + +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } + + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); + + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; + +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult; + +const isSigterm = signal => signal === os.constants.signals.SIGTERM + || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); + +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } + + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } + + return forceKillAfterTimeout; +}; + +// `childProcess.cancel()` +export const spawnedCancel = (spawned, context) => { + const killResult = spawned.kill(); + + if (killResult) { + context.isCanceled = true; + } +}; + +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; + +// `timeout` option handling +export const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); + + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); + + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; + +export const validateTimeout = ({timeout}) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}; + +// `cleanup` option handling +export const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = onExit(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; diff --git a/web/node_modules/execa/lib/pipe.js b/web/node_modules/execa/lib/pipe.js new file mode 100644 index 0000000000000000000000000000000000000000..e73ffcc9896eff8c2d23d3fba98a824d74a38666 --- /dev/null +++ b/web/node_modules/execa/lib/pipe.js @@ -0,0 +1,42 @@ +import {createWriteStream} from 'node:fs'; +import {ChildProcess} from 'node:child_process'; +import {isWritableStream} from 'is-stream'; + +const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function'; + +const pipeToTarget = (spawned, streamName, target) => { + if (typeof target === 'string') { + spawned[streamName].pipe(createWriteStream(target)); + return spawned; + } + + if (isWritableStream(target)) { + spawned[streamName].pipe(target); + return spawned; + } + + if (!isExecaChildProcess(target)) { + throw new TypeError('The second argument must be a string, a stream or an Execa child process.'); + } + + if (!isWritableStream(target.stdin)) { + throw new TypeError('The target child process\'s stdin must be available.'); + } + + spawned[streamName].pipe(target.stdin); + return target; +}; + +export const addPipeMethods = spawned => { + if (spawned.stdout !== null) { + spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout'); + } + + if (spawned.stderr !== null) { + spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr'); + } + + if (spawned.all !== undefined) { + spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all'); + } +}; diff --git a/web/node_modules/execa/lib/promise.js b/web/node_modules/execa/lib/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..a4773f30b0b4690553bd96d23a44969bfd05478a --- /dev/null +++ b/web/node_modules/execa/lib/promise.js @@ -0,0 +1,36 @@ +// eslint-disable-next-line unicorn/prefer-top-level-await +const nativePromisePrototype = (async () => {})().constructor.prototype; + +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), +]); + +// The return value is a mixin of `childProcess` and `Promise` +export const mergePromise = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' + ? (...args) => Reflect.apply(descriptor.value, promise(), args) + : descriptor.value.bind(promise); + + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } +}; + +// Use promises instead of `child_process` events +export const getSpawnedPromise = spawned => new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); + + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } +}); diff --git a/web/node_modules/execa/lib/stdio.js b/web/node_modules/execa/lib/stdio.js new file mode 100644 index 0000000000000000000000000000000000000000..e8c1132dc1aa3dd947bfc397e0240989ea434bae --- /dev/null +++ b/web/node_modules/execa/lib/stdio.js @@ -0,0 +1,49 @@ +const aliases = ['stdin', 'stdout', 'stderr']; + +const hasAlias = options => aliases.some(alias => options[alias] !== undefined); + +export const normalizeStdio = options => { + if (!options) { + return; + } + + const {stdio} = options; + + if (stdio === undefined) { + return aliases.map(alias => options[alias]); + } + + if (hasAlias(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } + + if (typeof stdio === 'string') { + return stdio; + } + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); +}; + +// `ipc` is pushed unless it is already present +export const normalizeStdioNode = options => { + const stdio = normalizeStdio(options); + + if (stdio === 'ipc') { + return 'ipc'; + } + + if (stdio === undefined || typeof stdio === 'string') { + return [stdio, stdio, stdio, 'ipc']; + } + + if (stdio.includes('ipc')) { + return stdio; + } + + return [...stdio, 'ipc']; +}; diff --git a/web/node_modules/execa/lib/stream.js b/web/node_modules/execa/lib/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..4e06459211e3a68a0f1e070aa75f53757e77547e --- /dev/null +++ b/web/node_modules/execa/lib/stream.js @@ -0,0 +1,133 @@ +import {createReadStream, readFileSync} from 'node:fs'; +import {setTimeout} from 'node:timers/promises'; +import {isStream} from 'is-stream'; +import getStream, {getStreamAsBuffer} from 'get-stream'; +import mergeStream from 'merge-stream'; + +const validateInputOptions = input => { + if (input !== undefined) { + throw new TypeError('The `input` and `inputFile` options cannot be both set.'); + } +}; + +const getInputSync = ({input, inputFile}) => { + if (typeof inputFile !== 'string') { + return input; + } + + validateInputOptions(input); + return readFileSync(inputFile); +}; + +// `input` and `inputFile` option in sync mode +export const handleInputSync = options => { + const input = getInputSync(options); + + if (isStream(input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } + + return input; +}; + +const getInput = ({input, inputFile}) => { + if (typeof inputFile !== 'string') { + return input; + } + + validateInputOptions(input); + return createReadStream(inputFile); +}; + +// `input` and `inputFile` option in async mode +export const handleInput = (spawned, options) => { + const input = getInput(options); + + if (input === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; + +// `all` interleaves `stdout` and `stderr` +export const makeAllStream = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } + + const mixed = mergeStream(); + + if (spawned.stdout) { + mixed.add(spawned.stdout); + } + + if (spawned.stderr) { + mixed.add(spawned.stderr); + } + + return mixed; +}; + +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve + if (!stream || streamPromise === undefined) { + return; + } + + // Wait for the `all` stream to receive the last chunk before destroying the stream + await setTimeout(0); + + stream.destroy(); + + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; + +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } + + // eslint-disable-next-line unicorn/text-encoding-identifier-case + if (encoding === 'utf8' || encoding === 'utf-8') { + return getStream(stream, {maxBuffer}); + } + + if (encoding === null || encoding === 'buffer') { + return getStreamAsBuffer(stream, {maxBuffer}); + } + + return applyEncoding(stream, maxBuffer, encoding); +}; + +const applyEncoding = async (stream, maxBuffer, encoding) => { + const buffer = await getStreamAsBuffer(stream, {maxBuffer}); + return buffer.toString(encoding); +}; + +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +export const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise), + ]); + } +}; diff --git a/web/node_modules/execa/lib/verbose.js b/web/node_modules/execa/lib/verbose.js new file mode 100644 index 0000000000000000000000000000000000000000..5f5490ed024fd394c285517d4e2e7eaa4ab2ea0c --- /dev/null +++ b/web/node_modules/execa/lib/verbose.js @@ -0,0 +1,19 @@ +import {debuglog} from 'node:util'; +import process from 'node:process'; + +export const verboseDefault = debuglog('execa').enabled; + +const padField = (field, padding) => String(field).padStart(padding, '0'); + +const getTimestamp = () => { + const date = new Date(); + return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`; +}; + +export const logCommand = (escapedCommand, {verbose}) => { + if (!verbose) { + return; + } + + process.stderr.write(`[${getTimestamp()}] ${escapedCommand}\n`); +}; diff --git a/web/node_modules/execa/license b/web/node_modules/execa/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/execa/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/web/node_modules/execa/package.json b/web/node_modules/execa/package.json new file mode 100644 index 0000000000000000000000000000000000000000..24ff1792a3833b50231a24ae6da690a983a5cb6d --- /dev/null +++ b/web/node_modules/execa/package.json @@ -0,0 +1,90 @@ +{ + "name": "execa", + "version": "8.0.1", + "description": "Process execution for humans", + "license": "MIT", + "repository": "sindresorhus/execa", + "funding": "https://github.com/sindresorhus/execa?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": ">=16.17" + }, + "scripts": { + "test": "xo && c8 ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "lib" + ], + "keywords": [ + "exec", + "child", + "process", + "execute", + "fork", + "execfile", + "spawn", + "file", + "shell", + "bin", + "binary", + "binaries", + "npm", + "path", + "local", + "zx" + ], + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "devDependencies": { + "@types/node": "^20.4.0", + "ava": "^5.2.0", + "c8": "^8.0.1", + "get-node": "^14.2.0", + "is-running": "^2.1.0", + "p-event": "^6.0.0", + "path-key": "^4.0.0", + "tempfile": "^5.0.0", + "tsd": "^0.28.1", + "xo": "^0.55.0" + }, + "c8": { + "reporter": [ + "text", + "lcov" + ], + "exclude": [ + "**/fixtures/**", + "**/test.js", + "**/test/**" + ] + }, + "ava": { + "workerThreads": false + }, + "xo": { + "rules": { + "unicorn/no-empty-file": "off", + "@typescript-eslint/ban-types": "off" + } + } +} diff --git a/web/node_modules/execa/readme.md b/web/node_modules/execa/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1babbe5f8ea46039ed53bcbdda72e9455b24afe9 --- /dev/null +++ b/web/node_modules/execa/readme.md @@ -0,0 +1,822 @@ + + + execa logo + +
+ +[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/execa) + +> Process execution for humans + +
+ +--- + +
+

+

+ + Sindre's open source work is supported by the community + +

+ Special thanks to: +
+
+ + + + + Transloadit logo + + +
+
+

+
+ +--- + +
+ +## Why + +This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with: + +- [Promise interface](#execacommandcommand-options). +- [Scripts interface](#scripts-interface), like `zx`. +- Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries. +- Executes [locally installed binaries](#preferlocal) without `npx`. +- [Cleans up](#cleanup) child processes when the parent process ends. +- [Graceful termination](#optionsforcekillaftertimeout). +- Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. +- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`. +- Convenience methods to pipe processes' [input](#input) and [output](#redirect-output-to-a-file). +- Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell. +- [Verbose mode](#verbose-mode) for debugging. +- More descriptive errors. +- Higher max buffer: 100 MB instead of 1 MB. + +## Install + +```sh +npm install execa +``` + +## Usage + +### Promise interface + +```js +import {execa} from 'execa'; + +const {stdout} = await execa('echo', ['unicorns']); +console.log(stdout); +//=> 'unicorns' +``` + +### Scripts interface + +For more information about Execa scripts, please see [this page](docs/scripts.md). + +#### Basic + +```js +import {$} from 'execa'; + +const branch = await $`git branch --show-current`; +await $`dep deploy --branch=${branch}`; +``` + +#### Multiple arguments + +```js +import {$} from 'execa'; + +const args = ['unicorns', '&', 'rainbows!']; +const {stdout} = await $`echo ${args}`; +console.log(stdout); +//=> 'unicorns & rainbows!' +``` + +#### With options + +```js +import {$} from 'execa'; + +await $({stdio: 'inherit'})`echo unicorns`; +//=> 'unicorns' +``` + +#### Shared options + +```js +import {$} from 'execa'; + +const $$ = $({stdio: 'inherit'}); + +await $$`echo unicorns`; +//=> 'unicorns' + +await $$`echo rainbows`; +//=> 'rainbows' +``` + +#### Verbose mode + +```sh +> node file.js +unicorns +rainbows + +> NODE_DEBUG=execa node file.js +[16:50:03.305] echo unicorns +unicorns +[16:50:03.308] echo rainbows +rainbows +``` + +### Input/output + +#### Redirect output to a file + +```js +import {execa} from 'execa'; + +// Similar to `echo unicorns > stdout.txt` in Bash +await execa('echo', ['unicorns']).pipeStdout('stdout.txt'); + +// Similar to `echo unicorns 2> stdout.txt` in Bash +await execa('echo', ['unicorns']).pipeStderr('stderr.txt'); + +// Similar to `echo unicorns &> stdout.txt` in Bash +await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt'); +``` + +#### Redirect input from a file + +```js +import {execa} from 'execa'; + +// Similar to `cat < stdin.txt` in Bash +const {stdout} = await execa('cat', {inputFile: 'stdin.txt'}); +console.log(stdout); +//=> 'unicorns' +``` + +#### Save and pipe output from a child process + +```js +import {execa} from 'execa'; + +const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout); +// Prints `unicorns` +console.log(stdout); +// Also returns 'unicorns' +``` + +#### Pipe multiple processes + +```js +import {execa} from 'execa'; + +// Similar to `echo unicorns | cat` in Bash +const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat')); +console.log(stdout); +//=> 'unicorns' +``` + +### Handling Errors + +```js +import {execa} from 'execa'; + +// Catching an error +try { + await execa('unknown', ['command']); +} catch (error) { + console.log(error); + /* + { + message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT', + errno: -2, + code: 'ENOENT', + syscall: 'spawn unknown', + path: 'unknown', + spawnargs: ['command'], + originalMessage: 'spawn unknown ENOENT', + shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT', + command: 'unknown command', + escapedCommand: 'unknown command', + stdout: '', + stderr: '', + failed: true, + timedOut: false, + isCanceled: false, + killed: false + } + */ +} +``` + +### Graceful termination + +Using SIGTERM, and after 2 seconds, kill it with SIGKILL. + +```js +const subprocess = execa('node'); + +setTimeout(() => { + subprocess.kill('SIGTERM', { + forceKillAfterTimeout: 2000 + }); +}, 1000); +``` + +## API + +### Methods + +#### execa(file, arguments?, options?) + +Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess). + +Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces. + +This is the preferred method when executing single commands. + +#### execaNode(scriptPath, arguments?, options?) + +Executes a Node.js file using `node scriptPath ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess). + +Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces. + +This is the preferred method when executing Node.js files. + +Like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options): + - the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options. + - the [`shell`](#shell) option cannot be used + - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio) + +#### $\`command\` + +Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess). + +Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must use `${}` like `` $`echo ${'has space'}` ``. + +This is the preferred method when executing multiple commands in a script file. + +The `command` string can inject any `${value}` with the following types: string, number, [`childProcess`](#childprocess) or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used. + +For more information, please see [this section](#scripts-interface) and [this page](docs/scripts.md). + +#### $(options) + +Returns a new instance of [`$`](#command) but with different default `options`. Consecutive calls are merged to previous ones. + +This can be used to either: + - Set options for a specific command: `` $(options)`command` `` + - Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand`; `` + +#### execaCommand(command, options?) + +Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess). + +Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`. + +This is the preferred method when executing a user-supplied `command` string, such as in a REPL. + +### execaSync(file, arguments?, options?) + +Same as [`execa()`](#execacommandcommand-options) but synchronous. + +Returns or throws a [`childProcessResult`](#childProcessResult). + +### $.sync\`command\` + +Same as [$\`command\`](#command) but synchronous. + +Returns or throws a [`childProcessResult`](#childProcessResult). + +### execaCommandSync(command, options?) + +Same as [`execaCommand()`](#execacommand-command-options) but synchronous. + +Returns or throws a [`childProcessResult`](#childProcessResult). + +### Shell syntax + +For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped. + +### childProcess + +The return value of all [asynchronous methods](#methods) is both: + - a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult). + - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following additional methods and properties. + +#### kill(signal?, options?) + +Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`. + +Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill). + +##### options.forceKillAfterTimeout + +Type: `number | false`\ +Default: `5000` + +Milliseconds to wait for the child process to terminate before sending `SIGKILL`. + +Can be disabled with `false`. + +#### all + +Type: `ReadableStream | undefined` + +Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr). + +This is `undefined` if either: + - the [`all` option](#all-2) is `false` (the default value) + - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio) + +#### pipeStdout(target) + +[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be: + - Another [`execa()` return value](#pipe-multiple-processes) + - A [writable stream](#save-and-pipe-output-from-a-child-process) + - A [file path string](#redirect-output-to-a-file) + +If the `target` is another [`execa()` return value](#execacommandcommand-options), it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the [final result](#childprocessresult). + +The [`stdout` option](#stdout-1) must be kept as `pipe`, its default value. + +#### pipeStderr(target) + +Like [`pipeStdout()`](#pipestdouttarget) but piping the child process's `stderr` instead. + +The [`stderr` option](#stderr-1) must be kept as `pipe`, its default value. + +#### pipeAll(target) + +Combines both [`pipeStdout()`](#pipestdouttarget) and [`pipeStderr()`](#pipestderrtarget). + +Either the [`stdout` option](#stdout-1) or the [`stderr` option](#stderr-1) must be kept as `pipe`, their default value. Also, the [`all` option](#all-2) must be set to `true`. + +### childProcessResult + +Type: `object` + +Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance. + +The child process [fails](#failed) when: +- its [exit code](#exitcode) is not `0` +- it was [killed](#killed) with a [signal](#signal) +- [timing out](#timedout) +- [being canceled](#iscanceled) +- there's not enough memory or there are already too many child processes + +#### command + +Type: `string` + +The file and arguments that were run, for logging purposes. + +This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options). + +#### escapedCommand + +Type: `string` + +Same as [`command`](#command-1) but escaped. + +This is meant to be copy and pasted into a shell, for debugging purposes. +Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options). + +#### exitCode + +Type: `number` + +The numeric exit code of the process that was run. + +#### stdout + +Type: `string | Buffer` + +The output of the process on stdout. + +#### stderr + +Type: `string | Buffer` + +The output of the process on stderr. + +#### all + +Type: `string | Buffer | undefined` + +The output of the process with `stdout` and `stderr` interleaved. + +This is `undefined` if either: + - the [`all` option](#all-2) is `false` (the default value) + - `execaSync()` was used + +#### failed + +Type: `boolean` + +Whether the process failed to run. + +#### timedOut + +Type: `boolean` + +Whether the process timed out. + +#### isCanceled + +Type: `boolean` + +Whether the process was canceled. + +You can cancel the spawned process using the [`signal`](#signal-1) option. + +#### killed + +Type: `boolean` + +Whether the process was killed. + +#### signal + +Type: `string | undefined` + +The name of the signal that was used to terminate the process. For example, `SIGFPE`. + +If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. + +#### signalDescription + +Type: `string | undefined` + +A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`. + +If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen. + +#### cwd + +Type: `string` + +The `cwd` of the command if provided in the [command options](#cwd-1). Otherwise it is `process.cwd()`. + +#### message + +Type: `string` + +Error message when the child process failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the child process errored. + +The child process [stderr](#stderr) then [stdout](#stdout) are appended to the end, separated with newlines and not interleaved. + +#### shortMessage + +Type: `string` + +This is the same as the [`message` property](#message) except it does not include the child process stdout/stderr. + +#### originalMessage + +Type: `string | undefined` + +Original error message. This is the same as the `message` property except it includes neither the child process stdout/stderr nor some additional information added by Execa. + +This is `undefined` unless the child process exited due to an `error` event or a timeout. + +### options + +Type: `object` + +#### cleanup + +Type: `boolean`\ +Default: `true` + +Kill the spawned process when the parent process exits unless either: + - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached) + - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit + +#### preferLocal + +Type: `boolean`\ +Default: `true` with [`$`](#command), `false` otherwise + +Prefer locally installed binaries when looking for a binary to execute.\ +If you `$ npm install foo`, you can then `execa('foo')`. + +#### localDir + +Type: `string | URL`\ +Default: `process.cwd()` + +Preferred path to find locally installed binaries in (use with `preferLocal`). + +#### execPath + +Type: `string`\ +Default: `process.execPath` (Current Node.js executable) + +Path to the Node.js executable to use in child processes. + +This can be either an absolute path or a path relative to the [`cwd` option](#cwd). + +Requires [`preferLocal`](#preferlocal) to be `true`. + +For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process. + +#### buffer + +Type: `boolean`\ +Default: `true` + +Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected. + +If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data. + +#### input + +Type: `string | Buffer | stream.Readable` + +Write some input to the `stdin` of your binary.\ +Streams are not allowed when using the synchronous methods. + +If the input is a file, use the [`inputFile` option](#inputfile) instead. + +#### inputFile + +Type: `string` + +Use a file as input to the the `stdin` of your binary. + +If the input is not a file, use the [`input` option](#input) instead. + +#### stdin + +Type: `string | number | Stream | undefined`\ +Default: `inherit` with [`$`](#command), `pipe` otherwise + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### stdout + +Type: `string | number | Stream | undefined`\ +Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### stderr + +Type: `string | number | Stream | undefined`\ +Default: `pipe` + +Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio). + +#### all + +Type: `boolean`\ +Default: `false` + +Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the process with `stdout` and `stderr` interleaved. + +#### reject + +Type: `boolean`\ +Default: `true` + +Setting this to `false` resolves the promise with the error instead of rejecting it. + +#### stripFinalNewline + +Type: `boolean`\ +Default: `true` + +Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output. + +#### extendEnv + +Type: `boolean`\ +Default: `true` + +Set to `false` if you don't want to extend the environment variables when providing the `env` property. + +--- + +Execa also accepts the below options which are the same as the options for [`child_process#spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)/[`child_process#exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) + +#### cwd + +Type: `string | URL`\ +Default: `process.cwd()` + +Current working directory of the child process. + +#### env + +Type: `object`\ +Default: `process.env` + +Environment key-value pairs. Extends automatically from `process.env`. Set [`extendEnv`](#extendenv) to `false` if you don't want this. + +#### argv0 + +Type: `string` + +Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified. + +#### stdio + +Type: `string | string[]`\ +Default: `pipe` + +Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration. + +#### serialization + +Type: `string`\ +Default: `'json'` + +Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options): + - `json`: Uses `JSON.stringify()` and `JSON.parse()`. + - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value) + +[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization) + +#### detached + +Type: `boolean` + +Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached). + +#### uid + +Type: `number` + +Sets the user identity of the process. + +#### gid + +Type: `number` + +Sets the group identity of the process. + +#### shell + +Type: `boolean | string`\ +Default: `false` + +If `true`, runs `file` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows. + +We recommend against using this option since it is: +- not cross-platform, encouraging shell-specific syntax. +- slower, because of the additional shell interpretation. +- unsafe, potentially allowing command injection. + +#### encoding + +Type: `string | null`\ +Default: `utf8` + +Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `'buffer'` or `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string. + +#### timeout + +Type: `number`\ +Default: `0` + +If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds. + +#### maxBuffer + +Type: `number`\ +Default: `100_000_000` (100 MB) + +Largest amount of data in bytes allowed on `stdout` or `stderr`. + +#### killSignal + +Type: `string | number`\ +Default: `SIGTERM` + +Signal value to be used when the spawned process will be killed. + +#### signal + +Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) + +You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). + +When `AbortController.abort()` is called, [`.isCanceled`](#iscanceled) becomes `true`. + +#### windowsVerbatimArguments + +Type: `boolean`\ +Default: `false` + +If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`. + +#### windowsHide + +Type: `boolean`\ +Default: `true` + +On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows. + +#### verbose + +Type: `boolean`\ +Default: `false` + +[Print each command](#verbose-mode) on `stderr` before executing it. + +This can also be enabled by setting the `NODE_DEBUG=execa` environment variable in the current process. + +#### nodePath *(For `.node()` only)* + +Type: `string`\ +Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) + +Node.js executable used to create the child process. + +#### nodeOptions *(For `.node()` only)* + +Type: `string[]`\ +Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv) + +List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable. + +## Tips + +### Retry on error + +Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package: + +```js +import pRetry from 'p-retry'; + +const run = async () => { + const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']); + return results; +}; + +console.log(await pRetry(run, {retries: 5})); +``` + +### Cancelling a spawned process + +```js +import {execa} from 'execa'; + +const abortController = new AbortController(); +const subprocess = execa('node', [], {signal: abortController.signal}); + +setTimeout(() => { + abortController.abort(); +}, 1000); + +try { + await subprocess; +} catch (error) { + console.log(subprocess.killed); // true + console.log(error.isCanceled); // true +} +``` + +### Execute the current package's binary + +```js +import {getBinPath} from 'get-bin-path'; + +const binPath = await getBinPath(); +await execa(binPath); +``` + +`execa` can be combined with [`get-bin-path`](https://github.com/ehmicky/get-bin-path) to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the `package.json` `bin` field is correctly set up. + +## Related + +- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for `execa` +- [nvexeca](https://github.com/ehmicky/nvexeca) - Run `execa` using any Node.js version +- [sudo-prompt](https://github.com/jorangreef/sudo-prompt) - Run commands with elevated privileges. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [@ehmicky](https://github.com/ehmicky) + +--- + +
+ + 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/web/node_modules/get-func-name/LICENSE b/web/node_modules/get-func-name/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7ea799f0ef4a80112178975b5f15d97c4863e09e --- /dev/null +++ b/web/node_modules/get-func-name/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Jake Luer (http://alogicalparadox.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/web/node_modules/get-func-name/README.md b/web/node_modules/get-func-name/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9084162b7593d5120cc24567e9c069b459d7c9d --- /dev/null +++ b/web/node_modules/get-func-name/README.md @@ -0,0 +1,123 @@ +

+ + ChaiJS +
+ get-func-name +
+

+ +

+ Utility for getting a function's name for node and the browser. +

+ +

+ + license:mit + + + tag:? + + + build:? + + + coverage:? + + + npm:? + + + dependencies:? + + + devDependencies:? + +
+ + Selenium Test Status + +
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is get-func-name? + +This is a module to retrieve a function's name securely and consistently both in NodeJS and the browser. + +## Installation + +### Node.js + +`get-func-name` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install get-func-name + +### Browsers + +You can also use it within the browser; install via npm and use the `get-func-name.js` file found within the download. For example: + +```html + +``` + +## Usage + +The module `get-func-name` exports the following method: + +* `getFuncName(fn)` - Returns the name of a function. + +```js +var getFuncName = require('get-func-name'); +``` + +#### .getFuncName(fun) + +```js +var getFuncName = require('get-func-name'); + +var unknownFunction = function myCoolFunction(word) { + return word + 'is cool'; +}; + +var anonymousFunction = (function () { + return function () {}; +}()); + +getFuncName(unknownFunction) // 'myCoolFunction' +getFuncName(anonymousFunction) // '' +``` diff --git a/web/node_modules/get-func-name/get-func-name.js b/web/node_modules/get-func-name/get-func-name.js new file mode 100644 index 0000000000000000000000000000000000000000..0070ed4586ce0473ac2034cb9150db29759269e9 --- /dev/null +++ b/web/node_modules/get-func-name/get-func-name.js @@ -0,0 +1 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * MIT Licensed + */ + +/** + * ### .getFuncName(constructorFn) + * + * Returns the name of a function. + * When a non-function instance is passed, returns `null`. + * This also includes a polyfill function if `aFunc.name` is not defined. + * + * @name getFuncName + * @param {Function} funct + * @namespace Utils + * @api public + */ + +var toString = Function.prototype.toString; +var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; +var maxFunctionSourceLength = 512; +function getFuncName(aFunc) { + if (typeof aFunc !== 'function') { + return null; + } + + var name = ''; + if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { + // eslint-disable-next-line prefer-reflect + var functionSource = toString.call(aFunc); + // To avoid unconstrained resource consumption due to pathalogically large function names, + // we limit the available return value to be less than 512 characters. + if (functionSource.indexOf('(') > maxFunctionSourceLength) { + return name; + } + // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined + var match = functionSource.match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + // If we've got a `name` property we just use it + name = aFunc.name; + } + + return name; +} + +module.exports = getFuncName; diff --git a/web/node_modules/get-func-name/package.json b/web/node_modules/get-func-name/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0eb8838a217f1e35de3672019dc8fe08aaac3286 --- /dev/null +++ b/web/node_modules/get-func-name/package.json @@ -0,0 +1,85 @@ +{ + "name": "get-func-name", + "version": "2.0.2", + "description": "Utility for getting a function's name for node and the browser", + "keywords": [ + "get-func-name", + "chai util" + ], + "license": "MIT", + "author": "Jake Luer (http://alogicalparadox.com)", + "contributors": [ + "Keith Cirkel (https://github.com/keithamus)", + "Lucas Fernandes da Costa (https://github.com/lucasfcosta)", + "Grant Snodgrass (https://github.com/meeber)", + "Lucas Vieira (https://github.com/vieiralucas)", + "Aleksey Shvayka (https://github.com/shvaikalesh)" + ], + "files": [ + "index.js", + "get-func-name.js" + ], + "main": "./index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/chaijs/get-func-name.git" + }, + "scripts": { + "build": "browserify --bare $npm_package_main --standalone getFuncName -o get-func-name.js", + "lint": "eslint --ignore-path .gitignore .", + "prepublish": "npm run build", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser && npm run upload-coverage", + "test:browser": "karma start --singleRun=true", + "test:node": "istanbul cover _mocha", + "upload-coverage": "lcov-result-merger 'coverage/**/lcov.info' | coveralls; exit 0" + }, + "config": { + "ghooks": { + "commit-msg": "validate-commit-msg" + } + }, + "eslintConfig": { + "extends": [ + "strict/es5" + ], + "env": { + "es6": true + }, + "globals": { + "HTMLElement": false + }, + "rules": { + "complexity": 0, + "max-statements": 0 + } + }, + "dependencies": {}, + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "2.11.14", + "eslint": "^2.4.0", + "eslint-config-strict": "^9.1.0", + "eslint-plugin-filenames": "^1.1.0", + "ghooks": "^1.0.1", + "istanbul": "^0.4.2", + "karma": "^1.3.0", + "karma-browserify": "^5.0.2", + "karma-coverage": "^1.1.1", + "karma-mocha": "^1.2.0", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sauce-launcher": "^1.0.0", + "lcov-result-merger": "^1.0.2", + "mocha": "^3.1.2", + "phantomjs-prebuilt": "^2.1.5", + "semantic-release": "^4.3.5", + "simple-assert": "^1.0.0", + "travis-after-all": "^1.4.4", + "validate-commit-msg": "^2.3.1" + }, + "engines": { + "node": "*" + } +} diff --git a/web/node_modules/get-stream/license b/web/node_modules/get-stream/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/get-stream/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/web/node_modules/get-stream/package.json b/web/node_modules/get-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bfd9a001d564242f610a867d269d7c1a5d066bba --- /dev/null +++ b/web/node_modules/get-stream/package.json @@ -0,0 +1,53 @@ +{ + "name": "get-stream", + "version": "8.0.1", + "description": "Get a stream as a string, Buffer, ArrayBuffer or array", + "license": "MIT", + "repository": "sindresorhus/get-stream", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./source/index.d.ts", + "default": "./source/index.js" + }, + "engines": { + "node": ">=16" + }, + "scripts": { + "benchmark": "node benchmarks/index.js", + "test": "xo && ava && tsd --typings=source/index.d.ts --files=source/index.test-d.ts" + }, + "files": [ + "source", + "!*.test-d.ts" + ], + "keywords": [ + "get", + "stream", + "promise", + "concat", + "string", + "text", + "buffer", + "read", + "data", + "consume", + "readable", + "readablestream", + "object", + "concat" + ], + "devDependencies": { + "@types/node": "^20.5.0", + "ava": "^5.3.1", + "precise-now": "^2.0.0", + "stream-json": "^1.8.0", + "tsd": "^0.28.1", + "xo": "^0.56.0" + } +} diff --git a/web/node_modules/get-stream/readme.md b/web/node_modules/get-stream/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..7f04b9471d545d16e04b45ab11ef6ff5778c3a3a --- /dev/null +++ b/web/node_modules/get-stream/readme.md @@ -0,0 +1,291 @@ +# get-stream + +> Get a stream as a string, Buffer, ArrayBuffer or array + +## Features + +- Works in any JavaScript environment ([Node.js](#nodejs-streams), [browsers](#web-streams), etc.). +- Supports [text streams](#getstreamstream-options), [binary streams](#getstreamasbufferstream-options) and [object streams](#getstreamasarraystream-options). +- Supports [async iterables](#async-iterables). +- Can set a [maximum stream size](#maxbuffer). +- Returns [partially read data](#errors) when the stream errors. +- [Fast](#benchmarks). + +## Install + +```sh +npm install get-stream +``` + +## Usage + +### Node.js streams + +```js +import fs from 'node:fs'; +import getStream from 'get-stream'; + +const stream = fs.createReadStream('unicorn.txt'); + +console.log(await getStream(stream)); +/* + ,,))))))));, + __)))))))))))))), +\|/ -\(((((''''((((((((. +-*-==//////(('' . `)))))), +/|\ ))| o ;-. '((((( ,(, + ( `| / ) ;))))' ,_))^;(~ + | | | ,))((((_ _____------~~~-. %,;(;(>';'~ + o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ + ; ''''```` `: `:::|\,__,%% );`'; ~ + | _ ) / `:|`----' `-' + ______/\/~ | / / + /~;;.____/;;' / ___--,-( `;;;/ + / // _;______;'------~~~~~ /;;/\ / + // | | / ; \;;,\ + (<_ | ; /',/-----' _> + \_| ||_ //~;~~~~~~~~~ + `\_| (,~~ + \~\ + ~~ +*/ +``` + +### Web streams + +```js +import getStream from 'get-stream'; + +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStream(readableStream)); +``` + +### Async iterables + +```js +import {opendir} from 'node:fs/promises'; +import {getStreamAsArray} from 'get-stream'; + +const asyncIterable = await opendir(directory); +console.log(await getStreamAsArray(asyncIterable)); +``` + +## API + +The following methods read the stream's contents and return it as a promise. + +### getStream(stream, options?) + +`stream`: [`stream.Readable`](https://nodejs.org/api/stream.html#class-streamreadable), [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), or [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)\ +`options`: [`Options`](#options) + +Get the given `stream` as a string. + +### getStreamAsBuffer(stream, options?) + +Get the given `stream` as a Node.js [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer). + +```js +import {getStreamAsBuffer} from 'get-stream'; + +const stream = fs.createReadStream('unicorn.png'); +console.log(await getStreamAsBuffer(stream)); +``` + +### getStreamAsArrayBuffer(stream, options?) + +Get the given `stream` as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + +```js +import {getStreamAsArrayBuffer} from 'get-stream'; + +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStreamAsArrayBuffer(readableStream)); +``` + +### getStreamAsArray(stream, options?) + +Get the given `stream` as an array. Unlike [other methods](#api), this supports [streams of objects](https://nodejs.org/api/stream.html#object-mode). + +```js +import {getStreamAsArray} from 'get-stream'; + +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStreamAsArray(readableStream)); +``` + +#### options + +Type: `object` + +##### maxBuffer + +Type: `number`\ +Default: `Infinity` + +Maximum length of the stream. If exceeded, the promise will be rejected with a `MaxBufferError`. + +Depending on the [method](#api), the length is measured with [`string.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), [`buffer.length`](https://nodejs.org/api/buffer.html#buflength), [`arrayBuffer.byteLength`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength) or [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length). + +## Errors + +If the stream errors, the returned promise will be rejected with the `error`. Any contents already read from the stream will be set to `error.bufferedData`, which is a `string`, a `Buffer`, an `ArrayBuffer` or an array depending on the [method used](#api). + +```js +import getStream from 'get-stream'; + +try { + await getStream(streamThatErrorsAtTheEnd('unicorn')); +} catch (error) { + console.log(error.bufferedData); + //=> 'unicorn' +} +``` + +## Tips + +### Alternatives + +If you do not need the [`maxBuffer`](#maxbuffer) option, [`error.bufferedData`](#errors), nor browser support, you can use the following methods instead of this package. + +#### [`streamConsumers.text()`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) + +```js +import fs from 'node:fs'; +import {text} from 'node:stream/consumers'; + +const stream = fs.createReadStream('unicorn.txt', {encoding: 'utf8'}); +console.log(await text(stream)) +``` + +#### [`streamConsumers.buffer()`](https://nodejs.org/api/webstreams.html#streamconsumersbufferstream) + +```js +import {buffer} from 'node:stream/consumers'; + +console.log(await buffer(stream)) +``` + +#### [`streamConsumers.arrayBuffer()`](https://nodejs.org/api/webstreams.html#streamconsumersarraybufferstream) + +```js +import {arrayBuffer} from 'node:stream/consumers'; + +console.log(await arrayBuffer(stream)) +``` + +#### [`readable.toArray()`](https://nodejs.org/api/stream.html#readabletoarrayoptions) + +```js +console.log(await stream.toArray()) +``` + +#### [`Array.fromAsync()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync) + +If your [environment supports it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync#browser_compatibility): + +```js +console.log(await Array.fromAsync(stream)) +``` + +### Non-UTF-8 encoding + +When all of the following conditions apply: + - [`getStream()`](#getstreamstream-options) is used (as opposed to [`getStreamAsBuffer()`](#getstreamasbufferstream-options) or [`getStreamAsArrayBuffer()`](#getstreamasarraybufferstream-options)) + - The stream is binary (not text) + - The stream's encoding is not UTF-8 (for example, it is UTF-16, hexadecimal, or Base64) + +Then the stream must be decoded using a transform stream like [`TextDecoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream) or [`b64`](https://github.com/hapijs/b64). + +```js +import getStream from 'get-stream'; + +const textDecoderStream = new TextDecoderStream('utf-16le'); +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStream(readableStream.pipeThrough(textDecoderStream))); +``` + +### Blobs + +[`getStreamAsArrayBuffer()`](#getstreamasarraybufferstream-options) can be used to create [Blobs](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + +```js +import {getStreamAsArrayBuffer} from 'get-stream'; + +const stream = fs.createReadStream('unicorn.txt'); +console.log(new Blob([await getStreamAsArrayBuffer(stream)])); +``` + +### JSON streaming + +[`getStreamAsArray()`](#getstreamasarraystream-options) can be combined with JSON streaming utilities to parse JSON incrementally. + +```js +import fs from 'node:fs'; +import {compose as composeStreams} from 'node:stream'; +import {getStreamAsArray} from 'get-stream'; +import streamJson from 'stream-json'; +import streamJsonArray from 'stream-json/streamers/StreamArray.js'; + +const stream = fs.createReadStream('big-array-of-objects.json'); +console.log(await getStreamAsArray( + composeStreams(stream, streamJson.parser(), streamJsonArray.streamArray()), +)); +``` + +## Benchmarks + +### Node.js stream (100 MB, binary) + +- `getStream()`: 142ms +- `text()`: 139ms +- `getStreamAsBuffer()`: 106ms +- `buffer()`: 83ms +- `getStreamAsArrayBuffer()`: 105ms +- `arrayBuffer()`: 81ms +- `getStreamAsArray()`: 24ms +- `stream.toArray()`: 21ms + +### Node.js stream (100 MB, text) + +- `getStream()`: 90ms +- `text()`: 89ms +- `getStreamAsBuffer()`: 127ms +- `buffer()`: 192ms +- `getStreamAsArrayBuffer()`: 129ms +- `arrayBuffer()`: 195ms +- `getStreamAsArray()`: 89ms +- `stream.toArray()`: 90ms + +### Web ReadableStream (100 MB, binary) + +- `getStream()`: 223ms +- `text()`: 221ms +- `getStreamAsBuffer()`: 182ms +- `buffer()`: 153ms +- `getStreamAsArrayBuffer()`: 171ms +- `arrayBuffer()`: 155ms +- `getStreamAsArray()`: 83ms + +### Web ReadableStream (100 MB, text) + +- `getStream()`: 141ms +- `text()`: 139ms +- `getStreamAsBuffer()`: 91ms +- `buffer()`: 80ms +- `getStreamAsArrayBuffer()`: 89ms +- `arrayBuffer()`: 81ms +- `getStreamAsArray()`: 21ms + +[Benchmarks' source file](benchmarks/index.js). + +## FAQ + +### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)? + +This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, `Buffer`, an `ArrayBuffer` or an array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package. + +## Related + +- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer +- [into-stream](https://github.com/sindresorhus/into-stream) - The opposite of this package diff --git a/web/node_modules/get-stream/source/array-buffer.js b/web/node_modules/get-stream/source/array-buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..a547405e012d8e58bd9d121ec9f15a5eb0a1b59e --- /dev/null +++ b/web/node_modules/get-stream/source/array-buffer.js @@ -0,0 +1,84 @@ +import {getStreamContents} from './contents.js'; +import {noop, throwObjectStream, getLengthProp} from './utils.js'; + +export async function getStreamAsArrayBuffer(stream, options) { + return getStreamContents(stream, arrayBufferMethods, options); +} + +const initArrayBuffer = () => ({contents: new ArrayBuffer(0)}); + +const useTextEncoder = chunk => textEncoder.encode(chunk); +const textEncoder = new TextEncoder(); + +const useUint8Array = chunk => new Uint8Array(chunk); + +const useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); + +const truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); + +// `contents` is an increasingly growing `Uint8Array`. +const addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => { + const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length); + new Uint8Array(newContents).set(convertedChunk, previousLength); + return newContents; +}; + +// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2. +// This means its last bytes are zeroes (not stream data), which need to be +// trimmed at the end with `ArrayBuffer.slice()`. +const resizeArrayBufferSlow = (contents, length) => { + if (length <= contents.byteLength) { + return contents; + } + + const arrayBuffer = new ArrayBuffer(getNewContentsLength(length)); + new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); + return arrayBuffer; +}; + +// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of +// the stream data. It does not include extraneous zeroes to trim at the end. +// The underlying `ArrayBuffer` does allocate a number of bytes that is a power +// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`. +const resizeArrayBuffer = (contents, length) => { + if (length <= contents.maxByteLength) { + contents.resize(length); + return contents; + } + + const arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)}); + new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); + return arrayBuffer; +}; + +// Retrieve the closest `length` that is both >= and a power of 2 +const getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)); + +const SCALE_FACTOR = 2; + +const finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length); + +// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available +// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead. +// eslint-disable-next-line no-warning-comments +// TODO: remove after dropping support for Node 20. +// eslint-disable-next-line no-warning-comments +// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available +const hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype; + +const arrayBufferMethods = { + init: initArrayBuffer, + convertChunk: { + string: useTextEncoder, + buffer: useUint8Array, + arrayBuffer: useUint8Array, + dataView: useUint8ArrayWithOffset, + typedArray: useUint8ArrayWithOffset, + others: throwObjectStream, + }, + getSize: getLengthProp, + truncateChunk: truncateArrayBufferChunk, + addChunk: addArrayBufferChunk, + getFinalChunk: noop, + finalize: finalizeArrayBuffer, +}; diff --git a/web/node_modules/get-stream/source/array.js b/web/node_modules/get-stream/source/array.js new file mode 100644 index 0000000000000000000000000000000000000000..468bad11917ca0e710e769a4eb737e1db47adca4 --- /dev/null +++ b/web/node_modules/get-stream/source/array.js @@ -0,0 +1,32 @@ +import {getStreamContents} from './contents.js'; +import {identity, noop, getContentsProp} from './utils.js'; + +export async function getStreamAsArray(stream, options) { + return getStreamContents(stream, arrayMethods, options); +} + +const initArray = () => ({contents: []}); + +const increment = () => 1; + +const addArrayChunk = (convertedChunk, {contents}) => { + contents.push(convertedChunk); + return contents; +}; + +const arrayMethods = { + init: initArray, + convertChunk: { + string: identity, + buffer: identity, + arrayBuffer: identity, + dataView: identity, + typedArray: identity, + others: identity, + }, + getSize: increment, + truncateChunk: noop, + addChunk: addArrayChunk, + getFinalChunk: noop, + finalize: getContentsProp, +}; diff --git a/web/node_modules/get-stream/source/buffer.js b/web/node_modules/get-stream/source/buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..7d22d78db63b667561b42ccde97574c39a9867af --- /dev/null +++ b/web/node_modules/get-stream/source/buffer.js @@ -0,0 +1,20 @@ +import {getStreamAsArrayBuffer} from './array-buffer.js'; + +export async function getStreamAsBuffer(stream, options) { + if (!('Buffer' in globalThis)) { + throw new Error('getStreamAsBuffer() is only supported in Node.js'); + } + + try { + return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options)); + } catch (error) { + if (error.bufferedData !== undefined) { + error.bufferedData = arrayBufferToNodeBuffer(error.bufferedData); + } + + throw error; + } +} + +// eslint-disable-next-line n/prefer-global/buffer +const arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer); diff --git a/web/node_modules/get-stream/source/contents.js b/web/node_modules/get-stream/source/contents.js new file mode 100644 index 0000000000000000000000000000000000000000..2ca36f2e16f40861028dbb92dd50399f47490325 --- /dev/null +++ b/web/node_modules/get-stream/source/contents.js @@ -0,0 +1,101 @@ +export const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => { + if (!isAsyncIterable(stream)) { + throw new Error('The first argument must be a Readable, a ReadableStream, or an async iterable.'); + } + + const state = init(); + state.length = 0; + + try { + for await (const chunk of stream) { + const chunkType = getChunkType(chunk); + const convertedChunk = convertChunk[chunkType](chunk, state); + appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}); + } + + appendFinalChunk({state, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}); + return finalize(state); + } catch (error) { + error.bufferedData = finalize(state); + throw error; + } +}; + +const appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => { + const convertedChunk = getFinalChunk(state); + if (convertedChunk !== undefined) { + appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}); + } +}; + +const appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => { + const chunkSize = getSize(convertedChunk); + const newLength = state.length + chunkSize; + + if (newLength <= maxBuffer) { + addNewChunk(convertedChunk, state, addChunk, newLength); + return; + } + + const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length); + + if (truncatedChunk !== undefined) { + addNewChunk(truncatedChunk, state, addChunk, maxBuffer); + } + + throw new MaxBufferError(); +}; + +const addNewChunk = (convertedChunk, state, addChunk, newLength) => { + state.contents = addChunk(convertedChunk, state, newLength); + state.length = newLength; +}; + +const isAsyncIterable = stream => typeof stream === 'object' && stream !== null && typeof stream[Symbol.asyncIterator] === 'function'; + +const getChunkType = chunk => { + const typeOfChunk = typeof chunk; + + if (typeOfChunk === 'string') { + return 'string'; + } + + if (typeOfChunk !== 'object' || chunk === null) { + return 'others'; + } + + // eslint-disable-next-line n/prefer-global/buffer + if (globalThis.Buffer?.isBuffer(chunk)) { + return 'buffer'; + } + + const prototypeName = objectToString.call(chunk); + + if (prototypeName === '[object ArrayBuffer]') { + return 'arrayBuffer'; + } + + if (prototypeName === '[object DataView]') { + return 'dataView'; + } + + if ( + Number.isInteger(chunk.byteLength) + && Number.isInteger(chunk.byteOffset) + && objectToString.call(chunk.buffer) === '[object ArrayBuffer]' + ) { + return 'typedArray'; + } + + return 'others'; +}; + +const {toString: objectToString} = Object.prototype; + +export class MaxBufferError extends Error { + name = 'MaxBufferError'; + + constructor() { + super('maxBuffer exceeded'); + } +} diff --git a/web/node_modules/get-stream/source/index.d.ts b/web/node_modules/get-stream/source/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a456ca1646c684a46793640a3b8d349bb0ac330 --- /dev/null +++ b/web/node_modules/get-stream/source/index.d.ts @@ -0,0 +1,119 @@ +import {type Readable} from 'node:stream'; +import {type Buffer} from 'node:buffer'; + +export class MaxBufferError extends Error { + readonly name: 'MaxBufferError'; + constructor(); +} + +type TextStreamItem = string | Buffer | ArrayBuffer | ArrayBufferView; +export type AnyStream = Readable | ReadableStream | AsyncIterable; + +export type Options = { + /** + Maximum length of the stream. If exceeded, the promise will be rejected with a `MaxBufferError`. + + Depending on the [method](#api), the length is measured with [`string.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), [`buffer.length`](https://nodejs.org/api/buffer.html#buflength), [`arrayBuffer.byteLength`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength) or [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length). + + @default Infinity + */ + readonly maxBuffer?: number; +}; + +/** +Get the given `stream` as a string. + +@returns The stream's contents as a promise. + +@example +``` +import fs from 'node:fs'; +import getStream from 'get-stream'; + +const stream = fs.createReadStream('unicorn.txt'); + +console.log(await getStream(stream)); +// ,,))))))));, +// __)))))))))))))), +// \|/ -\(((((''''((((((((. +// -*-==//////(('' . `)))))), +// /|\ ))| o ;-. '((((( ,(, +// ( `| / ) ;))))' ,_))^;(~ +// | | | ,))((((_ _____------~~~-. %,;(;(>';'~ +// o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ +// ; ''''```` `: `:::|\,__,%% );`'; ~ +// | _ ) / `:|`----' `-' +// ______/\/~ | / / +// /~;;.____/;;' / ___--,-( `;;;/ +// / // _;______;'------~~~~~ /;;/\ / +// // | | / ; \;;,\ +// (<_ | ; /',/-----' _> +// \_| ||_ //~;~~~~~~~~~ +// `\_| (,~~ +// \~\ +// ~~ +``` + +@example +``` +import getStream from 'get-stream'; + +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStream(readableStream)); +``` + +@example +``` +import {opendir} from 'node:fs/promises'; +import {getStreamAsArray} from 'get-stream'; + +const asyncIterable = await opendir(directory); +console.log(await getStreamAsArray(asyncIterable)); +``` +*/ +export default function getStream(stream: AnyStream, options?: Options): Promise; + +/** +Get the given `stream` as a Node.js [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer). + +@returns The stream's contents as a promise. + +@example +``` +import {getStreamAsBuffer} from 'get-stream'; + +const stream = fs.createReadStream('unicorn.png'); +console.log(await getStreamAsBuffer(stream)); +``` +*/ +export function getStreamAsBuffer(stream: AnyStream, options?: Options): Promise; + +/** +Get the given `stream` as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + +@returns The stream's contents as a promise. + +@example +``` +import {getStreamAsArrayBuffer} from 'get-stream'; + +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStreamAsArrayBuffer(readableStream)); +``` +*/ +export function getStreamAsArrayBuffer(stream: AnyStream, options?: Options): Promise; + +/** +Get the given `stream` as an array. Unlike [other methods](#api), this supports [streams of objects](https://nodejs.org/api/stream.html#object-mode). + +@returns The stream's contents as a promise. + +@example +``` +import {getStreamAsArray} from 'get-stream'; + +const {body: readableStream} = await fetch('https://example.com'); +console.log(await getStreamAsArray(readableStream)); +``` +*/ +export function getStreamAsArray(stream: AnyStream, options?: Options): Promise; diff --git a/web/node_modules/get-stream/source/index.js b/web/node_modules/get-stream/source/index.js new file mode 100644 index 0000000000000000000000000000000000000000..43c2dd4ba9110cc78978c3c5a99c629876b70ab2 --- /dev/null +++ b/web/node_modules/get-stream/source/index.js @@ -0,0 +1,5 @@ +export {getStreamAsArray} from './array.js'; +export {getStreamAsArrayBuffer} from './array-buffer.js'; +export {getStreamAsBuffer} from './buffer.js'; +export {getStreamAsString as default} from './string.js'; +export {MaxBufferError} from './contents.js'; diff --git a/web/node_modules/get-stream/source/string.js b/web/node_modules/get-stream/source/string.js new file mode 100644 index 0000000000000000000000000000000000000000..90f94b96a83087bae21dd56e02b86aadfd51875f --- /dev/null +++ b/web/node_modules/get-stream/source/string.js @@ -0,0 +1,36 @@ +import {getStreamContents} from './contents.js'; +import {identity, getContentsProp, throwObjectStream, getLengthProp} from './utils.js'; + +export async function getStreamAsString(stream, options) { + return getStreamContents(stream, stringMethods, options); +} + +const initString = () => ({contents: '', textDecoder: new TextDecoder()}); + +const useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true}); + +const addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk; + +const truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); + +const getFinalStringChunk = ({textDecoder}) => { + const finalChunk = textDecoder.decode(); + return finalChunk === '' ? undefined : finalChunk; +}; + +const stringMethods = { + init: initString, + convertChunk: { + string: identity, + buffer: useTextDecoder, + arrayBuffer: useTextDecoder, + dataView: useTextDecoder, + typedArray: useTextDecoder, + others: throwObjectStream, + }, + getSize: getLengthProp, + truncateChunk: truncateStringChunk, + addChunk: addStringChunk, + getFinalChunk: getFinalStringChunk, + finalize: getContentsProp, +}; diff --git a/web/node_modules/get-stream/source/utils.js b/web/node_modules/get-stream/source/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..af8d5e297d5cc43468e8faf7d33c41fbabf3fb95 --- /dev/null +++ b/web/node_modules/get-stream/source/utils.js @@ -0,0 +1,11 @@ +export const identity = value => value; + +export const noop = () => undefined; + +export const getContentsProp = ({contents}) => contents; + +export const throwObjectStream = chunk => { + throw new Error(`Streams in object mode are not supported: ${String(chunk)}`); +}; + +export const getLengthProp = convertedChunk => convertedChunk.length; diff --git a/web/node_modules/human-signals/LICENSE b/web/node_modules/human-signals/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..642f59b66d9b7aea984a3d57a2a42a8d50319ab5 --- /dev/null +++ b/web/node_modules/human-signals/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 2022 ehmicky + + 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/web/node_modules/human-signals/README.md b/web/node_modules/human-signals/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00d975cf0393de636bdd1ea7c2c944be3fb6ceab --- /dev/null +++ b/web/node_modules/human-signals/README.md @@ -0,0 +1,168 @@ +[![Node](https://img.shields.io/badge/-Node.js-808080?logo=node.js&colorA=404040&logoColor=66cc33)](https://www.npmjs.com/package/human-signals) +[![TypeScript](https://img.shields.io/badge/-Typed-808080?logo=typescript&colorA=404040&logoColor=0096ff)](/src/main.d.ts) +[![Codecov](https://img.shields.io/badge/-Tested%20100%25-808080?logo=codecov&colorA=404040)](https://codecov.io/gh/ehmicky/human-signals) +[![Mastodon](https://img.shields.io/badge/-Mastodon-808080.svg?logo=mastodon&colorA=404040&logoColor=9590F9)](https://fosstodon.org/@ehmicky) +[![Medium](https://img.shields.io/badge/-Medium-808080.svg?logo=medium&colorA=404040)](https://medium.com/@ehmicky) + +Human-friendly process signals. + +This is a map of known process signals with some information about each signal. + +Unlike +[`os.constants.signals`](https://nodejs.org/api/os.html#os_signal_constants) +this includes: + +- human-friendly [descriptions](#description) +- [default actions](#action), including whether they [can be prevented](#forced) +- whether the signal is [supported](#supported) by the current OS + +# Example + +```js +import { signalsByName, signalsByNumber } from 'human-signals' + +console.log(signalsByName.SIGINT) +// { +// name: 'SIGINT', +// number: 2, +// description: 'User interruption with CTRL-C', +// supported: true, +// action: 'terminate', +// forced: false, +// standard: 'ansi' +// } + +console.log(signalsByNumber[8]) +// { +// name: 'SIGFPE', +// number: 8, +// description: 'Floating point arithmetic error', +// supported: true, +// action: 'core', +// forced: false, +// standard: 'ansi' +// } +``` + +# Install + +```bash +npm install human-signals +``` + +This package works in Node.js >=16.17.0. + +This is an ES module. It must be loaded using +[an `import` or `import()` statement](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c), +not `require()`. If TypeScript is used, it must be configured to +[output ES modules](https://www.typescriptlang.org/docs/handbook/esm-node.html), +not CommonJS. + +# Usage + +## signalsByName + +_Type_: `object` + +Object whose keys are signal [names](#name) and values are +[signal objects](#signal). + +## signalsByNumber + +_Type_: `object` + +Object whose keys are signal [numbers](#number) and values are +[signal objects](#signal). + +## signal + +_Type_: `object` + +Signal object with the following properties. + +### name + +_Type_: `string` + +Standard name of the signal, for example `'SIGINT'`. + +### number + +_Type_: `number` + +Code number of the signal, for example `2`. While most `number` are +cross-platform, some are different between different OS. + +### description + +_Type_: `string` + +Human-friendly description for the signal, for example +`'User interruption with CTRL-C'`. + +### supported + +_Type_: `boolean` + +Whether the current OS can handle this signal in Node.js using +[`process.on(name, handler)`](https://nodejs.org/api/process.html#process_signal_events). + +The list of supported signals +[is OS-specific](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals). + +### action + +_Type_: `string`\ +_Enum_: `'terminate'`, `'core'`, `'ignore'`, `'pause'`, `'unpause'` + +What is the default action for this signal when it is not handled. + +### forced + +_Type_: `boolean` + +Whether the signal's default action cannot be prevented. This is `true` for +`SIGTERM`, `SIGKILL` and `SIGSTOP`. + +### standard + +_Type_: `string`\ +_Enum_: `'ansi'`, `'posix'`, `'bsd'`, `'systemv'`, `'other'` + +Which standard defined that signal. + +# Support + +For any question, _don't hesitate_ to [submit an issue on GitHub](../../issues). + +Everyone is welcome regardless of personal background. We enforce a +[Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and +inclusive environment. + +# Contributing + +This project was made with ❤️. The simplest way to give back is by starring and +sharing it online. + +If the documentation is unclear or has a typo, please click on the page's `Edit` +button (pencil icon) and suggest a correction. + +If you would like to help us fix a bug or add a new feature, please check our +[guidelines](CONTRIBUTING.md). Pull requests are welcome! + +Thanks go to our wonderful contributors: + + + + + + + + + +

ehmicky

💻 🎨 🤔 📖

electrovir

💻
+ + + + + diff --git a/web/node_modules/human-signals/build/src/core.js b/web/node_modules/human-signals/build/src/core.js new file mode 100644 index 0000000000000000000000000000000000000000..a3885ce426b4ff4c82942c764005c9bf1b0278e4 --- /dev/null +++ b/web/node_modules/human-signals/build/src/core.js @@ -0,0 +1,273 @@ + + +export const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix" +}, +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi" +}, +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix" +}, +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi" +}, +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix" +}, +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi" +}, +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd" +}, +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd" +}, +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other" +}, +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi" +}, +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true +}, +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix" +}, +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi" +}, +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix" +}, +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix" +}, +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix" +}, +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi" +}, +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other" +}, +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix" +}, +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other" +}, +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true +}, +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true +}, +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix" +}, +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix" +}, +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other" +}, +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix" +}, +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd" +}, +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd" +}, +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd" +}, +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd" +}, +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd" +}, +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd" +}, +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other" +}, +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other" +}, +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other" +}, +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv" +}, +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other" +}, +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other" +}]; \ No newline at end of file diff --git a/web/node_modules/human-signals/build/src/main.d.ts b/web/node_modules/human-signals/build/src/main.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..864d501ad848380509c816ff11363dd5e4000ae2 --- /dev/null +++ b/web/node_modules/human-signals/build/src/main.d.ts @@ -0,0 +1,73 @@ +/** + * What is the default action for this signal when it is not handled. + */ +export type SignalAction = 'terminate' | 'core' | 'ignore' | 'pause' | 'unpause' + +/** + * Which standard defined that signal. + */ +export type SignalStandard = 'ansi' | 'posix' | 'bsd' | 'systemv' | 'other' + +/** + * Standard name of the signal, for example 'SIGINT'. + */ +export type SignalName = `SIG${string}` + +/** + * Code number of the signal, for example 2. + * While most number are cross-platform, some are different between different + * OS. + */ +export type SignalNumber = number + +export interface Signal { + /** + * Standard name of the signal, for example 'SIGINT'. + */ + name: SignalName + + /** + * Code number of the signal, for example 2. + * While most number are cross-platform, some are different between different + * OS. + */ + number: SignalNumber + + /** + * Human-friendly description for the signal, for example + * 'User interruption with CTRL-C'. + */ + description: string + + /** + * Whether the current OS can handle this signal in Node.js using + * `process.on(name, handler)`. The list of supported signals is OS-specific. + */ + supported: boolean + + /** + * What is the default action for this signal when it is not handled. + */ + action: SignalAction + + /** + * Whether the signal's default action cannot be prevented. + * This is true for SIGTERM, SIGKILL and SIGSTOP. + */ + forced: boolean + + /** + * Which standard defined that signal. + */ + standard: SignalStandard +} + +/** + * Object whose keys are signal names and values are signal objects. + */ +export declare const signalsByName: { [signalName: SignalName]: Signal } + +/** + * Object whose keys are signal numbers and values are signal objects. + */ +export declare const signalsByNumber: { [signalNumber: SignalNumber]: Signal } diff --git a/web/node_modules/human-signals/build/src/main.js b/web/node_modules/human-signals/build/src/main.js new file mode 100644 index 0000000000000000000000000000000000000000..1c97801f92a73957f4806314cc5a8640f3851ec3 --- /dev/null +++ b/web/node_modules/human-signals/build/src/main.js @@ -0,0 +1,70 @@ +import{constants}from"node:os"; + +import{SIGRTMAX}from"./realtime.js"; +import{getSignals}from"./signals.js"; + + + +const getSignalsByName=()=>{ +const signals=getSignals(); +return Object.fromEntries(signals.map(getSignalByName)) +}; + +const getSignalByName=({ +name, +number, +description, +supported, +action, +forced, +standard +})=>[name,{name,number,description,supported,action,forced,standard}]; + +export const signalsByName=getSignalsByName(); + + + + +const getSignalsByNumber=()=>{ +const signals=getSignals(); +const length=SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals) +); +return Object.assign({},...signalsA) +}; + +const getSignalByNumber=(number,signals)=>{ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return{} +} + +const{name,description,supported,action,forced,standard}=signal; +return{ +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard +} +} +}; + + + +const findSignalByNumber=(number,signals)=>{ +const signal=signals.find(({name})=>constants.signals[name]===number); + +if(signal!==undefined){ +return signal +} + +return signals.find((signalA)=>signalA.number===number) +}; + +export const signalsByNumber=getSignalsByNumber(); \ No newline at end of file diff --git a/web/node_modules/human-signals/build/src/realtime.js b/web/node_modules/human-signals/build/src/realtime.js new file mode 100644 index 0000000000000000000000000000000000000000..76ab69dd2b39cb151bc011ff9a059f1d6904496a --- /dev/null +++ b/web/node_modules/human-signals/build/src/realtime.js @@ -0,0 +1,16 @@ + +export const getRealtimeSignals=()=>{ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal) +}; + +const getRealtimeSignal=(value,index)=>({ +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix" +}); + +const SIGRTMIN=34; +export const SIGRTMAX=64; \ No newline at end of file diff --git a/web/node_modules/human-signals/build/src/signals.js b/web/node_modules/human-signals/build/src/signals.js new file mode 100644 index 0000000000000000000000000000000000000000..14e4c730b4e69366e008fd32bc4c2825b3fcbb03 --- /dev/null +++ b/web/node_modules/human-signals/build/src/signals.js @@ -0,0 +1,34 @@ +import{constants}from"node:os"; + +import{SIGNALS}from"./core.js"; +import{getRealtimeSignals}from"./realtime.js"; + + + +export const getSignals=()=>{ +const realtimeSignals=getRealtimeSignals(); +const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals +}; + + + + + + + +const normalizeSignal=({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard +})=>{ +const{ +signals:{[name]:constantSignal} +}=constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return{name,number,description,supported,action,forced,standard} +}; \ No newline at end of file diff --git a/web/node_modules/human-signals/package.json b/web/node_modules/human-signals/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bb614d6c7075afb41bdd27778293d84a775d4b74 --- /dev/null +++ b/web/node_modules/human-signals/package.json @@ -0,0 +1,61 @@ +{ + "name": "human-signals", + "version": "5.0.0", + "type": "module", + "exports": { + "types": "./build/src/main.d.ts", + "default": "./build/src/main.js" + }, + "main": "./build/src/main.js", + "types": "./build/src/main.d.ts", + "files": [ + "build/src/**/*.{js,json,d.ts}", + "!build/src/**/*.test.js", + "!build/src/{helpers,fixtures}" + ], + "sideEffects": false, + "scripts": { + "test": "gulp test" + }, + "description": "Human-friendly process signals", + "keywords": [ + "signal", + "signals", + "handlers", + "error-handling", + "interrupts", + "sigterm", + "sigint", + "irq", + "process", + "exit", + "exit-code", + "status", + "operating-system", + "es6", + "javascript", + "typescript", + "linux", + "macos", + "windows", + "nodejs" + ], + "license": "Apache-2.0", + "homepage": "https://www.github.com/ehmicky/human-signals", + "repository": "ehmicky/human-signals", + "bugs": { + "url": "https://github.com/ehmicky/human-signals/issues" + }, + "author": "ehmicky (https://github.com/ehmicky)", + "directories": { + "lib": "src" + }, + "devDependencies": { + "@ehmicky/dev-tasks": "^2.0.80", + "ajv": "^8.12.0", + "test-each": "^6.0.0" + }, + "engines": { + "node": ">=16.17.0" + } +} diff --git a/web/node_modules/is-stream/index.d.ts b/web/node_modules/is-stream/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df994e096ab265f403876f3c514739256216cfa9 --- /dev/null +++ b/web/node_modules/is-stream/index.d.ts @@ -0,0 +1,81 @@ +import { + Stream, + Writable as WritableStream, + Readable as ReadableStream, + Duplex as DuplexStream, + Transform as TransformStream, +} from 'node:stream'; + +/** +@returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +@example +``` +import fs from 'node:fs'; +import {isStream} from 'is-stream'; + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` +*/ +export function isStream(stream: unknown): stream is Stream; + +/** +@returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +@example +``` +import fs from 'node:fs'; +import {isWritableStream} from 'is-stream'; + +isWritableStream(fs.createWriteStrem('unicorn.txt')); +//=> true +``` +*/ +export function isWritableStream(stream: unknown): stream is WritableStream; + +/** +@returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +@example +``` +import fs from 'node:fs'; +import {isReadableStream} from 'is-stream'; + +isReadableStream(fs.createReadStream('unicorn.png')); +//=> true +``` +*/ +export function isReadableStream(stream: unknown): stream is ReadableStream; + +/** +@returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +@example +``` +import {Duplex as DuplexStream} from 'node:stream'; +import {isDuplexStream} from 'is-stream'; + +isDuplexStream(new DuplexStream()); +//=> true +``` +*/ +export function isDuplexStream(stream: unknown): stream is DuplexStream; + +/** +@returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + +@example +``` +import fs from 'node:fs'; +import StringifyStream from 'streaming-json-stringify'; +import {isTransformStream} from 'is-stream'; + +isTransformStream(StringifyStream()); +//=> true +``` +*/ +export function isTransformStream(stream: unknown): stream is TransformStream; diff --git a/web/node_modules/is-stream/index.js b/web/node_modules/is-stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..887e601e028c83438c2c89de9c3591ecb33b44f9 --- /dev/null +++ b/web/node_modules/is-stream/index.js @@ -0,0 +1,29 @@ +export function isStream(stream) { + return stream !== null + && typeof stream === 'object' + && typeof stream.pipe === 'function'; +} + +export function isWritableStream(stream) { + return isStream(stream) + && stream.writable !== false + && typeof stream._write === 'function' + && typeof stream._writableState === 'object'; +} + +export function isReadableStream(stream) { + return isStream(stream) + && stream.readable !== false + && typeof stream._read === 'function' + && typeof stream._readableState === 'object'; +} + +export function isDuplexStream(stream) { + return isWritableStream(stream) + && isReadableStream(stream); +} + +export function isTransformStream(stream) { + return isDuplexStream(stream) + && typeof stream._transform === 'function'; +} diff --git a/web/node_modules/is-stream/license b/web/node_modules/is-stream/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/is-stream/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/web/node_modules/is-stream/package.json b/web/node_modules/is-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..47d5761f24253b814b2862727bbc152b982894b9 --- /dev/null +++ b/web/node_modules/is-stream/package.json @@ -0,0 +1,44 @@ +{ + "name": "is-stream", + "version": "3.0.0", + "description": "Check if something is a Node.js stream", + "license": "MIT", + "repository": "sindresorhus/is-stream", + "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.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "stream", + "type", + "streams", + "writable", + "readable", + "duplex", + "transform", + "check", + "detect", + "is" + ], + "devDependencies": { + "@types/node": "^16.4.13", + "ava": "^3.15.0", + "tempy": "^1.0.1", + "tsd": "^0.17.0", + "xo": "^0.44.0" + } +} diff --git a/web/node_modules/is-stream/readme.md b/web/node_modules/is-stream/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..c6f8c1b2cba365e8af05a56f6b0a9e42afa30484 --- /dev/null +++ b/web/node_modules/is-stream/readme.md @@ -0,0 +1,60 @@ +# is-stream + +> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html) + +## Install + +``` +$ npm install is-stream +``` + +## Usage + +```js +import fs from 'node:fs'; +import {isStream} from 'is-stream'; + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` + +## API + +### isStream(stream) + +Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +#### isWritableStream(stream) + +Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +#### isReadableStream(stream) + +Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +#### isDuplexStream(stream) + +Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +#### isTransformStream(stream) + +Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + +## Related + +- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream + +--- + +
+ + 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/web/node_modules/isexe/.npmignore b/web/node_modules/isexe/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..c1cb757acf58a46c2c962c963c2d965f1d0eccec --- /dev/null +++ b/web/node_modules/isexe/.npmignore @@ -0,0 +1,2 @@ +.nyc_output/ +coverage/ diff --git a/web/node_modules/isexe/LICENSE b/web/node_modules/isexe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/web/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/web/node_modules/isexe/README.md b/web/node_modules/isexe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35769e84408ce9076572c84e17d4a3f3eb611d08 --- /dev/null +++ b/web/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/web/node_modules/isexe/index.js b/web/node_modules/isexe/index.js new file mode 100644 index 0000000000000000000000000000000000000000..553fb32b119bdf2efaeffeefe1bef4bfd10f3e43 --- /dev/null +++ b/web/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/web/node_modules/isexe/mode.js b/web/node_modules/isexe/mode.js new file mode 100644 index 0000000000000000000000000000000000000000..1995ea4a06aec4c1506509b11f8e9ae941b86439 --- /dev/null +++ b/web/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/web/node_modules/isexe/package.json b/web/node_modules/isexe/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e452689442f2018bfa2b9ef3885cf4ce6a6e7912 --- /dev/null +++ b/web/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/web/node_modules/isexe/test/basic.js b/web/node_modules/isexe/test/basic.js new file mode 100644 index 0000000000000000000000000000000000000000..d926df64b902457c1487bb29e3258e7eca9c6753 --- /dev/null +++ b/web/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/web/node_modules/isexe/windows.js b/web/node_modules/isexe/windows.js new file mode 100644 index 0000000000000000000000000000000000000000..34996734d8ef3921c9590def676d79c58c06b61c --- /dev/null +++ b/web/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/web/node_modules/js-tokens/LICENSE b/web/node_modules/js-tokens/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f07e1ac1eb7cf137e51467c483e54bfd66549811 --- /dev/null +++ b/web/node_modules/js-tokens/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024 Simon Lydell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/web/node_modules/js-tokens/README.md b/web/node_modules/js-tokens/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ee52150ef85c45d9644c52129610a63aa0779b82 --- /dev/null +++ b/web/node_modules/js-tokens/README.md @@ -0,0 +1,14 @@ +# js-tokens + +The tiny, regex powered, lenient, _almost_ spec-compliant JavaScript tokenizer that never fails. + +```js +const jsTokens = require("js-tokens"); + +const jsString = 'JSON.stringify({k:3.14**2}, null /*replacer*/, "\\t")'; + +Array.from(jsTokens(jsString), (token) => token.value).join("|"); +// JSON|.|stringify|(|{|k|:|3.14|**|2|}|,| |null| |/*replacer*/|,| |"\t"|) +``` + +**[➡️ Full readme](https://github.com/lydell/js-tokens/)** \ No newline at end of file diff --git a/web/node_modules/js-tokens/index.d.ts b/web/node_modules/js-tokens/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f9da0fac1214980c17476a554bb1a7916490067 --- /dev/null +++ b/web/node_modules/js-tokens/index.d.ts @@ -0,0 +1,36 @@ +export declare type Token = + | { type: "StringLiteral"; value: string; closed: boolean } + | { type: "NoSubstitutionTemplate"; value: string; closed: boolean } + | { type: "TemplateHead"; value: string } + | { type: "TemplateMiddle"; value: string } + | { type: "TemplateTail"; value: string; closed: boolean } + | { type: "RegularExpressionLiteral"; value: string; closed: boolean } + | { type: "MultiLineComment"; value: string; closed: boolean } + | { type: "SingleLineComment"; value: string } + | { type: "IdentifierName"; value: string } + | { type: "PrivateIdentifier"; value: string } + | { type: "NumericLiteral"; value: string } + | { type: "Punctuator"; value: string } + | { type: "WhiteSpace"; value: string } + | { type: "LineTerminatorSequence"; value: string } + | { type: "Invalid"; value: string }; + +export declare type JSXToken = + | { type: "JSXString"; value: string; closed: boolean } + | { type: "JSXText"; value: string } + | { type: "JSXIdentifier"; value: string } + | { type: "JSXPunctuator"; value: string } + | { type: "JSXInvalid"; value: string }; + +declare function jsTokens( + input: string, + options: { jsx: true } +): Iterable; + +declare function jsTokens( + input: string, + options?: { jsx?: boolean } +): Iterable; + +// @ts-expect-error TypeScript complains about _both_ exporting types _and_ using `export =` but it seems to work fine in practice. +export = jsTokens; diff --git a/web/node_modules/js-tokens/index.js b/web/node_modules/js-tokens/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ded4ddb868f3cc8fffe68c93a0241df76de26977 --- /dev/null +++ b/web/node_modules/js-tokens/index.js @@ -0,0 +1,388 @@ +// Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell +// License: MIT. +var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace, jsTokens; +RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu; +Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; +Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu; +StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y; +NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; +Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y; +WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu; +LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; +MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y; +SingleLineComment = /\/\/.*/y; +JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; +JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu; +JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y; +JSXText = /[^<>{}]+/y; +TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; +TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; +KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; +KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; +Newline = RegExp(LineTerminatorSequence.source); +module.exports = jsTokens = function*(input, {jsx = false} = {}) { + var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; + ({length} = input); + lastIndex = 0; + lastSignificantToken = ""; + stack = [ + {tag: "JS"} + ]; + braces = []; + parenNesting = 0; + postfixIncDec = false; + while (lastIndex < length) { + mode = stack[stack.length - 1]; + switch (mode.tag) { + case "JS": + case "JSNonExpressionParen": + case "InterpolationInTemplate": + case "InterpolationInJSX": + if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + RegularExpressionLiteral.lastIndex = lastIndex; + if (match = RegularExpressionLiteral.exec(input)) { + lastIndex = RegularExpressionLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "RegularExpressionLiteral", + value: match[0], + closed: match[1] !== void 0 && match[1] !== "\\" + }); + continue; + } + } + Punctuator.lastIndex = lastIndex; + if (match = Punctuator.exec(input)) { + punctuator = match[0]; + nextLastIndex = Punctuator.lastIndex; + nextLastSignificantToken = punctuator; + switch (punctuator) { + case "(": + if (lastSignificantToken === "?NonExpressionParenKeyword") { + stack.push({ + tag: "JSNonExpressionParen", + nesting: parenNesting + }); + } + parenNesting++; + postfixIncDec = false; + break; + case ")": + parenNesting--; + postfixIncDec = true; + if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { + stack.pop(); + nextLastSignificantToken = "?NonExpressionParenEnd"; + postfixIncDec = false; + } + break; + case "{": + Punctuator.lastIndex = 0; + isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); + braces.push(isExpression); + postfixIncDec = false; + break; + case "}": + switch (mode.tag) { + case "InterpolationInTemplate": + if (braces.length === mode.nesting) { + Template.lastIndex = lastIndex; + match = Template.exec(input); + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + postfixIncDec = false; + yield ({ + type: "TemplateMiddle", + value: match[0] + }); + } else { + stack.pop(); + postfixIncDec = true; + yield ({ + type: "TemplateTail", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "InterpolationInJSX": + if (braces.length === mode.nesting) { + stack.pop(); + lastIndex += 1; + lastSignificantToken = "}"; + yield ({ + type: "JSXPunctuator", + value: "}" + }); + continue; + } + } + postfixIncDec = braces.pop(); + nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; + break; + case "]": + postfixIncDec = true; + break; + case "++": + case "--": + nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; + break; + case "<": + if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + stack.push({tag: "JSXTag"}); + lastIndex += 1; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: punctuator + }); + continue; + } + postfixIncDec = false; + break; + default: + postfixIncDec = false; + } + lastIndex = nextLastIndex; + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "Punctuator", + value: punctuator + }); + continue; + } + Identifier.lastIndex = lastIndex; + if (match = Identifier.exec(input)) { + lastIndex = Identifier.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "for": + case "if": + case "while": + case "with": + if (lastSignificantToken !== "." && lastSignificantToken !== "?.") { + nextLastSignificantToken = "?NonExpressionParenKeyword"; + } + } + lastSignificantToken = nextLastSignificantToken; + postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); + yield ({ + type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", + value: match[0] + }); + continue; + } + StringLiteral.lastIndex = lastIndex; + if (match = StringLiteral.exec(input)) { + lastIndex = StringLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "StringLiteral", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + NumericLiteral.lastIndex = lastIndex; + if (match = NumericLiteral.exec(input)) { + lastIndex = NumericLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "NumericLiteral", + value: match[0] + }); + continue; + } + Template.lastIndex = lastIndex; + if (match = Template.exec(input)) { + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + stack.push({ + tag: "InterpolationInTemplate", + nesting: braces.length + }); + postfixIncDec = false; + yield ({ + type: "TemplateHead", + value: match[0] + }); + } else { + postfixIncDec = true; + yield ({ + type: "NoSubstitutionTemplate", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "JSXTag": + case "JSXTagEnd": + JSXPunctuator.lastIndex = lastIndex; + if (match = JSXPunctuator.exec(input)) { + lastIndex = JSXPunctuator.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "<": + stack.push({tag: "JSXTag"}); + break; + case ">": + stack.pop(); + if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { + nextLastSignificantToken = "?JSX"; + postfixIncDec = true; + } else { + stack.push({tag: "JSXChildren"}); + } + break; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + nextLastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + break; + case "/": + if (lastSignificantToken === "<") { + stack.pop(); + if (stack[stack.length - 1].tag === "JSXChildren") { + stack.pop(); + } + stack.push({tag: "JSXTagEnd"}); + } + } + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "JSXPunctuator", + value: match[0] + }); + continue; + } + JSXIdentifier.lastIndex = lastIndex; + if (match = JSXIdentifier.exec(input)) { + lastIndex = JSXIdentifier.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXIdentifier", + value: match[0] + }); + continue; + } + JSXString.lastIndex = lastIndex; + if (match = JSXString.exec(input)) { + lastIndex = JSXString.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXString", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + break; + case "JSXChildren": + JSXText.lastIndex = lastIndex; + if (match = JSXText.exec(input)) { + lastIndex = JSXText.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXText", + value: match[0] + }); + continue; + } + switch (input[lastIndex]) { + case "<": + stack.push({tag: "JSXTag"}); + lastIndex++; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: "<" + }); + continue; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + lastIndex++; + lastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + yield ({ + type: "JSXPunctuator", + value: "{" + }); + continue; + } + } + WhiteSpace.lastIndex = lastIndex; + if (match = WhiteSpace.exec(input)) { + lastIndex = WhiteSpace.lastIndex; + yield ({ + type: "WhiteSpace", + value: match[0] + }); + continue; + } + LineTerminatorSequence.lastIndex = lastIndex; + if (match = LineTerminatorSequence.exec(input)) { + lastIndex = LineTerminatorSequence.lastIndex; + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + yield ({ + type: "LineTerminatorSequence", + value: match[0] + }); + continue; + } + MultiLineComment.lastIndex = lastIndex; + if (match = MultiLineComment.exec(input)) { + lastIndex = MultiLineComment.lastIndex; + if (Newline.test(match[0])) { + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + } + yield ({ + type: "MultiLineComment", + value: match[0], + closed: match[1] !== void 0 + }); + continue; + } + SingleLineComment.lastIndex = lastIndex; + if (match = SingleLineComment.exec(input)) { + lastIndex = SingleLineComment.lastIndex; + postfixIncDec = false; + yield ({ + type: "SingleLineComment", + value: match[0] + }); + continue; + } + firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); + lastIndex += firstCodePoint.length; + lastSignificantToken = firstCodePoint; + postfixIncDec = false; + yield ({ + type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", + value: firstCodePoint + }); + } + return void 0; +}; diff --git a/web/node_modules/js-tokens/package.json b/web/node_modules/js-tokens/package.json new file mode 100644 index 0000000000000000000000000000000000000000..575595b8f60f712858d96dbdb37c589dcd8606a2 --- /dev/null +++ b/web/node_modules/js-tokens/package.json @@ -0,0 +1,22 @@ +{ + "name": "js-tokens", + "version": "8.0.3", + "author": "Simon Lydell", + "license": "MIT", + "description": "Tiny JavaScript tokenizer.", + "repository": "lydell/js-tokens", + "type": "commonjs", + "exports": "./index.js", + "keywords": [ + "JavaScript", + "js", + "ECMAScript", + "es", + "token", + "tokens", + "tokenize", + "tokenizer", + "regex", + "regexp" + ] +} diff --git a/web/node_modules/jsonc-parser/CHANGELOG.md b/web/node_modules/jsonc-parser/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b43a083a2f98daed446a16861955c79997ffa1d1 --- /dev/null +++ b/web/node_modules/jsonc-parser/CHANGELOG.md @@ -0,0 +1,72 @@ + +3.2.0 2022-08-30 +================= +- update the version of the bundled Javascript files to `es2020`. +- include all `const enum` values in the bundled JavaScript files (`ScanError`, `SyntaxKind`, `ParseErrorCode`). + +3.1.0 2022-07-07 +================== + * added new API `FormattingOptions.keepLines` : It leaves the initial line positions in the formatting. + +3.0.0 2020-11-13 +================== + * fixed API spec for `parseTree`. Can return `undefine` for empty input. + * added new API `FormattingOptions.insertFinalNewline`. + + +2.3.0 2020-07-03 +================== + * new API `ModificationOptions.isArrayInsertion`: If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then `modify` will insert a new item at that location instead of overwriting its contents. + * `ModificationOptions.formattingOptions` is now optional. If not set, newly inserted content will not be formatted. + + +2.2.0 2019-10-25 +================== + * added `ParseOptions.allowEmptyContent`. Default is `false`. + * new API `getNodeType`: Returns the type of a value returned by parse. + * `parse`: Fix issue with empty property name + +2.1.0 2019-03-29 +================== + * `JSONScanner` and `JSONVisitor` return lineNumber / character. + +2.0.0 2018-04-12 +================== + * renamed `Node.columnOffset` to `Node.colonOffset` + * new API `getNodePath`: Gets the JSON path of the given JSON DOM node + * new API `findNodeAtOffset`: Finds the most inner node at the given offset. If `includeRightBound` is set, also finds nodes that end at the given offset. + +1.0.3 2018-03-07 +================== + * provide ems modules + +1.0.2 2018-03-05 +================== + * added the `visit.onComment` API, reported when comments are allowed. + * added the `ParseErrorCode.InvalidCommentToken` enum value, reported when comments are disallowed. + +1.0.1 +================== + * added the `format` API: computes edits to format a JSON document. + * added the `modify` API: computes edits to insert, remove or replace a property or value in a JSON document. + * added the `allyEdits` API: applies edits to a document + +1.0.0 +================== + * remove nls dependency (remove `getParseErrorMessage`) + +0.4.2 / 2017-05-05 +================== + * added `ParseError.offset` & `ParseError.length` + +0.4.1 / 2017-04-02 +================== + * added `ParseOptions.allowTrailingComma` + +0.4.0 / 2017-02-23 +================== + * fix for `getLocation`. Now `getLocation` inside an object will always return a property from inside that property. Can be empty string if the object has no properties or if the offset is before a actual property `{ "a": { | }} will return location ['a', ' ']` + +0.3.0 / 2017-01-17 +================== + * Updating to typescript 2.0 \ No newline at end of file diff --git a/web/node_modules/jsonc-parser/LICENSE.md b/web/node_modules/jsonc-parser/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..f54f08dcc2388136d625d8edc446f156de8e2432 --- /dev/null +++ b/web/node_modules/jsonc-parser/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Microsoft + +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/web/node_modules/jsonc-parser/README.md b/web/node_modules/jsonc-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5fd92d9e9310a6e4ed2309fea25b2be5063ad2e5 --- /dev/null +++ b/web/node_modules/jsonc-parser/README.md @@ -0,0 +1,362 @@ +# jsonc-parser +Scanner and parser for JSON with comments. + +[![npm Package](https://img.shields.io/npm/v/jsonc-parser.svg?style=flat-square)](https://www.npmjs.org/package/jsonc-parser) +[![NPM Downloads](https://img.shields.io/npm/dm/jsonc-parser.svg)](https://npmjs.org/package/jsonc-parser) +[![Build Status](https://github.com/microsoft/node-jsonc-parser/workflows/Tests/badge.svg)](https://github.com/microsoft/node-jsonc-parser/workflows/Tests) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +Why? +---- +JSONC is JSON with JavaScript style comments. This node module provides a scanner and fault tolerant parser that can process JSONC but is also useful for standard JSON. + - the *scanner* tokenizes the input string into tokens and token offsets + - the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values. + - the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values. + - the *parse* function evaluates the JavaScript object represented by JSON string in a fault tolerant fashion. + - the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document. + - the *findNodeAtLocation* API finds the node at a given location path in a JSON DOM. + - the *format* API computes edits to format a JSON document. + - the *modify* API computes edits to insert, remove or replace a property or value in a JSON document. + - the *applyEdits* API applies edits to a document. + +Installation +------------ + +``` +npm install --save jsonc-parser +``` + +API +--- + +### Scanner: +```typescript + +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +export function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner; + +/** + * The scanner object, representing a JSON scanner at a position in the input string. + */ +export interface JSONScanner { + /** + * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token. + */ + setPosition(pos: number): any; + /** + * Read the next token. Returns the token code. + */ + scan(): SyntaxKind; + /** + * Returns the zero-based current scan position, which is after the last read token. + */ + getPosition(): number; + /** + * Returns the last read token. + */ + getToken(): SyntaxKind; + /** + * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false. + */ + getTokenValue(): string; + /** + * The zero-based start offset of the last read token. + */ + getTokenOffset(): number; + /** + * The length of the last read token. + */ + getTokenLength(): number; + /** + * The zero-based start line number of the last read token. + */ + getTokenStartLine(): number; + /** + * The zero-based start character (column) of the last read token. + */ + getTokenStartCharacter(): number; + /** + * An error code of the last scan. + */ + getTokenError(): ScanError; +} +``` + +### Parser: +```typescript + +export interface ParseOptions { + disallowComments?: boolean; + allowTrailingComma?: boolean; + allowEmptyContent?: boolean; +} +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore always check the errors list to find out if the input was valid. + */ +export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any; + +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any; + +/** + * Visitor called by {@linkcode visit} when parsing JSON. + * + * The visitor functions have the following common parameters: + * - `offset`: Global offset within the JSON document, starting at 0 + * - `startLine`: Line number, starting at 0 + * - `startCharacter`: Start character (column) within the current line, starting at 0 + * + * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the + * current `JSONPath` within the document. + */ +export interface JSONVisitor { + /** + * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. + */ + onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + + /** + * Invoked when a property is encountered. The offset and length represent the location of the property name. + * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the + * property name yet. + */ + onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. + */ + onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. + */ + onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. + */ + onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. + */ + onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. + */ + onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment. + */ + onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked on an error. + */ + onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void; +} + +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node | undefined; + +export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null"; +export interface Node { + type: NodeType; + value?: any; + offset: number; + length: number; + colonOffset?: number; + parent?: Node; + children?: Node[]; +} + +``` + +### Utilities: +```typescript +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +export declare function stripComments(text: string, replaceCh?: string): string; + +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +export declare function getLocation(text: string, position: number): Location; + +/** + * A {@linkcode JSONPath} segment. Either a string representing an object property name + * or a number (starting at 0) for array indices. + */ +export declare type Segment = string | number; +export declare type JSONPath = Segment[]; +export interface Location { + /** + * The previous property key or literal value (string, number, boolean or null) or undefined. + */ + previousNode?: Node; + /** + * The path describing the location in the JSON document. The path consists of a sequence strings + * representing an object property or numbers for array indices. + */ + path: JSONPath; + /** + * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). + * '*' will match a single segment, of any property name or index. + * '**' will match a sequence of segments or no segment, of any property name or index. + */ + matches: (patterns: JSONPath) => boolean; + /** + * If set, the location's offset is at a property key. + */ + isAtPropertyKey: boolean; +} + +/** + * Finds the node at the given path in a JSON DOM. + */ +export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined; + +/** + * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +export function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined; + +/** + * Gets the JSON path of the given JSON DOM node + */ +export function getNodePath(node: Node): JSONPath; + +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +export function getNodeValue(node: Node): any; + +/** + * Computes the edit operations needed to format a JSON document. + * + * @param documentText The input text + * @param range The range to format or `undefined` to format the full content + * @param options The formatting options + * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export function format(documentText: string, range: Range, options: FormattingOptions): EditResult; + +/** + * Computes the edit operations needed to modify a value in the JSON document. + * + * @param documentText The input text + * @param path The path of the value to change. The path represents either to the document root, a property or an array item. + * If the path points to an non-existing property or item, it will be created. + * @param value The new value for the specified property or item. If the value is undefined, + * the property or item will be removed. + * @param options Options + * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult; + +/** + * Applies edits to an input string. + * @param text The input text + * @param edits Edit operations following the format described in {@linkcode EditResult}. + * @returns The text with the applied edits. + * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. + */ +export function applyEdits(text: string, edits: EditResult): string; + +/** + * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation. + * It consist of one or more edits describing insertions, replacements or removals of text segments. + * * The offsets of the edits refer to the original state of the document. + * * No two edits change or remove the same range of text in the original document. + * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. + * * The order in the array defines which edit is applied first. + * To apply an edit result use {@linkcode applyEdits}. + * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data. + */ +export type EditResult = Edit[]; + +/** + * Represents a text modification + */ +export interface Edit { + /** + * The start offset of the modification. + */ + offset: number; + /** + * The length of the modification. Must not be negative. Empty length represents an *insert*. + */ + length: number; + /** + * The new content. Empty content represents a *remove*. + */ + content: string; +} + +/** + * A text range in the document +*/ +export interface Range { + /** + * The start offset of the range. + */ + offset: number; + /** + * The length of the range. Must not be negative. + */ + length: number; +} + +/** + * Options used by {@linkcode format} when computing the formatting edit operations + */ +export interface FormattingOptions { + /** + * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent? + */ + tabSize: number; + /** + * Is indentation based on spaces? + */ + insertSpaces: boolean; + /** + * The default 'end of line' character + */ + eol: string; +} + +/** + * Options used by {@linkcode modify} when computing the modification edit operations + */ +export interface ModificationOptions { + /** + * Formatting options. If undefined, the newly inserted code will be inserted unformatted. + */ + formattingOptions?: FormattingOptions; + /** + * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then + * {@linkcode modify} will insert a new item at that location instead of overwriting its contents. + */ + isArrayInsertion?: boolean; + /** + * Optional function to define the insertion index given an existing list of properties. + */ + getInsertionIndex?: (properties: string[]) => number; +} +``` + + +License +------- + +(MIT License) + +Copyright 2018, Microsoft diff --git a/web/node_modules/jsonc-parser/SECURITY.md b/web/node_modules/jsonc-parser/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f7b89984f0fb5dd204028bc525e19eefc0859f4f --- /dev/null +++ b/web/node_modules/jsonc-parser/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). + + \ No newline at end of file diff --git a/web/node_modules/jsonc-parser/lib/esm/impl/edit.js b/web/node_modules/jsonc-parser/lib/esm/impl/edit.js new file mode 100644 index 0000000000000000000000000000000000000000..4114d525b7fa2db6824ee4c3351c58aa4c6a4876 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/impl/edit.js @@ -0,0 +1,185 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +import { format, isEOL } from './format'; +import { parseTree, findNodeAtLocation } from './parser'; +export function removeProperty(text, path, options) { + return setProperty(text, path, void 0, options); +} +export function setProperty(text, originalPath, value, options) { + const path = originalPath.slice(); + const errors = []; + const root = parseTree(text, errors); + let parent = void 0; + let lastSegment = void 0; + while (path.length > 0) { + lastSegment = path.pop(); + parent = findNodeAtLocation(root, path); + if (parent === void 0 && value !== void 0) { + if (typeof lastSegment === 'string') { + value = { [lastSegment]: value }; + } + else { + value = [value]; + } + } + else { + break; + } + } + if (!parent) { + // empty document + if (value === void 0) { // delete + throw new Error('Can not delete in empty document'); + } + return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); + } + else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { + const existing = findNodeAtLocation(parent, [lastSegment]); + if (existing !== void 0) { + if (value === void 0) { // delete + if (!existing.parent) { + throw new Error('Malformed AST'); + } + const propertyIndex = parent.children.indexOf(existing.parent); + let removeBegin; + let removeEnd = existing.parent.offset + existing.parent.length; + if (propertyIndex > 0) { + // remove the comma of the previous node + let previous = parent.children[propertyIndex - 1]; + removeBegin = previous.offset + previous.length; + } + else { + removeBegin = parent.offset + 1; + if (parent.children.length > 1) { + // remove the comma of the next node + let next = parent.children[1]; + removeEnd = next.offset; + } + } + return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); + } + else { + // set value of existing property + return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); + } + } + else { + if (value === void 0) { // delete + return []; // property does not exist, nothing to do + } + const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; + const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length; + let edit; + if (index > 0) { + let previous = parent.children[index - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + else if (parent.children.length === 0) { + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; + } + else { + edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; + } + return withFormatting(text, edit, options); + } + } + else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { + const insertIndex = lastSegment; + if (insertIndex === -1) { + // Insert + const newProperty = `${JSON.stringify(value)}`; + let edit; + if (parent.children.length === 0) { + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; + } + else { + const previous = parent.children[parent.children.length - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + return withFormatting(text, edit, options); + } + else if (value === void 0 && parent.children.length >= 0) { + // Removal + const removalIndex = lastSegment; + const toRemove = parent.children[removalIndex]; + let edit; + if (parent.children.length === 1) { + // only item + edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; + } + else if (parent.children.length - 1 === removalIndex) { + // last item + let previous = parent.children[removalIndex - 1]; + let offset = previous.offset + previous.length; + let parentEndOffset = parent.offset + parent.length; + edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; + } + else { + edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; + } + return withFormatting(text, edit, options); + } + else if (value !== void 0) { + let edit; + const newProperty = `${JSON.stringify(value)}`; + if (!options.isArrayInsertion && parent.children.length > lastSegment) { + const toModify = parent.children[lastSegment]; + edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; + } + else if (parent.children.length === 0 || lastSegment === 0) { + edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; + } + else { + const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; + const previous = parent.children[index - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + return withFormatting(text, edit, options); + } + else { + throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`); + } + } + else { + throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); + } +} +function withFormatting(text, edit, options) { + if (!options.formattingOptions) { + return [edit]; + } + // apply the edit + let newText = applyEdit(text, edit); + // format the new text + let begin = edit.offset; + let end = edit.offset + edit.content.length; + if (edit.length === 0 || edit.content.length === 0) { // insert or remove + while (begin > 0 && !isEOL(newText, begin - 1)) { + begin--; + } + while (end < newText.length && !isEOL(newText, end)) { + end++; + } + } + const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false }); + // apply the formatting edits and track the begin and end offsets of the changes + for (let i = edits.length - 1; i >= 0; i--) { + const edit = edits[i]; + newText = applyEdit(newText, edit); + begin = Math.min(begin, edit.offset); + end = Math.max(end, edit.offset + edit.length); + end += edit.content.length - edit.length; + } + // create a single edit with all changes + const editLength = text.length - (newText.length - end) - begin; + return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; +} +export function applyEdit(text, edit) { + return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); +} +export function isWS(text, offset) { + return '\r\n \t'.indexOf(text.charAt(offset)) !== -1; +} diff --git a/web/node_modules/jsonc-parser/lib/esm/impl/format.js b/web/node_modules/jsonc-parser/lib/esm/impl/format.js new file mode 100644 index 0000000000000000000000000000000000000000..8663a1f385b08ddb8d2cc32bd3fc793b6751737c --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/impl/format.js @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +import { createScanner } from './scanner'; +import { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern'; +export function format(documentText, range, options) { + let initialIndentLevel; + let formatText; + let formatTextStart; + let rangeStart; + let rangeEnd; + if (range) { + rangeStart = range.offset; + rangeEnd = rangeStart + range.length; + formatTextStart = rangeStart; + while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { + formatTextStart--; + } + let endOffset = rangeEnd; + while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { + endOffset++; + } + formatText = documentText.substring(formatTextStart, endOffset); + initialIndentLevel = computeIndentLevel(formatText, options); + } + else { + formatText = documentText; + initialIndentLevel = 0; + formatTextStart = 0; + rangeStart = 0; + rangeEnd = documentText.length; + } + const eol = getEOL(options, documentText); + const eolFastPathSupported = supportedEols.includes(eol); + let numberLineBreaks = 0; + let indentLevel = 0; + let indentValue; + if (options.insertSpaces) { + indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4); + } + else { + indentValue = '\t'; + } + const indentType = indentValue === '\t' ? '\t' : ' '; + let scanner = createScanner(formatText, false); + let hasError = false; + function newLinesAndIndent() { + if (numberLineBreaks > 1) { + return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); + } + const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel); + if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) { + return eol + repeat(indentValue, initialIndentLevel + indentLevel); + } + if (amountOfSpaces <= 0) { + return eol; + } + return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]; + } + function scanNext() { + let token = scanner.scan(); + numberLineBreaks = 0; + while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) { + if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) { + numberLineBreaks += 1; + } + else if (token === 14 /* SyntaxKind.LineBreakTrivia */) { + numberLineBreaks = 1; + } + token = scanner.scan(); + } + hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */; + return token; + } + const editOperations = []; + function addEdit(text, startOffset, endOffset) { + if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) { + editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); + } + } + let firstToken = scanNext(); + if (options.keepLines && numberLineBreaks > 0) { + addEdit(repeat(eol, numberLineBreaks), 0, 0); + } + if (firstToken !== 17 /* SyntaxKind.EOF */) { + let firstTokenStart = scanner.getTokenOffset() + formatTextStart; + let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces + ? cachedSpaces[indentValue.length * initialIndentLevel] + : repeat(indentValue, initialIndentLevel); + addEdit(initialIndent, formatTextStart, firstTokenStart); + } + while (firstToken !== 17 /* SyntaxKind.EOF */) { + let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + let secondToken = scanNext(); + let replaceContent = ''; + let needsLineBreak = false; + while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { + let commentTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart); + firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */; + replaceContent = needsLineBreak ? newLinesAndIndent() : ''; + secondToken = scanNext(); + } + if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) { + if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { + indentLevel--; + } + ; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { + replaceContent = newLinesAndIndent(); + } + else if (options.keepLines) { + replaceContent = cachedSpaces[1]; + } + } + else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) { + if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { + indentLevel--; + } + ; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { + replaceContent = newLinesAndIndent(); + } + else if (options.keepLines) { + replaceContent = cachedSpaces[1]; + } + } + else { + switch (firstToken) { + case 3 /* SyntaxKind.OpenBracketToken */: + case 1 /* SyntaxKind.OpenBraceToken */: + indentLevel++; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = cachedSpaces[1]; + } + break; + case 5 /* SyntaxKind.CommaToken */: + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = cachedSpaces[1]; + } + break; + case 12 /* SyntaxKind.LineCommentTrivia */: + replaceContent = newLinesAndIndent(); + break; + case 13 /* SyntaxKind.BlockCommentTrivia */: + if (numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (!needsLineBreak) { + replaceContent = cachedSpaces[1]; + } + break; + case 6 /* SyntaxKind.ColonToken */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (!needsLineBreak) { + replaceContent = cachedSpaces[1]; + } + break; + case 10 /* SyntaxKind.StringLiteral */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) { + replaceContent = ''; + } + break; + case 7 /* SyntaxKind.NullKeyword */: + case 8 /* SyntaxKind.TrueKeyword */: + case 9 /* SyntaxKind.FalseKeyword */: + case 11 /* SyntaxKind.NumericLiteral */: + case 2 /* SyntaxKind.CloseBraceToken */: + case 4 /* SyntaxKind.CloseBracketToken */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else { + if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) { + replaceContent = cachedSpaces[1]; + } + else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) { + hasError = true; + } + } + break; + case 16 /* SyntaxKind.Unknown */: + hasError = true; + break; + } + if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { + replaceContent = newLinesAndIndent(); + } + } + if (secondToken === 17 /* SyntaxKind.EOF */) { + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = options.insertFinalNewline ? eol : ''; + } + } + const secondTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(replaceContent, firstTokenEnd, secondTokenStart); + firstToken = secondToken; + } + return editOperations; +} +function repeat(s, count) { + let result = ''; + for (let i = 0; i < count; i++) { + result += s; + } + return result; +} +function computeIndentLevel(content, options) { + let i = 0; + let nChars = 0; + const tabSize = options.tabSize || 4; + while (i < content.length) { + let ch = content.charAt(i); + if (ch === cachedSpaces[1]) { + nChars++; + } + else if (ch === '\t') { + nChars += tabSize; + } + else { + break; + } + i++; + } + return Math.floor(nChars / tabSize); +} +function getEOL(options, text) { + for (let i = 0; i < text.length; i++) { + const ch = text.charAt(i); + if (ch === '\r') { + if (i + 1 < text.length && text.charAt(i + 1) === '\n') { + return '\r\n'; + } + return '\r'; + } + else if (ch === '\n') { + return '\n'; + } + } + return (options && options.eol) || '\n'; +} +export function isEOL(text, offset) { + return '\r\n'.indexOf(text.charAt(offset)) !== -1; +} diff --git a/web/node_modules/jsonc-parser/lib/esm/impl/parser.js b/web/node_modules/jsonc-parser/lib/esm/impl/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..ea1ac2ed37bf0b4a90d9405066c0a9040a040dff --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/impl/parser.js @@ -0,0 +1,632 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +import { createScanner } from './scanner'; +var ParseOptions; +(function (ParseOptions) { + ParseOptions.DEFAULT = { + allowTrailingComma: false + }; +})(ParseOptions || (ParseOptions = {})); +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +export function getLocation(text, position) { + const segments = []; // strings or numbers + const earlyReturnException = new Object(); + let previousNode = undefined; + const previousNodeInst = { + value: {}, + offset: 0, + length: 0, + type: 'object', + parent: undefined + }; + let isAtPropertyKey = false; + function setPreviousNode(value, offset, length, type) { + previousNodeInst.value = value; + previousNodeInst.offset = offset; + previousNodeInst.length = length; + previousNodeInst.type = type; + previousNodeInst.colonOffset = undefined; + previousNode = previousNodeInst; + } + try { + visit(text, { + onObjectBegin: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + isAtPropertyKey = position > offset; + segments.push(''); // push a placeholder (will be replaced) + }, + onObjectProperty: (name, offset, length) => { + if (position < offset) { + throw earlyReturnException; + } + setPreviousNode(name, offset, length, 'property'); + segments[segments.length - 1] = name; + if (position <= offset + length) { + throw earlyReturnException; + } + }, + onObjectEnd: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.pop(); + }, + onArrayBegin: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.push(0); + }, + onArrayEnd: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.pop(); + }, + onLiteralValue: (value, offset, length) => { + if (position < offset) { + throw earlyReturnException; + } + setPreviousNode(value, offset, length, getNodeType(value)); + if (position <= offset + length) { + throw earlyReturnException; + } + }, + onSeparator: (sep, offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + if (sep === ':' && previousNode && previousNode.type === 'property') { + previousNode.colonOffset = offset; + isAtPropertyKey = false; + previousNode = undefined; + } + else if (sep === ',') { + const last = segments[segments.length - 1]; + if (typeof last === 'number') { + segments[segments.length - 1] = last + 1; + } + else { + isAtPropertyKey = true; + segments[segments.length - 1] = ''; + } + previousNode = undefined; + } + } + }); + } + catch (e) { + if (e !== earlyReturnException) { + throw e; + } + } + return { + path: segments, + previousNode, + isAtPropertyKey, + matches: (pattern) => { + let k = 0; + for (let i = 0; k < pattern.length && i < segments.length; i++) { + if (pattern[k] === segments[i] || pattern[k] === '*') { + k++; + } + else if (pattern[k] !== '**') { + return false; + } + } + return k === pattern.length; + } + }; +} +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore always check the errors list to find out if the input was valid. + */ +export function parse(text, errors = [], options = ParseOptions.DEFAULT) { + let currentProperty = null; + let currentParent = []; + const previousParents = []; + function onValue(value) { + if (Array.isArray(currentParent)) { + currentParent.push(value); + } + else if (currentProperty !== null) { + currentParent[currentProperty] = value; + } + } + const visitor = { + onObjectBegin: () => { + const object = {}; + onValue(object); + previousParents.push(currentParent); + currentParent = object; + currentProperty = null; + }, + onObjectProperty: (name) => { + currentProperty = name; + }, + onObjectEnd: () => { + currentParent = previousParents.pop(); + }, + onArrayBegin: () => { + const array = []; + onValue(array); + previousParents.push(currentParent); + currentParent = array; + currentProperty = null; + }, + onArrayEnd: () => { + currentParent = previousParents.pop(); + }, + onLiteralValue: onValue, + onError: (error, offset, length) => { + errors.push({ error, offset, length }); + } + }; + visit(text, visitor, options); + return currentParent[0]; +} +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +export function parseTree(text, errors = [], options = ParseOptions.DEFAULT) { + let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root + function ensurePropertyComplete(endOffset) { + if (currentParent.type === 'property') { + currentParent.length = endOffset - currentParent.offset; + currentParent = currentParent.parent; + } + } + function onValue(valueNode) { + currentParent.children.push(valueNode); + return valueNode; + } + const visitor = { + onObjectBegin: (offset) => { + currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); + }, + onObjectProperty: (name, offset, length) => { + currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); + currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); + }, + onObjectEnd: (offset, length) => { + ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onArrayBegin: (offset, length) => { + currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); + }, + onArrayEnd: (offset, length) => { + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onLiteralValue: (value, offset, length) => { + onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); + ensurePropertyComplete(offset + length); + }, + onSeparator: (sep, offset, length) => { + if (currentParent.type === 'property') { + if (sep === ':') { + currentParent.colonOffset = offset; + } + else if (sep === ',') { + ensurePropertyComplete(offset); + } + } + }, + onError: (error, offset, length) => { + errors.push({ error, offset, length }); + } + }; + visit(text, visitor, options); + const result = currentParent.children[0]; + if (result) { + delete result.parent; + } + return result; +} +/** + * Finds the node at the given path in a JSON DOM. + */ +export function findNodeAtLocation(root, path) { + if (!root) { + return undefined; + } + let node = root; + for (let segment of path) { + if (typeof segment === 'string') { + if (node.type !== 'object' || !Array.isArray(node.children)) { + return undefined; + } + let found = false; + for (const propertyNode of node.children) { + if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { + node = propertyNode.children[1]; + found = true; + break; + } + } + if (!found) { + return undefined; + } + } + else { + const index = segment; + if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { + return undefined; + } + node = node.children[index]; + } + } + return node; +} +/** + * Gets the JSON path of the given JSON DOM node + */ +export function getNodePath(node) { + if (!node.parent || !node.parent.children) { + return []; + } + const path = getNodePath(node.parent); + if (node.parent.type === 'property') { + const key = node.parent.children[0].value; + path.push(key); + } + else if (node.parent.type === 'array') { + const index = node.parent.children.indexOf(node); + if (index !== -1) { + path.push(index); + } + } + return path; +} +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +export function getNodeValue(node) { + switch (node.type) { + case 'array': + return node.children.map(getNodeValue); + case 'object': + const obj = Object.create(null); + for (let prop of node.children) { + const valueNode = prop.children[1]; + if (valueNode) { + obj[prop.children[0].value] = getNodeValue(valueNode); + } + } + return obj; + case 'null': + case 'string': + case 'number': + case 'boolean': + return node.value; + default: + return undefined; + } +} +export function contains(node, offset, includeRightBound = false) { + return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); +} +/** + * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +export function findNodeAtOffset(node, offset, includeRightBound = false) { + if (contains(node, offset, includeRightBound)) { + const children = node.children; + if (Array.isArray(children)) { + for (let i = 0; i < children.length && children[i].offset <= offset; i++) { + const item = findNodeAtOffset(children[i], offset, includeRightBound); + if (item) { + return item; + } + } + } + return node; + } + return undefined; +} +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +export function visit(text, visitor, options = ParseOptions.DEFAULT) { + const _scanner = createScanner(text, false); + // Important: Only pass copies of this to visitor functions to prevent accidental modification, and + // to not affect visitor functions which stored a reference to a previous JSONPath + const _jsonPath = []; + function toNoArgVisit(visitFunction) { + return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toNoArgVisitWithPath(visitFunction) { + return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + function toOneArgVisit(visitFunction) { + return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toOneArgVisitWithPath(visitFunction) { + return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); + const disallowComments = options && options.disallowComments; + const allowTrailingComma = options && options.allowTrailingComma; + function scanNext() { + while (true) { + const token = _scanner.scan(); + switch (_scanner.getTokenError()) { + case 4 /* ScanError.InvalidUnicode */: + handleError(14 /* ParseErrorCode.InvalidUnicode */); + break; + case 5 /* ScanError.InvalidEscapeCharacter */: + handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */); + break; + case 3 /* ScanError.UnexpectedEndOfNumber */: + handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */); + break; + case 1 /* ScanError.UnexpectedEndOfComment */: + if (!disallowComments) { + handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */); + } + break; + case 2 /* ScanError.UnexpectedEndOfString */: + handleError(12 /* ParseErrorCode.UnexpectedEndOfString */); + break; + case 6 /* ScanError.InvalidCharacter */: + handleError(16 /* ParseErrorCode.InvalidCharacter */); + break; + } + switch (token) { + case 12 /* SyntaxKind.LineCommentTrivia */: + case 13 /* SyntaxKind.BlockCommentTrivia */: + if (disallowComments) { + handleError(10 /* ParseErrorCode.InvalidCommentToken */); + } + else { + onComment(); + } + break; + case 16 /* SyntaxKind.Unknown */: + handleError(1 /* ParseErrorCode.InvalidSymbol */); + break; + case 15 /* SyntaxKind.Trivia */: + case 14 /* SyntaxKind.LineBreakTrivia */: + break; + default: + return token; + } + } + } + function handleError(error, skipUntilAfter = [], skipUntil = []) { + onError(error); + if (skipUntilAfter.length + skipUntil.length > 0) { + let token = _scanner.getToken(); + while (token !== 17 /* SyntaxKind.EOF */) { + if (skipUntilAfter.indexOf(token) !== -1) { + scanNext(); + break; + } + else if (skipUntil.indexOf(token) !== -1) { + break; + } + token = scanNext(); + } + } + } + function parseString(isValue) { + const value = _scanner.getTokenValue(); + if (isValue) { + onLiteralValue(value); + } + else { + onObjectProperty(value); + // add property name afterwards + _jsonPath.push(value); + } + scanNext(); + return true; + } + function parseLiteral() { + switch (_scanner.getToken()) { + case 11 /* SyntaxKind.NumericLiteral */: + const tokenValue = _scanner.getTokenValue(); + let value = Number(tokenValue); + if (isNaN(value)) { + handleError(2 /* ParseErrorCode.InvalidNumberFormat */); + value = 0; + } + onLiteralValue(value); + break; + case 7 /* SyntaxKind.NullKeyword */: + onLiteralValue(null); + break; + case 8 /* SyntaxKind.TrueKeyword */: + onLiteralValue(true); + break; + case 9 /* SyntaxKind.FalseKeyword */: + onLiteralValue(false); + break; + default: + return false; + } + scanNext(); + return true; + } + function parseProperty() { + if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) { + handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + return false; + } + parseString(false); + if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) { + onSeparator(':'); + scanNext(); // consume colon + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + } + else { + handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + _jsonPath.pop(); // remove processed property name + return true; + } + function parseObject() { + onObjectBegin(); + scanNext(); // consume open brace + let needsComma = false; + while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { + if (!needsComma) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + } + onSeparator(','); + scanNext(); // consume comma + if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) { + break; + } + } + else if (needsComma) { + handleError(6 /* ParseErrorCode.CommaExpected */, [], []); + } + if (!parseProperty()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + needsComma = true; + } + onObjectEnd(); + if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) { + handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []); + } + else { + scanNext(); // consume close brace + } + return true; + } + function parseArray() { + onArrayBegin(); + scanNext(); // consume open bracket + let isFirstElement = true; + let needsComma = false; + while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { + if (!needsComma) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + } + onSeparator(','); + scanNext(); // consume comma + if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) { + break; + } + } + else if (needsComma) { + handleError(6 /* ParseErrorCode.CommaExpected */, [], []); + } + if (isFirstElement) { + _jsonPath.push(0); + isFirstElement = false; + } + else { + _jsonPath[_jsonPath.length - 1]++; + } + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]); + } + needsComma = true; + } + onArrayEnd(); + if (!isFirstElement) { + _jsonPath.pop(); // remove array index + } + if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) { + handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []); + } + else { + scanNext(); // consume close bracket + } + return true; + } + function parseValue() { + switch (_scanner.getToken()) { + case 3 /* SyntaxKind.OpenBracketToken */: + return parseArray(); + case 1 /* SyntaxKind.OpenBraceToken */: + return parseObject(); + case 10 /* SyntaxKind.StringLiteral */: + return parseString(true); + default: + return parseLiteral(); + } + } + scanNext(); + if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) { + if (options.allowEmptyContent) { + return true; + } + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + return false; + } + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + return false; + } + if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []); + } + return true; +} +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +export function stripComments(text, replaceCh) { + let _scanner = createScanner(text), parts = [], kind, offset = 0, pos; + do { + pos = _scanner.getPosition(); + kind = _scanner.scan(); + switch (kind) { + case 12 /* SyntaxKind.LineCommentTrivia */: + case 13 /* SyntaxKind.BlockCommentTrivia */: + case 17 /* SyntaxKind.EOF */: + if (offset !== pos) { + parts.push(text.substring(offset, pos)); + } + if (replaceCh !== undefined) { + parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); + } + offset = _scanner.getPosition(); + break; + } + } while (kind !== 17 /* SyntaxKind.EOF */); + return parts.join(''); +} +export function getNodeType(value) { + switch (typeof value) { + case 'boolean': return 'boolean'; + case 'number': return 'number'; + case 'string': return 'string'; + case 'object': { + if (!value) { + return 'null'; + } + else if (Array.isArray(value)) { + return 'array'; + } + return 'object'; + } + default: return 'null'; + } +} diff --git a/web/node_modules/jsonc-parser/lib/esm/impl/scanner.js b/web/node_modules/jsonc-parser/lib/esm/impl/scanner.js new file mode 100644 index 0000000000000000000000000000000000000000..e84942c122b7bca38dddd177a519d7a17ad4fcef --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/impl/scanner.js @@ -0,0 +1,443 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +export function createScanner(text, ignoreTrivia = false) { + const len = text.length; + let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */; + function scanHexDigits(count, exact) { + let digits = 0; + let value = 0; + while (digits < count || !exact) { + let ch = text.charCodeAt(pos); + if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) { + value = value * 16 + ch - 48 /* CharacterCodes._0 */; + } + else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) { + value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10; + } + else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) { + value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10; + } + else { + break; + } + pos++; + digits++; + } + if (digits < count) { + value = -1; + } + return value; + } + function setPosition(newPosition) { + pos = newPosition; + value = ''; + tokenOffset = 0; + token = 16 /* SyntaxKind.Unknown */; + scanError = 0 /* ScanError.None */; + } + function scanNumber() { + let start = pos; + if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) { + pos++; + } + else { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + } + if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) { + pos++; + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + } + else { + scanError = 3 /* ScanError.UnexpectedEndOfNumber */; + return text.substring(start, pos); + } + } + let end = pos; + if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) { + pos++; + if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) { + pos++; + } + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + end = pos; + } + else { + scanError = 3 /* ScanError.UnexpectedEndOfNumber */; + } + } + return text.substring(start, end); + } + function scanString() { + let result = '', start = pos; + while (true) { + if (pos >= len) { + result += text.substring(start, pos); + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + const ch = text.charCodeAt(pos); + if (ch === 34 /* CharacterCodes.doubleQuote */) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* CharacterCodes.backslash */) { + result += text.substring(start, pos); + pos++; + if (pos >= len) { + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + const ch2 = text.charCodeAt(pos++); + switch (ch2) { + case 34 /* CharacterCodes.doubleQuote */: + result += '\"'; + break; + case 92 /* CharacterCodes.backslash */: + result += '\\'; + break; + case 47 /* CharacterCodes.slash */: + result += '/'; + break; + case 98 /* CharacterCodes.b */: + result += '\b'; + break; + case 102 /* CharacterCodes.f */: + result += '\f'; + break; + case 110 /* CharacterCodes.n */: + result += '\n'; + break; + case 114 /* CharacterCodes.r */: + result += '\r'; + break; + case 116 /* CharacterCodes.t */: + result += '\t'; + break; + case 117 /* CharacterCodes.u */: + const ch3 = scanHexDigits(4, true); + if (ch3 >= 0) { + result += String.fromCharCode(ch3); + } + else { + scanError = 4 /* ScanError.InvalidUnicode */; + } + break; + default: + scanError = 5 /* ScanError.InvalidEscapeCharacter */; + } + start = pos; + continue; + } + if (ch >= 0 && ch <= 0x1f) { + if (isLineBreak(ch)) { + result += text.substring(start, pos); + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + else { + scanError = 6 /* ScanError.InvalidCharacter */; + // mark as error but continue with string + } + } + pos++; + } + return result; + } + function scanNext() { + value = ''; + scanError = 0 /* ScanError.None */; + tokenOffset = pos; + lineStartOffset = lineNumber; + prevTokenLineStartOffset = tokenLineStartOffset; + if (pos >= len) { + // at the end + tokenOffset = len; + return token = 17 /* SyntaxKind.EOF */; + } + let code = text.charCodeAt(pos); + // trivia: whitespace + if (isWhiteSpace(code)) { + do { + pos++; + value += String.fromCharCode(code); + code = text.charCodeAt(pos); + } while (isWhiteSpace(code)); + return token = 15 /* SyntaxKind.Trivia */; + } + // trivia: newlines + if (isLineBreak(code)) { + pos++; + value += String.fromCharCode(code); + if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { + pos++; + value += '\n'; + } + lineNumber++; + tokenLineStartOffset = pos; + return token = 14 /* SyntaxKind.LineBreakTrivia */; + } + switch (code) { + // tokens: []{}:, + case 123 /* CharacterCodes.openBrace */: + pos++; + return token = 1 /* SyntaxKind.OpenBraceToken */; + case 125 /* CharacterCodes.closeBrace */: + pos++; + return token = 2 /* SyntaxKind.CloseBraceToken */; + case 91 /* CharacterCodes.openBracket */: + pos++; + return token = 3 /* SyntaxKind.OpenBracketToken */; + case 93 /* CharacterCodes.closeBracket */: + pos++; + return token = 4 /* SyntaxKind.CloseBracketToken */; + case 58 /* CharacterCodes.colon */: + pos++; + return token = 6 /* SyntaxKind.ColonToken */; + case 44 /* CharacterCodes.comma */: + pos++; + return token = 5 /* SyntaxKind.CommaToken */; + // strings + case 34 /* CharacterCodes.doubleQuote */: + pos++; + value = scanString(); + return token = 10 /* SyntaxKind.StringLiteral */; + // comments + case 47 /* CharacterCodes.slash */: + const start = pos - 1; + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { + pos += 2; + while (pos < len) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + value = text.substring(start, pos); + return token = 12 /* SyntaxKind.LineCommentTrivia */; + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) { + pos += 2; + const safeLength = len - 1; // For lookahead. + let commentClosed = false; + while (pos < safeLength) { + const ch = text.charCodeAt(pos); + if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { + pos += 2; + commentClosed = true; + break; + } + pos++; + if (isLineBreak(ch)) { + if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { + pos++; + } + lineNumber++; + tokenLineStartOffset = pos; + } + } + if (!commentClosed) { + pos++; + scanError = 1 /* ScanError.UnexpectedEndOfComment */; + } + value = text.substring(start, pos); + return token = 13 /* SyntaxKind.BlockCommentTrivia */; + } + // just a single slash + value += String.fromCharCode(code); + pos++; + return token = 16 /* SyntaxKind.Unknown */; + // numbers + case 45 /* CharacterCodes.minus */: + value += String.fromCharCode(code); + pos++; + if (pos === len || !isDigit(text.charCodeAt(pos))) { + return token = 16 /* SyntaxKind.Unknown */; + } + // found a minus, followed by a number so + // we fall through to proceed with scanning + // numbers + case 48 /* CharacterCodes._0 */: + case 49 /* CharacterCodes._1 */: + case 50 /* CharacterCodes._2 */: + case 51 /* CharacterCodes._3 */: + case 52 /* CharacterCodes._4 */: + case 53 /* CharacterCodes._5 */: + case 54 /* CharacterCodes._6 */: + case 55 /* CharacterCodes._7 */: + case 56 /* CharacterCodes._8 */: + case 57 /* CharacterCodes._9 */: + value += scanNumber(); + return token = 11 /* SyntaxKind.NumericLiteral */; + // literals and unknown symbols + default: + // is a literal? Read the full word. + while (pos < len && isUnknownContentCharacter(code)) { + pos++; + code = text.charCodeAt(pos); + } + if (tokenOffset !== pos) { + value = text.substring(tokenOffset, pos); + // keywords: true, false, null + switch (value) { + case 'true': return token = 8 /* SyntaxKind.TrueKeyword */; + case 'false': return token = 9 /* SyntaxKind.FalseKeyword */; + case 'null': return token = 7 /* SyntaxKind.NullKeyword */; + } + return token = 16 /* SyntaxKind.Unknown */; + } + // some + value += String.fromCharCode(code); + pos++; + return token = 16 /* SyntaxKind.Unknown */; + } + } + function isUnknownContentCharacter(code) { + if (isWhiteSpace(code) || isLineBreak(code)) { + return false; + } + switch (code) { + case 125 /* CharacterCodes.closeBrace */: + case 93 /* CharacterCodes.closeBracket */: + case 123 /* CharacterCodes.openBrace */: + case 91 /* CharacterCodes.openBracket */: + case 34 /* CharacterCodes.doubleQuote */: + case 58 /* CharacterCodes.colon */: + case 44 /* CharacterCodes.comma */: + case 47 /* CharacterCodes.slash */: + return false; + } + return true; + } + function scanNextNonTrivia() { + let result; + do { + result = scanNext(); + } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */); + return result; + } + return { + setPosition: setPosition, + getPosition: () => pos, + scan: ignoreTrivia ? scanNextNonTrivia : scanNext, + getToken: () => token, + getTokenValue: () => value, + getTokenOffset: () => tokenOffset, + getTokenLength: () => pos - tokenOffset, + getTokenStartLine: () => lineStartOffset, + getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, + getTokenError: () => scanError, + }; +} +function isWhiteSpace(ch) { + return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */; +} +function isLineBreak(ch) { + return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */; +} +function isDigit(ch) { + return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */; +} +var CharacterCodes; +(function (CharacterCodes) { + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; +})(CharacterCodes || (CharacterCodes = {})); diff --git a/web/node_modules/jsonc-parser/lib/esm/impl/string-intern.js b/web/node_modules/jsonc-parser/lib/esm/impl/string-intern.js new file mode 100644 index 0000000000000000000000000000000000000000..2794e2b39325539833035e7a140de17df8b28e93 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/impl/string-intern.js @@ -0,0 +1,29 @@ +export const cachedSpaces = new Array(20).fill(0).map((_, index) => { + return ' '.repeat(index); +}); +const maxCachedValues = 200; +export const cachedBreakLinesWithSpaces = { + ' ': { + '\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\n' + ' '.repeat(index); + }), + '\r': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r' + ' '.repeat(index); + }), + '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r\n' + ' '.repeat(index); + }), + }, + '\t': { + '\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\n' + '\t'.repeat(index); + }), + '\r': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r' + '\t'.repeat(index); + }), + '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r\n' + '\t'.repeat(index); + }), + } +}; +export const supportedEols = ['\n', '\r', '\r\n']; diff --git a/web/node_modules/jsonc-parser/lib/esm/main.d.ts b/web/node_modules/jsonc-parser/lib/esm/main.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7312a36d4f48d03e354ba9c4e45fc28947d33894 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/main.d.ts @@ -0,0 +1,349 @@ +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +export declare const createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner; +export declare const enum ScanError { + None = 0, + UnexpectedEndOfComment = 1, + UnexpectedEndOfString = 2, + UnexpectedEndOfNumber = 3, + InvalidUnicode = 4, + InvalidEscapeCharacter = 5, + InvalidCharacter = 6 +} +export declare const enum SyntaxKind { + OpenBraceToken = 1, + CloseBraceToken = 2, + OpenBracketToken = 3, + CloseBracketToken = 4, + CommaToken = 5, + ColonToken = 6, + NullKeyword = 7, + TrueKeyword = 8, + FalseKeyword = 9, + StringLiteral = 10, + NumericLiteral = 11, + LineCommentTrivia = 12, + BlockCommentTrivia = 13, + LineBreakTrivia = 14, + Trivia = 15, + Unknown = 16, + EOF = 17 +} +/** + * The scanner object, representing a JSON scanner at a position in the input string. + */ +export interface JSONScanner { + /** + * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token. + */ + setPosition(pos: number): void; + /** + * Read the next token. Returns the token code. + */ + scan(): SyntaxKind; + /** + * Returns the zero-based current scan position, which is after the last read token. + */ + getPosition(): number; + /** + * Returns the last read token. + */ + getToken(): SyntaxKind; + /** + * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false. + */ + getTokenValue(): string; + /** + * The zero-based start offset of the last read token. + */ + getTokenOffset(): number; + /** + * The length of the last read token. + */ + getTokenLength(): number; + /** + * The zero-based start line number of the last read token. + */ + getTokenStartLine(): number; + /** + * The zero-based start character (column) of the last read token. + */ + getTokenStartCharacter(): number; + /** + * An error code of the last scan. + */ + getTokenError(): ScanError; +} +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +export declare const getLocation: (text: string, position: number) => Location; +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore, always check the errors list to find out if the input was valid. + */ +export declare const parse: (text: string, errors?: ParseError[], options?: ParseOptions) => any; +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +export declare const parseTree: (text: string, errors?: ParseError[], options?: ParseOptions) => Node | undefined; +/** + * Finds the node at the given path in a JSON DOM. + */ +export declare const findNodeAtLocation: (root: Node, path: JSONPath) => Node | undefined; +/** + * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +export declare const findNodeAtOffset: (root: Node, offset: number, includeRightBound?: boolean) => Node | undefined; +/** + * Gets the JSON path of the given JSON DOM node + */ +export declare const getNodePath: (node: Node) => JSONPath; +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +export declare const getNodeValue: (node: Node) => any; +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +export declare const visit: (text: string, visitor: JSONVisitor, options?: ParseOptions) => any; +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +export declare const stripComments: (text: string, replaceCh?: string) => string; +export interface ParseError { + error: ParseErrorCode; + offset: number; + length: number; +} +export declare const enum ParseErrorCode { + InvalidSymbol = 1, + InvalidNumberFormat = 2, + PropertyNameExpected = 3, + ValueExpected = 4, + ColonExpected = 5, + CommaExpected = 6, + CloseBraceExpected = 7, + CloseBracketExpected = 8, + EndOfFileExpected = 9, + InvalidCommentToken = 10, + UnexpectedEndOfComment = 11, + UnexpectedEndOfString = 12, + UnexpectedEndOfNumber = 13, + InvalidUnicode = 14, + InvalidEscapeCharacter = 15, + InvalidCharacter = 16 +} +export declare function printParseErrorCode(code: ParseErrorCode): "InvalidSymbol" | "InvalidNumberFormat" | "PropertyNameExpected" | "ValueExpected" | "ColonExpected" | "CommaExpected" | "CloseBraceExpected" | "CloseBracketExpected" | "EndOfFileExpected" | "InvalidCommentToken" | "UnexpectedEndOfComment" | "UnexpectedEndOfString" | "UnexpectedEndOfNumber" | "InvalidUnicode" | "InvalidEscapeCharacter" | "InvalidCharacter" | ""; +export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null'; +export interface Node { + readonly type: NodeType; + readonly value?: any; + readonly offset: number; + readonly length: number; + readonly colonOffset?: number; + readonly parent?: Node; + readonly children?: Node[]; +} +/** + * A {@linkcode JSONPath} segment. Either a string representing an object property name + * or a number (starting at 0) for array indices. + */ +export type Segment = string | number; +export type JSONPath = Segment[]; +export interface Location { + /** + * The previous property key or literal value (string, number, boolean or null) or undefined. + */ + previousNode?: Node; + /** + * The path describing the location in the JSON document. The path consists of a sequence of strings + * representing an object property or numbers for array indices. + */ + path: JSONPath; + /** + * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). + * '*' will match a single segment of any property name or index. + * '**' will match a sequence of segments of any property name or index, or no segment. + */ + matches: (patterns: JSONPath) => boolean; + /** + * If set, the location's offset is at a property key. + */ + isAtPropertyKey: boolean; +} +export interface ParseOptions { + disallowComments?: boolean; + allowTrailingComma?: boolean; + allowEmptyContent?: boolean; +} +/** + * Visitor called by {@linkcode visit} when parsing JSON. + * + * The visitor functions have the following common parameters: + * - `offset`: Global offset within the JSON document, starting at 0 + * - `startLine`: Line number, starting at 0 + * - `startCharacter`: Start character (column) within the current line, starting at 0 + * + * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the + * current `JSONPath` within the document. + */ +export interface JSONVisitor { + /** + * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. + */ + onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a property is encountered. The offset and length represent the location of the property name. + * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the + * property name yet. + */ + onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. + */ + onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. + */ + onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. + */ + onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. + */ + onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. + */ + onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment. + */ + onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked on an error. + */ + onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void; +} +/** + * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation. + * It consist of one or more edits describing insertions, replacements or removals of text segments. + * * The offsets of the edits refer to the original state of the document. + * * No two edits change or remove the same range of text in the original document. + * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. + * * The order in the array defines which edit is applied first. + * To apply an edit result use {@linkcode applyEdits}. + * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data. + */ +export type EditResult = Edit[]; +/** + * Represents a text modification + */ +export interface Edit { + /** + * The start offset of the modification. + */ + offset: number; + /** + * The length of the modification. Must not be negative. Empty length represents an *insert*. + */ + length: number; + /** + * The new content. Empty content represents a *remove*. + */ + content: string; +} +/** + * A text range in the document +*/ +export interface Range { + /** + * The start offset of the range. + */ + offset: number; + /** + * The length of the range. Must not be negative. + */ + length: number; +} +/** + * Options used by {@linkcode format} when computing the formatting edit operations + */ +export interface FormattingOptions { + /** + * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent. + */ + tabSize?: number; + /** + * Is indentation based on spaces? + */ + insertSpaces?: boolean; + /** + * The default 'end of line' character. If not set, '\n' is used as default. + */ + eol?: string; + /** + * If set, will add a new line at the end of the document. + */ + insertFinalNewline?: boolean; + /** + * If true, will keep line positions as is in the formatting + */ + keepLines?: boolean; +} +/** + * Computes the edit operations needed to format a JSON document. + * + * @param documentText The input text + * @param range The range to format or `undefined` to format the full content + * @param options The formatting options + * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): EditResult; +/** + * Options used by {@linkcode modify} when computing the modification edit operations + */ +export interface ModificationOptions { + /** + * Formatting options. If undefined, the newly inserted code will be inserted unformatted. + */ + formattingOptions?: FormattingOptions; + /** + * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then + * {@linkcode modify} will insert a new item at that location instead of overwriting its contents. + */ + isArrayInsertion?: boolean; + /** + * Optional function to define the insertion index given an existing list of properties. + */ + getInsertionIndex?: (properties: string[]) => number; +} +/** + * Computes the edit operations needed to modify a value in the JSON document. + * + * @param documentText The input text + * @param path The path of the value to change. The path represents either to the document root, a property or an array item. + * If the path points to an non-existing property or item, it will be created. + * @param value The new value for the specified property or item. If the value is undefined, + * the property or item will be removed. + * @param options Options + * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult; +/** + * Applies edits to an input string. + * @param text The input text + * @param edits Edit operations following the format described in {@linkcode EditResult}. + * @returns The text with the applied edits. + * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. + */ +export declare function applyEdits(text: string, edits: EditResult): string; diff --git a/web/node_modules/jsonc-parser/lib/esm/main.js b/web/node_modules/jsonc-parser/lib/esm/main.js new file mode 100644 index 0000000000000000000000000000000000000000..18e3cb7168b5cc4401a25bcace1f8af379c408d5 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/esm/main.js @@ -0,0 +1,178 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +import * as formatter from './impl/format'; +import * as edit from './impl/edit'; +import * as scanner from './impl/scanner'; +import * as parser from './impl/parser'; +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +export const createScanner = scanner.createScanner; +export var ScanError; +(function (ScanError) { + ScanError[ScanError["None"] = 0] = "None"; + ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; + ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; + ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; + ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; + ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; + ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter"; +})(ScanError || (ScanError = {})); +export var SyntaxKind; +(function (SyntaxKind) { + SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; + SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; + SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; + SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; + SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; + SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; + SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; + SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF"; +})(SyntaxKind || (SyntaxKind = {})); +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +export const getLocation = parser.getLocation; +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore, always check the errors list to find out if the input was valid. + */ +export const parse = parser.parse; +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +export const parseTree = parser.parseTree; +/** + * Finds the node at the given path in a JSON DOM. + */ +export const findNodeAtLocation = parser.findNodeAtLocation; +/** + * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +export const findNodeAtOffset = parser.findNodeAtOffset; +/** + * Gets the JSON path of the given JSON DOM node + */ +export const getNodePath = parser.getNodePath; +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +export const getNodeValue = parser.getNodeValue; +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +export const visit = parser.visit; +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +export const stripComments = parser.stripComments; +export var ParseErrorCode; +(function (ParseErrorCode) { + ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; + ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; + ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; + ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; + ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; + ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; + ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; + ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; + ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; + ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; + ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; + ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; + ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter"; +})(ParseErrorCode || (ParseErrorCode = {})); +export function printParseErrorCode(code) { + switch (code) { + case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol'; + case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat'; + case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected'; + case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected'; + case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected'; + case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected'; + case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected'; + case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected'; + case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected'; + case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken'; + case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; + case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString'; + case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; + case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode'; + case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; + case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter'; + } + return ''; +} +/** + * Computes the edit operations needed to format a JSON document. + * + * @param documentText The input text + * @param range The range to format or `undefined` to format the full content + * @param options The formatting options + * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export function format(documentText, range, options) { + return formatter.format(documentText, range, options); +} +/** + * Computes the edit operations needed to modify a value in the JSON document. + * + * @param documentText The input text + * @param path The path of the value to change. The path represents either to the document root, a property or an array item. + * If the path points to an non-existing property or item, it will be created. + * @param value The new value for the specified property or item. If the value is undefined, + * the property or item will be removed. + * @param options Options + * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export function modify(text, path, value, options) { + return edit.setProperty(text, path, value, options); +} +/** + * Applies edits to an input string. + * @param text The input text + * @param edits Edit operations following the format described in {@linkcode EditResult}. + * @returns The text with the applied edits. + * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. + */ +export function applyEdits(text, edits) { + let sortedEdits = edits.slice(0).sort((a, b) => { + const diff = a.offset - b.offset; + if (diff === 0) { + return a.length - b.length; + } + return diff; + }); + let lastModifiedOffset = text.length; + for (let i = sortedEdits.length - 1; i >= 0; i--) { + let e = sortedEdits[i]; + if (e.offset + e.length <= lastModifiedOffset) { + text = edit.applyEdit(text, e); + } + else { + throw new Error('Overlapping edit'); + } + lastModifiedOffset = e.offset; + } + return text; +} diff --git a/web/node_modules/jsonc-parser/lib/umd/impl/edit.js b/web/node_modules/jsonc-parser/lib/umd/impl/edit.js new file mode 100644 index 0000000000000000000000000000000000000000..f9aeefef667d8a725dba6954d5831bdc5ff145f8 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/impl/edit.js @@ -0,0 +1,201 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "./format", "./parser"], factory); + } +})(function (require, exports) { + /*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isWS = exports.applyEdit = exports.setProperty = exports.removeProperty = void 0; + const format_1 = require("./format"); + const parser_1 = require("./parser"); + function removeProperty(text, path, options) { + return setProperty(text, path, void 0, options); + } + exports.removeProperty = removeProperty; + function setProperty(text, originalPath, value, options) { + const path = originalPath.slice(); + const errors = []; + const root = (0, parser_1.parseTree)(text, errors); + let parent = void 0; + let lastSegment = void 0; + while (path.length > 0) { + lastSegment = path.pop(); + parent = (0, parser_1.findNodeAtLocation)(root, path); + if (parent === void 0 && value !== void 0) { + if (typeof lastSegment === 'string') { + value = { [lastSegment]: value }; + } + else { + value = [value]; + } + } + else { + break; + } + } + if (!parent) { + // empty document + if (value === void 0) { // delete + throw new Error('Can not delete in empty document'); + } + return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); + } + else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { + const existing = (0, parser_1.findNodeAtLocation)(parent, [lastSegment]); + if (existing !== void 0) { + if (value === void 0) { // delete + if (!existing.parent) { + throw new Error('Malformed AST'); + } + const propertyIndex = parent.children.indexOf(existing.parent); + let removeBegin; + let removeEnd = existing.parent.offset + existing.parent.length; + if (propertyIndex > 0) { + // remove the comma of the previous node + let previous = parent.children[propertyIndex - 1]; + removeBegin = previous.offset + previous.length; + } + else { + removeBegin = parent.offset + 1; + if (parent.children.length > 1) { + // remove the comma of the next node + let next = parent.children[1]; + removeEnd = next.offset; + } + } + return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); + } + else { + // set value of existing property + return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); + } + } + else { + if (value === void 0) { // delete + return []; // property does not exist, nothing to do + } + const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; + const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length; + let edit; + if (index > 0) { + let previous = parent.children[index - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + else if (parent.children.length === 0) { + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; + } + else { + edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; + } + return withFormatting(text, edit, options); + } + } + else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { + const insertIndex = lastSegment; + if (insertIndex === -1) { + // Insert + const newProperty = `${JSON.stringify(value)}`; + let edit; + if (parent.children.length === 0) { + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; + } + else { + const previous = parent.children[parent.children.length - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + return withFormatting(text, edit, options); + } + else if (value === void 0 && parent.children.length >= 0) { + // Removal + const removalIndex = lastSegment; + const toRemove = parent.children[removalIndex]; + let edit; + if (parent.children.length === 1) { + // only item + edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; + } + else if (parent.children.length - 1 === removalIndex) { + // last item + let previous = parent.children[removalIndex - 1]; + let offset = previous.offset + previous.length; + let parentEndOffset = parent.offset + parent.length; + edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; + } + else { + edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; + } + return withFormatting(text, edit, options); + } + else if (value !== void 0) { + let edit; + const newProperty = `${JSON.stringify(value)}`; + if (!options.isArrayInsertion && parent.children.length > lastSegment) { + const toModify = parent.children[lastSegment]; + edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; + } + else if (parent.children.length === 0 || lastSegment === 0) { + edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; + } + else { + const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; + const previous = parent.children[index - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + return withFormatting(text, edit, options); + } + else { + throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`); + } + } + else { + throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); + } + } + exports.setProperty = setProperty; + function withFormatting(text, edit, options) { + if (!options.formattingOptions) { + return [edit]; + } + // apply the edit + let newText = applyEdit(text, edit); + // format the new text + let begin = edit.offset; + let end = edit.offset + edit.content.length; + if (edit.length === 0 || edit.content.length === 0) { // insert or remove + while (begin > 0 && !(0, format_1.isEOL)(newText, begin - 1)) { + begin--; + } + while (end < newText.length && !(0, format_1.isEOL)(newText, end)) { + end++; + } + } + const edits = (0, format_1.format)(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false }); + // apply the formatting edits and track the begin and end offsets of the changes + for (let i = edits.length - 1; i >= 0; i--) { + const edit = edits[i]; + newText = applyEdit(newText, edit); + begin = Math.min(begin, edit.offset); + end = Math.max(end, edit.offset + edit.length); + end += edit.content.length - edit.length; + } + // create a single edit with all changes + const editLength = text.length - (newText.length - end) - begin; + return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; + } + function applyEdit(text, edit) { + return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); + } + exports.applyEdit = applyEdit; + function isWS(text, offset) { + return '\r\n \t'.indexOf(text.charAt(offset)) !== -1; + } + exports.isWS = isWS; +}); diff --git a/web/node_modules/jsonc-parser/lib/umd/impl/format.js b/web/node_modules/jsonc-parser/lib/umd/impl/format.js new file mode 100644 index 0000000000000000000000000000000000000000..2b9f2bc54a9ad4ad38a99bbaab4da57f89d40f3d --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/impl/format.js @@ -0,0 +1,275 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "./scanner", "./string-intern"], factory); + } +})(function (require, exports) { + /*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEOL = exports.format = void 0; + const scanner_1 = require("./scanner"); + const string_intern_1 = require("./string-intern"); + function format(documentText, range, options) { + let initialIndentLevel; + let formatText; + let formatTextStart; + let rangeStart; + let rangeEnd; + if (range) { + rangeStart = range.offset; + rangeEnd = rangeStart + range.length; + formatTextStart = rangeStart; + while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { + formatTextStart--; + } + let endOffset = rangeEnd; + while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { + endOffset++; + } + formatText = documentText.substring(formatTextStart, endOffset); + initialIndentLevel = computeIndentLevel(formatText, options); + } + else { + formatText = documentText; + initialIndentLevel = 0; + formatTextStart = 0; + rangeStart = 0; + rangeEnd = documentText.length; + } + const eol = getEOL(options, documentText); + const eolFastPathSupported = string_intern_1.supportedEols.includes(eol); + let numberLineBreaks = 0; + let indentLevel = 0; + let indentValue; + if (options.insertSpaces) { + indentValue = string_intern_1.cachedSpaces[options.tabSize || 4] ?? repeat(string_intern_1.cachedSpaces[1], options.tabSize || 4); + } + else { + indentValue = '\t'; + } + const indentType = indentValue === '\t' ? '\t' : ' '; + let scanner = (0, scanner_1.createScanner)(formatText, false); + let hasError = false; + function newLinesAndIndent() { + if (numberLineBreaks > 1) { + return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); + } + const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel); + if (!eolFastPathSupported || amountOfSpaces > string_intern_1.cachedBreakLinesWithSpaces[indentType][eol].length) { + return eol + repeat(indentValue, initialIndentLevel + indentLevel); + } + if (amountOfSpaces <= 0) { + return eol; + } + return string_intern_1.cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]; + } + function scanNext() { + let token = scanner.scan(); + numberLineBreaks = 0; + while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) { + if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) { + numberLineBreaks += 1; + } + else if (token === 14 /* SyntaxKind.LineBreakTrivia */) { + numberLineBreaks = 1; + } + token = scanner.scan(); + } + hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */; + return token; + } + const editOperations = []; + function addEdit(text, startOffset, endOffset) { + if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) { + editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); + } + } + let firstToken = scanNext(); + if (options.keepLines && numberLineBreaks > 0) { + addEdit(repeat(eol, numberLineBreaks), 0, 0); + } + if (firstToken !== 17 /* SyntaxKind.EOF */) { + let firstTokenStart = scanner.getTokenOffset() + formatTextStart; + let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces + ? string_intern_1.cachedSpaces[indentValue.length * initialIndentLevel] + : repeat(indentValue, initialIndentLevel); + addEdit(initialIndent, formatTextStart, firstTokenStart); + } + while (firstToken !== 17 /* SyntaxKind.EOF */) { + let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + let secondToken = scanNext(); + let replaceContent = ''; + let needsLineBreak = false; + while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { + let commentTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(string_intern_1.cachedSpaces[1], firstTokenEnd, commentTokenStart); + firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */; + replaceContent = needsLineBreak ? newLinesAndIndent() : ''; + secondToken = scanNext(); + } + if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) { + if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { + indentLevel--; + } + ; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { + replaceContent = newLinesAndIndent(); + } + else if (options.keepLines) { + replaceContent = string_intern_1.cachedSpaces[1]; + } + } + else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) { + if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { + indentLevel--; + } + ; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { + replaceContent = newLinesAndIndent(); + } + else if (options.keepLines) { + replaceContent = string_intern_1.cachedSpaces[1]; + } + } + else { + switch (firstToken) { + case 3 /* SyntaxKind.OpenBracketToken */: + case 1 /* SyntaxKind.OpenBraceToken */: + indentLevel++; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = string_intern_1.cachedSpaces[1]; + } + break; + case 5 /* SyntaxKind.CommaToken */: + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = string_intern_1.cachedSpaces[1]; + } + break; + case 12 /* SyntaxKind.LineCommentTrivia */: + replaceContent = newLinesAndIndent(); + break; + case 13 /* SyntaxKind.BlockCommentTrivia */: + if (numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (!needsLineBreak) { + replaceContent = string_intern_1.cachedSpaces[1]; + } + break; + case 6 /* SyntaxKind.ColonToken */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (!needsLineBreak) { + replaceContent = string_intern_1.cachedSpaces[1]; + } + break; + case 10 /* SyntaxKind.StringLiteral */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) { + replaceContent = ''; + } + break; + case 7 /* SyntaxKind.NullKeyword */: + case 8 /* SyntaxKind.TrueKeyword */: + case 9 /* SyntaxKind.FalseKeyword */: + case 11 /* SyntaxKind.NumericLiteral */: + case 2 /* SyntaxKind.CloseBraceToken */: + case 4 /* SyntaxKind.CloseBracketToken */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else { + if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) { + replaceContent = string_intern_1.cachedSpaces[1]; + } + else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) { + hasError = true; + } + } + break; + case 16 /* SyntaxKind.Unknown */: + hasError = true; + break; + } + if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { + replaceContent = newLinesAndIndent(); + } + } + if (secondToken === 17 /* SyntaxKind.EOF */) { + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = options.insertFinalNewline ? eol : ''; + } + } + const secondTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(replaceContent, firstTokenEnd, secondTokenStart); + firstToken = secondToken; + } + return editOperations; + } + exports.format = format; + function repeat(s, count) { + let result = ''; + for (let i = 0; i < count; i++) { + result += s; + } + return result; + } + function computeIndentLevel(content, options) { + let i = 0; + let nChars = 0; + const tabSize = options.tabSize || 4; + while (i < content.length) { + let ch = content.charAt(i); + if (ch === string_intern_1.cachedSpaces[1]) { + nChars++; + } + else if (ch === '\t') { + nChars += tabSize; + } + else { + break; + } + i++; + } + return Math.floor(nChars / tabSize); + } + function getEOL(options, text) { + for (let i = 0; i < text.length; i++) { + const ch = text.charAt(i); + if (ch === '\r') { + if (i + 1 < text.length && text.charAt(i + 1) === '\n') { + return '\r\n'; + } + return '\r'; + } + else if (ch === '\n') { + return '\n'; + } + } + return (options && options.eol) || '\n'; + } + function isEOL(text, offset) { + return '\r\n'.indexOf(text.charAt(offset)) !== -1; + } + exports.isEOL = isEOL; +}); diff --git a/web/node_modules/jsonc-parser/lib/umd/impl/parser.js b/web/node_modules/jsonc-parser/lib/umd/impl/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..211e1d1c14885aedc6fd3b966d5a24790beaf908 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/impl/parser.js @@ -0,0 +1,655 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "./scanner"], factory); + } +})(function (require, exports) { + /*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getNodeType = exports.stripComments = exports.visit = exports.findNodeAtOffset = exports.contains = exports.getNodeValue = exports.getNodePath = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = void 0; + const scanner_1 = require("./scanner"); + var ParseOptions; + (function (ParseOptions) { + ParseOptions.DEFAULT = { + allowTrailingComma: false + }; + })(ParseOptions || (ParseOptions = {})); + /** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ + function getLocation(text, position) { + const segments = []; // strings or numbers + const earlyReturnException = new Object(); + let previousNode = undefined; + const previousNodeInst = { + value: {}, + offset: 0, + length: 0, + type: 'object', + parent: undefined + }; + let isAtPropertyKey = false; + function setPreviousNode(value, offset, length, type) { + previousNodeInst.value = value; + previousNodeInst.offset = offset; + previousNodeInst.length = length; + previousNodeInst.type = type; + previousNodeInst.colonOffset = undefined; + previousNode = previousNodeInst; + } + try { + visit(text, { + onObjectBegin: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + isAtPropertyKey = position > offset; + segments.push(''); // push a placeholder (will be replaced) + }, + onObjectProperty: (name, offset, length) => { + if (position < offset) { + throw earlyReturnException; + } + setPreviousNode(name, offset, length, 'property'); + segments[segments.length - 1] = name; + if (position <= offset + length) { + throw earlyReturnException; + } + }, + onObjectEnd: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.pop(); + }, + onArrayBegin: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.push(0); + }, + onArrayEnd: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.pop(); + }, + onLiteralValue: (value, offset, length) => { + if (position < offset) { + throw earlyReturnException; + } + setPreviousNode(value, offset, length, getNodeType(value)); + if (position <= offset + length) { + throw earlyReturnException; + } + }, + onSeparator: (sep, offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + if (sep === ':' && previousNode && previousNode.type === 'property') { + previousNode.colonOffset = offset; + isAtPropertyKey = false; + previousNode = undefined; + } + else if (sep === ',') { + const last = segments[segments.length - 1]; + if (typeof last === 'number') { + segments[segments.length - 1] = last + 1; + } + else { + isAtPropertyKey = true; + segments[segments.length - 1] = ''; + } + previousNode = undefined; + } + } + }); + } + catch (e) { + if (e !== earlyReturnException) { + throw e; + } + } + return { + path: segments, + previousNode, + isAtPropertyKey, + matches: (pattern) => { + let k = 0; + for (let i = 0; k < pattern.length && i < segments.length; i++) { + if (pattern[k] === segments[i] || pattern[k] === '*') { + k++; + } + else if (pattern[k] !== '**') { + return false; + } + } + return k === pattern.length; + } + }; + } + exports.getLocation = getLocation; + /** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore always check the errors list to find out if the input was valid. + */ + function parse(text, errors = [], options = ParseOptions.DEFAULT) { + let currentProperty = null; + let currentParent = []; + const previousParents = []; + function onValue(value) { + if (Array.isArray(currentParent)) { + currentParent.push(value); + } + else if (currentProperty !== null) { + currentParent[currentProperty] = value; + } + } + const visitor = { + onObjectBegin: () => { + const object = {}; + onValue(object); + previousParents.push(currentParent); + currentParent = object; + currentProperty = null; + }, + onObjectProperty: (name) => { + currentProperty = name; + }, + onObjectEnd: () => { + currentParent = previousParents.pop(); + }, + onArrayBegin: () => { + const array = []; + onValue(array); + previousParents.push(currentParent); + currentParent = array; + currentProperty = null; + }, + onArrayEnd: () => { + currentParent = previousParents.pop(); + }, + onLiteralValue: onValue, + onError: (error, offset, length) => { + errors.push({ error, offset, length }); + } + }; + visit(text, visitor, options); + return currentParent[0]; + } + exports.parse = parse; + /** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ + function parseTree(text, errors = [], options = ParseOptions.DEFAULT) { + let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root + function ensurePropertyComplete(endOffset) { + if (currentParent.type === 'property') { + currentParent.length = endOffset - currentParent.offset; + currentParent = currentParent.parent; + } + } + function onValue(valueNode) { + currentParent.children.push(valueNode); + return valueNode; + } + const visitor = { + onObjectBegin: (offset) => { + currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); + }, + onObjectProperty: (name, offset, length) => { + currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); + currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); + }, + onObjectEnd: (offset, length) => { + ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onArrayBegin: (offset, length) => { + currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); + }, + onArrayEnd: (offset, length) => { + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onLiteralValue: (value, offset, length) => { + onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); + ensurePropertyComplete(offset + length); + }, + onSeparator: (sep, offset, length) => { + if (currentParent.type === 'property') { + if (sep === ':') { + currentParent.colonOffset = offset; + } + else if (sep === ',') { + ensurePropertyComplete(offset); + } + } + }, + onError: (error, offset, length) => { + errors.push({ error, offset, length }); + } + }; + visit(text, visitor, options); + const result = currentParent.children[0]; + if (result) { + delete result.parent; + } + return result; + } + exports.parseTree = parseTree; + /** + * Finds the node at the given path in a JSON DOM. + */ + function findNodeAtLocation(root, path) { + if (!root) { + return undefined; + } + let node = root; + for (let segment of path) { + if (typeof segment === 'string') { + if (node.type !== 'object' || !Array.isArray(node.children)) { + return undefined; + } + let found = false; + for (const propertyNode of node.children) { + if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { + node = propertyNode.children[1]; + found = true; + break; + } + } + if (!found) { + return undefined; + } + } + else { + const index = segment; + if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { + return undefined; + } + node = node.children[index]; + } + } + return node; + } + exports.findNodeAtLocation = findNodeAtLocation; + /** + * Gets the JSON path of the given JSON DOM node + */ + function getNodePath(node) { + if (!node.parent || !node.parent.children) { + return []; + } + const path = getNodePath(node.parent); + if (node.parent.type === 'property') { + const key = node.parent.children[0].value; + path.push(key); + } + else if (node.parent.type === 'array') { + const index = node.parent.children.indexOf(node); + if (index !== -1) { + path.push(index); + } + } + return path; + } + exports.getNodePath = getNodePath; + /** + * Evaluates the JavaScript object of the given JSON DOM node + */ + function getNodeValue(node) { + switch (node.type) { + case 'array': + return node.children.map(getNodeValue); + case 'object': + const obj = Object.create(null); + for (let prop of node.children) { + const valueNode = prop.children[1]; + if (valueNode) { + obj[prop.children[0].value] = getNodeValue(valueNode); + } + } + return obj; + case 'null': + case 'string': + case 'number': + case 'boolean': + return node.value; + default: + return undefined; + } + } + exports.getNodeValue = getNodeValue; + function contains(node, offset, includeRightBound = false) { + return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); + } + exports.contains = contains; + /** + * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ + function findNodeAtOffset(node, offset, includeRightBound = false) { + if (contains(node, offset, includeRightBound)) { + const children = node.children; + if (Array.isArray(children)) { + for (let i = 0; i < children.length && children[i].offset <= offset; i++) { + const item = findNodeAtOffset(children[i], offset, includeRightBound); + if (item) { + return item; + } + } + } + return node; + } + return undefined; + } + exports.findNodeAtOffset = findNodeAtOffset; + /** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ + function visit(text, visitor, options = ParseOptions.DEFAULT) { + const _scanner = (0, scanner_1.createScanner)(text, false); + // Important: Only pass copies of this to visitor functions to prevent accidental modification, and + // to not affect visitor functions which stored a reference to a previous JSONPath + const _jsonPath = []; + function toNoArgVisit(visitFunction) { + return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toNoArgVisitWithPath(visitFunction) { + return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + function toOneArgVisit(visitFunction) { + return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toOneArgVisitWithPath(visitFunction) { + return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); + const disallowComments = options && options.disallowComments; + const allowTrailingComma = options && options.allowTrailingComma; + function scanNext() { + while (true) { + const token = _scanner.scan(); + switch (_scanner.getTokenError()) { + case 4 /* ScanError.InvalidUnicode */: + handleError(14 /* ParseErrorCode.InvalidUnicode */); + break; + case 5 /* ScanError.InvalidEscapeCharacter */: + handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */); + break; + case 3 /* ScanError.UnexpectedEndOfNumber */: + handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */); + break; + case 1 /* ScanError.UnexpectedEndOfComment */: + if (!disallowComments) { + handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */); + } + break; + case 2 /* ScanError.UnexpectedEndOfString */: + handleError(12 /* ParseErrorCode.UnexpectedEndOfString */); + break; + case 6 /* ScanError.InvalidCharacter */: + handleError(16 /* ParseErrorCode.InvalidCharacter */); + break; + } + switch (token) { + case 12 /* SyntaxKind.LineCommentTrivia */: + case 13 /* SyntaxKind.BlockCommentTrivia */: + if (disallowComments) { + handleError(10 /* ParseErrorCode.InvalidCommentToken */); + } + else { + onComment(); + } + break; + case 16 /* SyntaxKind.Unknown */: + handleError(1 /* ParseErrorCode.InvalidSymbol */); + break; + case 15 /* SyntaxKind.Trivia */: + case 14 /* SyntaxKind.LineBreakTrivia */: + break; + default: + return token; + } + } + } + function handleError(error, skipUntilAfter = [], skipUntil = []) { + onError(error); + if (skipUntilAfter.length + skipUntil.length > 0) { + let token = _scanner.getToken(); + while (token !== 17 /* SyntaxKind.EOF */) { + if (skipUntilAfter.indexOf(token) !== -1) { + scanNext(); + break; + } + else if (skipUntil.indexOf(token) !== -1) { + break; + } + token = scanNext(); + } + } + } + function parseString(isValue) { + const value = _scanner.getTokenValue(); + if (isValue) { + onLiteralValue(value); + } + else { + onObjectProperty(value); + // add property name afterwards + _jsonPath.push(value); + } + scanNext(); + return true; + } + function parseLiteral() { + switch (_scanner.getToken()) { + case 11 /* SyntaxKind.NumericLiteral */: + const tokenValue = _scanner.getTokenValue(); + let value = Number(tokenValue); + if (isNaN(value)) { + handleError(2 /* ParseErrorCode.InvalidNumberFormat */); + value = 0; + } + onLiteralValue(value); + break; + case 7 /* SyntaxKind.NullKeyword */: + onLiteralValue(null); + break; + case 8 /* SyntaxKind.TrueKeyword */: + onLiteralValue(true); + break; + case 9 /* SyntaxKind.FalseKeyword */: + onLiteralValue(false); + break; + default: + return false; + } + scanNext(); + return true; + } + function parseProperty() { + if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) { + handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + return false; + } + parseString(false); + if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) { + onSeparator(':'); + scanNext(); // consume colon + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + } + else { + handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + _jsonPath.pop(); // remove processed property name + return true; + } + function parseObject() { + onObjectBegin(); + scanNext(); // consume open brace + let needsComma = false; + while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { + if (!needsComma) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + } + onSeparator(','); + scanNext(); // consume comma + if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) { + break; + } + } + else if (needsComma) { + handleError(6 /* ParseErrorCode.CommaExpected */, [], []); + } + if (!parseProperty()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + needsComma = true; + } + onObjectEnd(); + if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) { + handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []); + } + else { + scanNext(); // consume close brace + } + return true; + } + function parseArray() { + onArrayBegin(); + scanNext(); // consume open bracket + let isFirstElement = true; + let needsComma = false; + while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { + if (!needsComma) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + } + onSeparator(','); + scanNext(); // consume comma + if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) { + break; + } + } + else if (needsComma) { + handleError(6 /* ParseErrorCode.CommaExpected */, [], []); + } + if (isFirstElement) { + _jsonPath.push(0); + isFirstElement = false; + } + else { + _jsonPath[_jsonPath.length - 1]++; + } + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]); + } + needsComma = true; + } + onArrayEnd(); + if (!isFirstElement) { + _jsonPath.pop(); // remove array index + } + if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) { + handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []); + } + else { + scanNext(); // consume close bracket + } + return true; + } + function parseValue() { + switch (_scanner.getToken()) { + case 3 /* SyntaxKind.OpenBracketToken */: + return parseArray(); + case 1 /* SyntaxKind.OpenBraceToken */: + return parseObject(); + case 10 /* SyntaxKind.StringLiteral */: + return parseString(true); + default: + return parseLiteral(); + } + } + scanNext(); + if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) { + if (options.allowEmptyContent) { + return true; + } + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + return false; + } + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + return false; + } + if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []); + } + return true; + } + exports.visit = visit; + /** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ + function stripComments(text, replaceCh) { + let _scanner = (0, scanner_1.createScanner)(text), parts = [], kind, offset = 0, pos; + do { + pos = _scanner.getPosition(); + kind = _scanner.scan(); + switch (kind) { + case 12 /* SyntaxKind.LineCommentTrivia */: + case 13 /* SyntaxKind.BlockCommentTrivia */: + case 17 /* SyntaxKind.EOF */: + if (offset !== pos) { + parts.push(text.substring(offset, pos)); + } + if (replaceCh !== undefined) { + parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); + } + offset = _scanner.getPosition(); + break; + } + } while (kind !== 17 /* SyntaxKind.EOF */); + return parts.join(''); + } + exports.stripComments = stripComments; + function getNodeType(value) { + switch (typeof value) { + case 'boolean': return 'boolean'; + case 'number': return 'number'; + case 'string': return 'string'; + case 'object': { + if (!value) { + return 'null'; + } + else if (Array.isArray(value)) { + return 'array'; + } + return 'object'; + } + default: return 'null'; + } + } + exports.getNodeType = getNodeType; +}); diff --git a/web/node_modules/jsonc-parser/lib/umd/impl/scanner.js b/web/node_modules/jsonc-parser/lib/umd/impl/scanner.js new file mode 100644 index 0000000000000000000000000000000000000000..ebca65f49cc2507b2ca0f8cd784dfdf414896dd7 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/impl/scanner.js @@ -0,0 +1,456 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + /*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createScanner = void 0; + /** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ + function createScanner(text, ignoreTrivia = false) { + const len = text.length; + let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */; + function scanHexDigits(count, exact) { + let digits = 0; + let value = 0; + while (digits < count || !exact) { + let ch = text.charCodeAt(pos); + if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) { + value = value * 16 + ch - 48 /* CharacterCodes._0 */; + } + else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) { + value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10; + } + else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) { + value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10; + } + else { + break; + } + pos++; + digits++; + } + if (digits < count) { + value = -1; + } + return value; + } + function setPosition(newPosition) { + pos = newPosition; + value = ''; + tokenOffset = 0; + token = 16 /* SyntaxKind.Unknown */; + scanError = 0 /* ScanError.None */; + } + function scanNumber() { + let start = pos; + if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) { + pos++; + } + else { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + } + if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) { + pos++; + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + } + else { + scanError = 3 /* ScanError.UnexpectedEndOfNumber */; + return text.substring(start, pos); + } + } + let end = pos; + if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) { + pos++; + if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) { + pos++; + } + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + end = pos; + } + else { + scanError = 3 /* ScanError.UnexpectedEndOfNumber */; + } + } + return text.substring(start, end); + } + function scanString() { + let result = '', start = pos; + while (true) { + if (pos >= len) { + result += text.substring(start, pos); + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + const ch = text.charCodeAt(pos); + if (ch === 34 /* CharacterCodes.doubleQuote */) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* CharacterCodes.backslash */) { + result += text.substring(start, pos); + pos++; + if (pos >= len) { + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + const ch2 = text.charCodeAt(pos++); + switch (ch2) { + case 34 /* CharacterCodes.doubleQuote */: + result += '\"'; + break; + case 92 /* CharacterCodes.backslash */: + result += '\\'; + break; + case 47 /* CharacterCodes.slash */: + result += '/'; + break; + case 98 /* CharacterCodes.b */: + result += '\b'; + break; + case 102 /* CharacterCodes.f */: + result += '\f'; + break; + case 110 /* CharacterCodes.n */: + result += '\n'; + break; + case 114 /* CharacterCodes.r */: + result += '\r'; + break; + case 116 /* CharacterCodes.t */: + result += '\t'; + break; + case 117 /* CharacterCodes.u */: + const ch3 = scanHexDigits(4, true); + if (ch3 >= 0) { + result += String.fromCharCode(ch3); + } + else { + scanError = 4 /* ScanError.InvalidUnicode */; + } + break; + default: + scanError = 5 /* ScanError.InvalidEscapeCharacter */; + } + start = pos; + continue; + } + if (ch >= 0 && ch <= 0x1f) { + if (isLineBreak(ch)) { + result += text.substring(start, pos); + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + else { + scanError = 6 /* ScanError.InvalidCharacter */; + // mark as error but continue with string + } + } + pos++; + } + return result; + } + function scanNext() { + value = ''; + scanError = 0 /* ScanError.None */; + tokenOffset = pos; + lineStartOffset = lineNumber; + prevTokenLineStartOffset = tokenLineStartOffset; + if (pos >= len) { + // at the end + tokenOffset = len; + return token = 17 /* SyntaxKind.EOF */; + } + let code = text.charCodeAt(pos); + // trivia: whitespace + if (isWhiteSpace(code)) { + do { + pos++; + value += String.fromCharCode(code); + code = text.charCodeAt(pos); + } while (isWhiteSpace(code)); + return token = 15 /* SyntaxKind.Trivia */; + } + // trivia: newlines + if (isLineBreak(code)) { + pos++; + value += String.fromCharCode(code); + if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { + pos++; + value += '\n'; + } + lineNumber++; + tokenLineStartOffset = pos; + return token = 14 /* SyntaxKind.LineBreakTrivia */; + } + switch (code) { + // tokens: []{}:, + case 123 /* CharacterCodes.openBrace */: + pos++; + return token = 1 /* SyntaxKind.OpenBraceToken */; + case 125 /* CharacterCodes.closeBrace */: + pos++; + return token = 2 /* SyntaxKind.CloseBraceToken */; + case 91 /* CharacterCodes.openBracket */: + pos++; + return token = 3 /* SyntaxKind.OpenBracketToken */; + case 93 /* CharacterCodes.closeBracket */: + pos++; + return token = 4 /* SyntaxKind.CloseBracketToken */; + case 58 /* CharacterCodes.colon */: + pos++; + return token = 6 /* SyntaxKind.ColonToken */; + case 44 /* CharacterCodes.comma */: + pos++; + return token = 5 /* SyntaxKind.CommaToken */; + // strings + case 34 /* CharacterCodes.doubleQuote */: + pos++; + value = scanString(); + return token = 10 /* SyntaxKind.StringLiteral */; + // comments + case 47 /* CharacterCodes.slash */: + const start = pos - 1; + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { + pos += 2; + while (pos < len) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + value = text.substring(start, pos); + return token = 12 /* SyntaxKind.LineCommentTrivia */; + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) { + pos += 2; + const safeLength = len - 1; // For lookahead. + let commentClosed = false; + while (pos < safeLength) { + const ch = text.charCodeAt(pos); + if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { + pos += 2; + commentClosed = true; + break; + } + pos++; + if (isLineBreak(ch)) { + if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { + pos++; + } + lineNumber++; + tokenLineStartOffset = pos; + } + } + if (!commentClosed) { + pos++; + scanError = 1 /* ScanError.UnexpectedEndOfComment */; + } + value = text.substring(start, pos); + return token = 13 /* SyntaxKind.BlockCommentTrivia */; + } + // just a single slash + value += String.fromCharCode(code); + pos++; + return token = 16 /* SyntaxKind.Unknown */; + // numbers + case 45 /* CharacterCodes.minus */: + value += String.fromCharCode(code); + pos++; + if (pos === len || !isDigit(text.charCodeAt(pos))) { + return token = 16 /* SyntaxKind.Unknown */; + } + // found a minus, followed by a number so + // we fall through to proceed with scanning + // numbers + case 48 /* CharacterCodes._0 */: + case 49 /* CharacterCodes._1 */: + case 50 /* CharacterCodes._2 */: + case 51 /* CharacterCodes._3 */: + case 52 /* CharacterCodes._4 */: + case 53 /* CharacterCodes._5 */: + case 54 /* CharacterCodes._6 */: + case 55 /* CharacterCodes._7 */: + case 56 /* CharacterCodes._8 */: + case 57 /* CharacterCodes._9 */: + value += scanNumber(); + return token = 11 /* SyntaxKind.NumericLiteral */; + // literals and unknown symbols + default: + // is a literal? Read the full word. + while (pos < len && isUnknownContentCharacter(code)) { + pos++; + code = text.charCodeAt(pos); + } + if (tokenOffset !== pos) { + value = text.substring(tokenOffset, pos); + // keywords: true, false, null + switch (value) { + case 'true': return token = 8 /* SyntaxKind.TrueKeyword */; + case 'false': return token = 9 /* SyntaxKind.FalseKeyword */; + case 'null': return token = 7 /* SyntaxKind.NullKeyword */; + } + return token = 16 /* SyntaxKind.Unknown */; + } + // some + value += String.fromCharCode(code); + pos++; + return token = 16 /* SyntaxKind.Unknown */; + } + } + function isUnknownContentCharacter(code) { + if (isWhiteSpace(code) || isLineBreak(code)) { + return false; + } + switch (code) { + case 125 /* CharacterCodes.closeBrace */: + case 93 /* CharacterCodes.closeBracket */: + case 123 /* CharacterCodes.openBrace */: + case 91 /* CharacterCodes.openBracket */: + case 34 /* CharacterCodes.doubleQuote */: + case 58 /* CharacterCodes.colon */: + case 44 /* CharacterCodes.comma */: + case 47 /* CharacterCodes.slash */: + return false; + } + return true; + } + function scanNextNonTrivia() { + let result; + do { + result = scanNext(); + } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */); + return result; + } + return { + setPosition: setPosition, + getPosition: () => pos, + scan: ignoreTrivia ? scanNextNonTrivia : scanNext, + getToken: () => token, + getTokenValue: () => value, + getTokenOffset: () => tokenOffset, + getTokenLength: () => pos - tokenOffset, + getTokenStartLine: () => lineStartOffset, + getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, + getTokenError: () => scanError, + }; + } + exports.createScanner = createScanner; + function isWhiteSpace(ch) { + return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */; + } + function isLineBreak(ch) { + return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */; + } + function isDigit(ch) { + return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */; + } + var CharacterCodes; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + })(CharacterCodes || (CharacterCodes = {})); +}); diff --git a/web/node_modules/jsonc-parser/lib/umd/impl/string-intern.js b/web/node_modules/jsonc-parser/lib/umd/impl/string-intern.js new file mode 100644 index 0000000000000000000000000000000000000000..177f2d72734a7fdad28df179e9d00e32bf17657c --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/impl/string-intern.js @@ -0,0 +1,42 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.supportedEols = exports.cachedBreakLinesWithSpaces = exports.cachedSpaces = void 0; + exports.cachedSpaces = new Array(20).fill(0).map((_, index) => { + return ' '.repeat(index); + }); + const maxCachedValues = 200; + exports.cachedBreakLinesWithSpaces = { + ' ': { + '\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\n' + ' '.repeat(index); + }), + '\r': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r' + ' '.repeat(index); + }), + '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r\n' + ' '.repeat(index); + }), + }, + '\t': { + '\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\n' + '\t'.repeat(index); + }), + '\r': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r' + '\t'.repeat(index); + }), + '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { + return '\r\n' + '\t'.repeat(index); + }), + } + }; + exports.supportedEols = ['\n', '\r', '\r\n']; +}); diff --git a/web/node_modules/jsonc-parser/lib/umd/main.d.ts b/web/node_modules/jsonc-parser/lib/umd/main.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7312a36d4f48d03e354ba9c4e45fc28947d33894 --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/main.d.ts @@ -0,0 +1,349 @@ +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +export declare const createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner; +export declare const enum ScanError { + None = 0, + UnexpectedEndOfComment = 1, + UnexpectedEndOfString = 2, + UnexpectedEndOfNumber = 3, + InvalidUnicode = 4, + InvalidEscapeCharacter = 5, + InvalidCharacter = 6 +} +export declare const enum SyntaxKind { + OpenBraceToken = 1, + CloseBraceToken = 2, + OpenBracketToken = 3, + CloseBracketToken = 4, + CommaToken = 5, + ColonToken = 6, + NullKeyword = 7, + TrueKeyword = 8, + FalseKeyword = 9, + StringLiteral = 10, + NumericLiteral = 11, + LineCommentTrivia = 12, + BlockCommentTrivia = 13, + LineBreakTrivia = 14, + Trivia = 15, + Unknown = 16, + EOF = 17 +} +/** + * The scanner object, representing a JSON scanner at a position in the input string. + */ +export interface JSONScanner { + /** + * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token. + */ + setPosition(pos: number): void; + /** + * Read the next token. Returns the token code. + */ + scan(): SyntaxKind; + /** + * Returns the zero-based current scan position, which is after the last read token. + */ + getPosition(): number; + /** + * Returns the last read token. + */ + getToken(): SyntaxKind; + /** + * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false. + */ + getTokenValue(): string; + /** + * The zero-based start offset of the last read token. + */ + getTokenOffset(): number; + /** + * The length of the last read token. + */ + getTokenLength(): number; + /** + * The zero-based start line number of the last read token. + */ + getTokenStartLine(): number; + /** + * The zero-based start character (column) of the last read token. + */ + getTokenStartCharacter(): number; + /** + * An error code of the last scan. + */ + getTokenError(): ScanError; +} +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +export declare const getLocation: (text: string, position: number) => Location; +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore, always check the errors list to find out if the input was valid. + */ +export declare const parse: (text: string, errors?: ParseError[], options?: ParseOptions) => any; +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +export declare const parseTree: (text: string, errors?: ParseError[], options?: ParseOptions) => Node | undefined; +/** + * Finds the node at the given path in a JSON DOM. + */ +export declare const findNodeAtLocation: (root: Node, path: JSONPath) => Node | undefined; +/** + * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +export declare const findNodeAtOffset: (root: Node, offset: number, includeRightBound?: boolean) => Node | undefined; +/** + * Gets the JSON path of the given JSON DOM node + */ +export declare const getNodePath: (node: Node) => JSONPath; +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +export declare const getNodeValue: (node: Node) => any; +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +export declare const visit: (text: string, visitor: JSONVisitor, options?: ParseOptions) => any; +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +export declare const stripComments: (text: string, replaceCh?: string) => string; +export interface ParseError { + error: ParseErrorCode; + offset: number; + length: number; +} +export declare const enum ParseErrorCode { + InvalidSymbol = 1, + InvalidNumberFormat = 2, + PropertyNameExpected = 3, + ValueExpected = 4, + ColonExpected = 5, + CommaExpected = 6, + CloseBraceExpected = 7, + CloseBracketExpected = 8, + EndOfFileExpected = 9, + InvalidCommentToken = 10, + UnexpectedEndOfComment = 11, + UnexpectedEndOfString = 12, + UnexpectedEndOfNumber = 13, + InvalidUnicode = 14, + InvalidEscapeCharacter = 15, + InvalidCharacter = 16 +} +export declare function printParseErrorCode(code: ParseErrorCode): "InvalidSymbol" | "InvalidNumberFormat" | "PropertyNameExpected" | "ValueExpected" | "ColonExpected" | "CommaExpected" | "CloseBraceExpected" | "CloseBracketExpected" | "EndOfFileExpected" | "InvalidCommentToken" | "UnexpectedEndOfComment" | "UnexpectedEndOfString" | "UnexpectedEndOfNumber" | "InvalidUnicode" | "InvalidEscapeCharacter" | "InvalidCharacter" | ""; +export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null'; +export interface Node { + readonly type: NodeType; + readonly value?: any; + readonly offset: number; + readonly length: number; + readonly colonOffset?: number; + readonly parent?: Node; + readonly children?: Node[]; +} +/** + * A {@linkcode JSONPath} segment. Either a string representing an object property name + * or a number (starting at 0) for array indices. + */ +export type Segment = string | number; +export type JSONPath = Segment[]; +export interface Location { + /** + * The previous property key or literal value (string, number, boolean or null) or undefined. + */ + previousNode?: Node; + /** + * The path describing the location in the JSON document. The path consists of a sequence of strings + * representing an object property or numbers for array indices. + */ + path: JSONPath; + /** + * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). + * '*' will match a single segment of any property name or index. + * '**' will match a sequence of segments of any property name or index, or no segment. + */ + matches: (patterns: JSONPath) => boolean; + /** + * If set, the location's offset is at a property key. + */ + isAtPropertyKey: boolean; +} +export interface ParseOptions { + disallowComments?: boolean; + allowTrailingComma?: boolean; + allowEmptyContent?: boolean; +} +/** + * Visitor called by {@linkcode visit} when parsing JSON. + * + * The visitor functions have the following common parameters: + * - `offset`: Global offset within the JSON document, starting at 0 + * - `startLine`: Line number, starting at 0 + * - `startCharacter`: Start character (column) within the current line, starting at 0 + * + * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the + * current `JSONPath` within the document. + */ +export interface JSONVisitor { + /** + * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. + */ + onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a property is encountered. The offset and length represent the location of the property name. + * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the + * property name yet. + */ + onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. + */ + onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. + */ + onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. + */ + onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. + */ + onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; + /** + * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. + */ + onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment. + */ + onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void; + /** + * Invoked on an error. + */ + onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void; +} +/** + * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation. + * It consist of one or more edits describing insertions, replacements or removals of text segments. + * * The offsets of the edits refer to the original state of the document. + * * No two edits change or remove the same range of text in the original document. + * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. + * * The order in the array defines which edit is applied first. + * To apply an edit result use {@linkcode applyEdits}. + * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data. + */ +export type EditResult = Edit[]; +/** + * Represents a text modification + */ +export interface Edit { + /** + * The start offset of the modification. + */ + offset: number; + /** + * The length of the modification. Must not be negative. Empty length represents an *insert*. + */ + length: number; + /** + * The new content. Empty content represents a *remove*. + */ + content: string; +} +/** + * A text range in the document +*/ +export interface Range { + /** + * The start offset of the range. + */ + offset: number; + /** + * The length of the range. Must not be negative. + */ + length: number; +} +/** + * Options used by {@linkcode format} when computing the formatting edit operations + */ +export interface FormattingOptions { + /** + * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent. + */ + tabSize?: number; + /** + * Is indentation based on spaces? + */ + insertSpaces?: boolean; + /** + * The default 'end of line' character. If not set, '\n' is used as default. + */ + eol?: string; + /** + * If set, will add a new line at the end of the document. + */ + insertFinalNewline?: boolean; + /** + * If true, will keep line positions as is in the formatting + */ + keepLines?: boolean; +} +/** + * Computes the edit operations needed to format a JSON document. + * + * @param documentText The input text + * @param range The range to format or `undefined` to format the full content + * @param options The formatting options + * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): EditResult; +/** + * Options used by {@linkcode modify} when computing the modification edit operations + */ +export interface ModificationOptions { + /** + * Formatting options. If undefined, the newly inserted code will be inserted unformatted. + */ + formattingOptions?: FormattingOptions; + /** + * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then + * {@linkcode modify} will insert a new item at that location instead of overwriting its contents. + */ + isArrayInsertion?: boolean; + /** + * Optional function to define the insertion index given an existing list of properties. + */ + getInsertionIndex?: (properties: string[]) => number; +} +/** + * Computes the edit operations needed to modify a value in the JSON document. + * + * @param documentText The input text + * @param path The path of the value to change. The path represents either to the document root, a property or an array item. + * If the path points to an non-existing property or item, it will be created. + * @param value The new value for the specified property or item. If the value is undefined, + * the property or item will be removed. + * @param options Options + * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult; +/** + * Applies edits to an input string. + * @param text The input text + * @param edits Edit operations following the format described in {@linkcode EditResult}. + * @returns The text with the applied edits. + * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. + */ +export declare function applyEdits(text: string, edits: EditResult): string; diff --git a/web/node_modules/jsonc-parser/lib/umd/main.js b/web/node_modules/jsonc-parser/lib/umd/main.js new file mode 100644 index 0000000000000000000000000000000000000000..2ed744665430578caebcb12053150fbf4d7e76da --- /dev/null +++ b/web/node_modules/jsonc-parser/lib/umd/main.js @@ -0,0 +1,194 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "./impl/format", "./impl/edit", "./impl/scanner", "./impl/parser"], factory); + } +})(function (require, exports) { + /*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.applyEdits = exports.modify = exports.format = exports.printParseErrorCode = exports.ParseErrorCode = exports.stripComments = exports.visit = exports.getNodeValue = exports.getNodePath = exports.findNodeAtOffset = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = exports.SyntaxKind = exports.ScanError = exports.createScanner = void 0; + const formatter = require("./impl/format"); + const edit = require("./impl/edit"); + const scanner = require("./impl/scanner"); + const parser = require("./impl/parser"); + /** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ + exports.createScanner = scanner.createScanner; + var ScanError; + (function (ScanError) { + ScanError[ScanError["None"] = 0] = "None"; + ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; + ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; + ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; + ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; + ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; + ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter"; + })(ScanError || (exports.ScanError = ScanError = {})); + var SyntaxKind; + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; + SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; + SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; + SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; + SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; + SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; + SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; + SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF"; + })(SyntaxKind || (exports.SyntaxKind = SyntaxKind = {})); + /** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ + exports.getLocation = parser.getLocation; + /** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore, always check the errors list to find out if the input was valid. + */ + exports.parse = parser.parse; + /** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ + exports.parseTree = parser.parseTree; + /** + * Finds the node at the given path in a JSON DOM. + */ + exports.findNodeAtLocation = parser.findNodeAtLocation; + /** + * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ + exports.findNodeAtOffset = parser.findNodeAtOffset; + /** + * Gets the JSON path of the given JSON DOM node + */ + exports.getNodePath = parser.getNodePath; + /** + * Evaluates the JavaScript object of the given JSON DOM node + */ + exports.getNodeValue = parser.getNodeValue; + /** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ + exports.visit = parser.visit; + /** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ + exports.stripComments = parser.stripComments; + var ParseErrorCode; + (function (ParseErrorCode) { + ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; + ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; + ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; + ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; + ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; + ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; + ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; + ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; + ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; + ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; + ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; + ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; + ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter"; + })(ParseErrorCode || (exports.ParseErrorCode = ParseErrorCode = {})); + function printParseErrorCode(code) { + switch (code) { + case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol'; + case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat'; + case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected'; + case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected'; + case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected'; + case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected'; + case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected'; + case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected'; + case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected'; + case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken'; + case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; + case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString'; + case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; + case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode'; + case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; + case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter'; + } + return ''; + } + exports.printParseErrorCode = printParseErrorCode; + /** + * Computes the edit operations needed to format a JSON document. + * + * @param documentText The input text + * @param range The range to format or `undefined` to format the full content + * @param options The formatting options + * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ + function format(documentText, range, options) { + return formatter.format(documentText, range, options); + } + exports.format = format; + /** + * Computes the edit operations needed to modify a value in the JSON document. + * + * @param documentText The input text + * @param path The path of the value to change. The path represents either to the document root, a property or an array item. + * If the path points to an non-existing property or item, it will be created. + * @param value The new value for the specified property or item. If the value is undefined, + * the property or item will be removed. + * @param options Options + * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ + function modify(text, path, value, options) { + return edit.setProperty(text, path, value, options); + } + exports.modify = modify; + /** + * Applies edits to an input string. + * @param text The input text + * @param edits Edit operations following the format described in {@linkcode EditResult}. + * @returns The text with the applied edits. + * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. + */ + function applyEdits(text, edits) { + let sortedEdits = edits.slice(0).sort((a, b) => { + const diff = a.offset - b.offset; + if (diff === 0) { + return a.length - b.length; + } + return diff; + }); + let lastModifiedOffset = text.length; + for (let i = sortedEdits.length - 1; i >= 0; i--) { + let e = sortedEdits[i]; + if (e.offset + e.length <= lastModifiedOffset) { + text = edit.applyEdit(text, e); + } + else { + throw new Error('Overlapping edit'); + } + lastModifiedOffset = e.offset; + } + return text; + } + exports.applyEdits = applyEdits; +}); diff --git a/web/node_modules/jsonc-parser/package.json b/web/node_modules/jsonc-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..da7a76b27709ed983d4c62c132e278b0da791872 --- /dev/null +++ b/web/node_modules/jsonc-parser/package.json @@ -0,0 +1,37 @@ +{ + "name": "jsonc-parser", + "version": "3.2.1", + "description": "Scanner and parser for JSON with comments.", + "main": "./lib/umd/main.js", + "typings": "./lib/umd/main.d.ts", + "module": "./lib/esm/main.js", + "author": "Microsoft Corporation", + "repository": { + "type": "git", + "url": "https://github.com/microsoft/node-jsonc-parser" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/microsoft/node-jsonc-parser/issues" + }, + "devDependencies": { + "mocha": "^10.2.0", + "typescript": "^5.3.3", + "@types/node": "^16.x", + "@types/mocha": "^10.0.6", + "@typescript-eslint/eslint-plugin": "^6.19.1", + "@typescript-eslint/parser": "^6.19.1", + "eslint": "^8.56.0", + "rimraf": "^5.0.5" + }, + "scripts": { + "prepack": "npm run clean && npm run compile-esm && npm run test && npm run remove-sourcemap-refs", + "compile": "tsc -p ./src && npm run lint", + "compile-esm": "tsc -p ./src/tsconfig.esm.json", + "remove-sourcemap-refs": "node ./build/remove-sourcemap-refs.js", + "clean": "rimraf lib", + "watch": "tsc -w -p ./src", + "test": "npm run compile && mocha ./lib/umd/test", + "lint": "eslint src/**/*.ts" + } +} diff --git a/web/node_modules/local-pkg/LICENSE b/web/node_modules/local-pkg/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d47cea55b87848029cce30f4ce7dfb0c7c1c5394 --- /dev/null +++ b/web/node_modules/local-pkg/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Anthony Fu + +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/web/node_modules/local-pkg/README.md b/web/node_modules/local-pkg/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d47aca18f7addb1c5806015b7d67a5aa5419d8ff --- /dev/null +++ b/web/node_modules/local-pkg/README.md @@ -0,0 +1,56 @@ +# local-pkg + +[![NPM version](https://img.shields.io/npm/v/local-pkg?color=a1b858&label=)](https://www.npmjs.com/package/local-pkg) + +Get information on local packages. Works on both CJS and ESM. + +## Install + +```bash +npm i local-pkg +``` + +## Usage + +```ts +import { + getPackageInfo, + importModule, + isPackageExists, + resolveModule, +} from 'local-pkg' + +isPackageExists('local-pkg') // true +isPackageExists('foo') // false + +await getPackageInfo('local-pkg') +/* { + * name: "local-pkg", + * version: "0.1.0", + * rootPath: "/path/to/node_modules/local-pkg", + * packageJson: { + * ... + * } + * } + */ + +// similar to `require.resolve` but works also in ESM +resolveModule('local-pkg') +// '/path/to/node_modules/local-pkg/dist/index.cjs' + +// similar to `await import()` but works also in CJS +const { importModule } = await importModule('local-pkg') +``` + + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu) diff --git a/web/node_modules/local-pkg/dist/index.cjs b/web/node_modules/local-pkg/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..37896a14cefc0d599ae982fe98f88f27ce591843 --- /dev/null +++ b/web/node_modules/local-pkg/dist/index.cjs @@ -0,0 +1,397 @@ +'use strict'; + +const path = require('node:path'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const process = require('node:process'); +const mlly = require('mlly'); +const node_url = require('node:url'); + +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } + +const path__default = /*#__PURE__*/_interopDefaultCompat(path); +const fs__default = /*#__PURE__*/_interopDefaultCompat(fs); +const fsp__default = /*#__PURE__*/_interopDefaultCompat(fsp); +const process__default = /*#__PURE__*/_interopDefaultCompat(process); + +/* +How it works: +`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value. +*/ + +class Node { + value; + next; + + constructor(value) { + this.value = value; + } +} + +class Queue { + #head; + #tail; + #size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this.#head) { + this.#tail.next = node; + this.#tail = node; + } else { + this.#head = node; + this.#tail = node; + } + + this.#size++; + } + + dequeue() { + const current = this.#head; + if (!current) { + return; + } + + this.#head = this.#head.next; + this.#size--; + return current.value; + } + + clear() { + this.#head = undefined; + this.#tail = undefined; + this.#size = 0; + } + + get size() { + return this.#size; + } + + * [Symbol.iterator]() { + let current = this.#head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +function pLimit(concurrency) { + if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, args) => { + queue.enqueue(run.bind(undefined, fn, resolve, args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount, + }, + pendingCount: { + get: () => queue.size, + }, + clearQueue: { + value: () => { + queue.clear(); + }, + }, + }); + + return generator; +} + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it. +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both. +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +async function pLocate( + iterable, + tester, + { + concurrency = Number.POSITIVE_INFINITY, + preserveOrder = true, + } = {}, +) { + const limit = pLimit(concurrency); + + // Start all the promises concurrently with optional limit. + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently. + const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +} + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile', +}; + +function checkType(type) { + if (Object.hasOwnProperty.call(typeMappings, type)) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => stat[typeMappings[type]](); + +const toPath$1 = urlOrPath => urlOrPath instanceof URL ? node_url.fileURLToPath(urlOrPath) : urlOrPath; + +async function locatePath( + paths, + { + cwd = process__default.cwd(), + type = 'file', + allowSymlinks = true, + concurrency, + preserveOrder, + } = {}, +) { + checkType(type); + cwd = toPath$1(cwd); + + const statFunction = allowSymlinks ? fs.promises.stat : fs.promises.lstat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFunction(path__default.resolve(cwd, path_)); + return matchType(type, stat); + } catch { + return false; + } + }, {concurrency, preserveOrder}); +} + +const toPath = urlOrPath => urlOrPath instanceof URL ? node_url.fileURLToPath(urlOrPath) : urlOrPath; + +const findUpStop = Symbol('findUpStop'); + +async function findUpMultiple(name, options = {}) { + let directory = path__default.resolve(toPath(options.cwd) || ''); + const {root} = path__default.parse(directory); + const stopAt = path__default.resolve(directory, options.stopAt || root); + const limit = options.limit || Number.POSITIVE_INFINITY; + const paths = [name].flat(); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + const matches = []; + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === findUpStop) { + break; + } + + if (foundPath) { + matches.push(path__default.resolve(directory, foundPath)); + } + + if (directory === stopAt || matches.length >= limit) { + break; + } + + directory = path__default.dirname(directory); + } + + return matches; +} + +async function findUp(name, options = {}) { + const matches = await findUpMultiple(name, {...options, limit: 1}); + return matches[0]; +} + +function _resolve(path$1, options = {}) { + if (options.platform === "auto" || !options.platform) + options.platform = process__default.platform === "win32" ? "win32" : "posix"; + const modulePath = mlly.resolvePathSync(path$1, { + url: options.paths + }); + if (options.platform === "win32") + return path.win32.normalize(modulePath); + return modulePath; +} +function resolveModule(name, options = {}) { + try { + return _resolve(name, options); + } catch (e) { + return void 0; + } +} +async function importModule(path) { + const i = await import(path); + if (i) + return mlly.interopDefault(i); + return i; +} +function isPackageExists(name, options = {}) { + return !!resolvePackage(name, options); +} +function getPackageJsonPath(name, options = {}) { + const entry = resolvePackage(name, options); + if (!entry) + return; + return searchPackageJSON(entry); +} +async function getPackageInfo(name, options = {}) { + const packageJsonPath = getPackageJsonPath(name, options); + if (!packageJsonPath) + return; + const packageJson = JSON.parse(await fs__default.promises.readFile(packageJsonPath, "utf8")); + return { + name, + version: packageJson.version, + rootPath: path.dirname(packageJsonPath), + packageJsonPath, + packageJson + }; +} +function getPackageInfoSync(name, options = {}) { + const packageJsonPath = getPackageJsonPath(name, options); + if (!packageJsonPath) + return; + const packageJson = JSON.parse(fs__default.readFileSync(packageJsonPath, "utf8")); + return { + name, + version: packageJson.version, + rootPath: path.dirname(packageJsonPath), + packageJsonPath, + packageJson + }; +} +function resolvePackage(name, options = {}) { + try { + return _resolve(`${name}/package.json`, options); + } catch { + } + try { + return _resolve(name, options); + } catch (e) { + if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND") + console.error(e); + return false; + } +} +function searchPackageJSON(dir) { + let packageJsonPath; + while (true) { + if (!dir) + return; + const newDir = path.dirname(dir); + if (newDir === dir) + return; + dir = newDir; + packageJsonPath = path.join(dir, "package.json"); + if (fs__default.existsSync(packageJsonPath)) + break; + } + return packageJsonPath; +} +async function loadPackageJSON(cwd = process__default.cwd()) { + const path = await findUp("package.json", { cwd }); + if (!path || !fs__default.existsSync(path)) + return null; + return JSON.parse(await fsp__default.readFile(path, "utf-8")); +} +async function isPackageListed(name, cwd) { + const pkg = await loadPackageJSON(cwd) || {}; + return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {}); +} + +exports.getPackageInfo = getPackageInfo; +exports.getPackageInfoSync = getPackageInfoSync; +exports.importModule = importModule; +exports.isPackageExists = isPackageExists; +exports.isPackageListed = isPackageListed; +exports.loadPackageJSON = loadPackageJSON; +exports.resolveModule = resolveModule; diff --git a/web/node_modules/local-pkg/dist/index.d.cts b/web/node_modules/local-pkg/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..f2e4df79c5a5e43ebabfefc6967897586cc23482 --- /dev/null +++ b/web/node_modules/local-pkg/dist/index.d.cts @@ -0,0 +1,38 @@ +import { PackageJson } from 'pkg-types'; + +interface PackageInfo { + name: string; + rootPath: string; + packageJsonPath: string; + version: string; + packageJson: PackageJson; +} +interface PackageResolvingOptions { + paths?: string[]; + /** + * @default 'auto' + * Resolve path as posix or win32 + */ + platform?: 'posix' | 'win32' | 'auto'; +} +declare function resolveModule(name: string, options?: PackageResolvingOptions): string | undefined; +declare function importModule(path: string): Promise; +declare function isPackageExists(name: string, options?: PackageResolvingOptions): boolean; +declare function getPackageInfo(name: string, options?: PackageResolvingOptions): Promise<{ + name: string; + version: string | undefined; + rootPath: string; + packageJsonPath: string; + packageJson: PackageJson; +} | undefined>; +declare function getPackageInfoSync(name: string, options?: PackageResolvingOptions): { + name: string; + version: string | undefined; + rootPath: string; + packageJsonPath: string; + packageJson: PackageJson; +} | undefined; +declare function loadPackageJSON(cwd?: string): Promise; +declare function isPackageListed(name: string, cwd?: string): Promise; + +export { type PackageInfo, type PackageResolvingOptions, getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, loadPackageJSON, resolveModule }; diff --git a/web/node_modules/local-pkg/dist/index.d.mts b/web/node_modules/local-pkg/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f2e4df79c5a5e43ebabfefc6967897586cc23482 --- /dev/null +++ b/web/node_modules/local-pkg/dist/index.d.mts @@ -0,0 +1,38 @@ +import { PackageJson } from 'pkg-types'; + +interface PackageInfo { + name: string; + rootPath: string; + packageJsonPath: string; + version: string; + packageJson: PackageJson; +} +interface PackageResolvingOptions { + paths?: string[]; + /** + * @default 'auto' + * Resolve path as posix or win32 + */ + platform?: 'posix' | 'win32' | 'auto'; +} +declare function resolveModule(name: string, options?: PackageResolvingOptions): string | undefined; +declare function importModule(path: string): Promise; +declare function isPackageExists(name: string, options?: PackageResolvingOptions): boolean; +declare function getPackageInfo(name: string, options?: PackageResolvingOptions): Promise<{ + name: string; + version: string | undefined; + rootPath: string; + packageJsonPath: string; + packageJson: PackageJson; +} | undefined>; +declare function getPackageInfoSync(name: string, options?: PackageResolvingOptions): { + name: string; + version: string | undefined; + rootPath: string; + packageJsonPath: string; + packageJson: PackageJson; +} | undefined; +declare function loadPackageJSON(cwd?: string): Promise; +declare function isPackageListed(name: string, cwd?: string): Promise; + +export { type PackageInfo, type PackageResolvingOptions, getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, loadPackageJSON, resolveModule }; diff --git a/web/node_modules/local-pkg/dist/index.d.ts b/web/node_modules/local-pkg/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2e4df79c5a5e43ebabfefc6967897586cc23482 --- /dev/null +++ b/web/node_modules/local-pkg/dist/index.d.ts @@ -0,0 +1,38 @@ +import { PackageJson } from 'pkg-types'; + +interface PackageInfo { + name: string; + rootPath: string; + packageJsonPath: string; + version: string; + packageJson: PackageJson; +} +interface PackageResolvingOptions { + paths?: string[]; + /** + * @default 'auto' + * Resolve path as posix or win32 + */ + platform?: 'posix' | 'win32' | 'auto'; +} +declare function resolveModule(name: string, options?: PackageResolvingOptions): string | undefined; +declare function importModule(path: string): Promise; +declare function isPackageExists(name: string, options?: PackageResolvingOptions): boolean; +declare function getPackageInfo(name: string, options?: PackageResolvingOptions): Promise<{ + name: string; + version: string | undefined; + rootPath: string; + packageJsonPath: string; + packageJson: PackageJson; +} | undefined>; +declare function getPackageInfoSync(name: string, options?: PackageResolvingOptions): { + name: string; + version: string | undefined; + rootPath: string; + packageJsonPath: string; + packageJson: PackageJson; +} | undefined; +declare function loadPackageJSON(cwd?: string): Promise; +declare function isPackageListed(name: string, cwd?: string): Promise; + +export { type PackageInfo, type PackageResolvingOptions, getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, loadPackageJSON, resolveModule }; diff --git a/web/node_modules/local-pkg/dist/index.mjs b/web/node_modules/local-pkg/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d604883590c86be039d2dd07f770cd5bb2c6a915 --- /dev/null +++ b/web/node_modules/local-pkg/dist/index.mjs @@ -0,0 +1,382 @@ +import path, { dirname, win32, join } from 'node:path'; +import fs, { promises } from 'node:fs'; +import fsp from 'node:fs/promises'; +import process from 'node:process'; +import { interopDefault, resolvePathSync } from 'mlly'; +import { fileURLToPath } from 'node:url'; + +/* +How it works: +`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value. +*/ + +class Node { + value; + next; + + constructor(value) { + this.value = value; + } +} + +class Queue { + #head; + #tail; + #size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this.#head) { + this.#tail.next = node; + this.#tail = node; + } else { + this.#head = node; + this.#tail = node; + } + + this.#size++; + } + + dequeue() { + const current = this.#head; + if (!current) { + return; + } + + this.#head = this.#head.next; + this.#size--; + return current.value; + } + + clear() { + this.#head = undefined; + this.#tail = undefined; + this.#size = 0; + } + + get size() { + return this.#size; + } + + * [Symbol.iterator]() { + let current = this.#head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +function pLimit(concurrency) { + if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, args) => { + queue.enqueue(run.bind(undefined, fn, resolve, args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount, + }, + pendingCount: { + get: () => queue.size, + }, + clearQueue: { + value: () => { + queue.clear(); + }, + }, + }); + + return generator; +} + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it. +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both. +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +async function pLocate( + iterable, + tester, + { + concurrency = Number.POSITIVE_INFINITY, + preserveOrder = true, + } = {}, +) { + const limit = pLimit(concurrency); + + // Start all the promises concurrently with optional limit. + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently. + const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +} + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile', +}; + +function checkType(type) { + if (Object.hasOwnProperty.call(typeMappings, type)) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => stat[typeMappings[type]](); + +const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; + +async function locatePath( + paths, + { + cwd = process.cwd(), + type = 'file', + allowSymlinks = true, + concurrency, + preserveOrder, + } = {}, +) { + checkType(type); + cwd = toPath$1(cwd); + + const statFunction = allowSymlinks ? promises.stat : promises.lstat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFunction(path.resolve(cwd, path_)); + return matchType(type, stat); + } catch { + return false; + } + }, {concurrency, preserveOrder}); +} + +const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; + +const findUpStop = Symbol('findUpStop'); + +async function findUpMultiple(name, options = {}) { + let directory = path.resolve(toPath(options.cwd) || ''); + const {root} = path.parse(directory); + const stopAt = path.resolve(directory, options.stopAt || root); + const limit = options.limit || Number.POSITIVE_INFINITY; + const paths = [name].flat(); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + const matches = []; + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === findUpStop) { + break; + } + + if (foundPath) { + matches.push(path.resolve(directory, foundPath)); + } + + if (directory === stopAt || matches.length >= limit) { + break; + } + + directory = path.dirname(directory); + } + + return matches; +} + +async function findUp(name, options = {}) { + const matches = await findUpMultiple(name, {...options, limit: 1}); + return matches[0]; +} + +function _resolve(path, options = {}) { + if (options.platform === "auto" || !options.platform) + options.platform = process.platform === "win32" ? "win32" : "posix"; + const modulePath = resolvePathSync(path, { + url: options.paths + }); + if (options.platform === "win32") + return win32.normalize(modulePath); + return modulePath; +} +function resolveModule(name, options = {}) { + try { + return _resolve(name, options); + } catch (e) { + return void 0; + } +} +async function importModule(path) { + const i = await import(path); + if (i) + return interopDefault(i); + return i; +} +function isPackageExists(name, options = {}) { + return !!resolvePackage(name, options); +} +function getPackageJsonPath(name, options = {}) { + const entry = resolvePackage(name, options); + if (!entry) + return; + return searchPackageJSON(entry); +} +async function getPackageInfo(name, options = {}) { + const packageJsonPath = getPackageJsonPath(name, options); + if (!packageJsonPath) + return; + const packageJson = JSON.parse(await fs.promises.readFile(packageJsonPath, "utf8")); + return { + name, + version: packageJson.version, + rootPath: dirname(packageJsonPath), + packageJsonPath, + packageJson + }; +} +function getPackageInfoSync(name, options = {}) { + const packageJsonPath = getPackageJsonPath(name, options); + if (!packageJsonPath) + return; + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); + return { + name, + version: packageJson.version, + rootPath: dirname(packageJsonPath), + packageJsonPath, + packageJson + }; +} +function resolvePackage(name, options = {}) { + try { + return _resolve(`${name}/package.json`, options); + } catch { + } + try { + return _resolve(name, options); + } catch (e) { + if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND") + console.error(e); + return false; + } +} +function searchPackageJSON(dir) { + let packageJsonPath; + while (true) { + if (!dir) + return; + const newDir = dirname(dir); + if (newDir === dir) + return; + dir = newDir; + packageJsonPath = join(dir, "package.json"); + if (fs.existsSync(packageJsonPath)) + break; + } + return packageJsonPath; +} +async function loadPackageJSON(cwd = process.cwd()) { + const path = await findUp("package.json", { cwd }); + if (!path || !fs.existsSync(path)) + return null; + return JSON.parse(await fsp.readFile(path, "utf-8")); +} +async function isPackageListed(name, cwd) { + const pkg = await loadPackageJSON(cwd) || {}; + return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {}); +} + +export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, loadPackageJSON, resolveModule }; diff --git a/web/node_modules/local-pkg/package.json b/web/node_modules/local-pkg/package.json new file mode 100644 index 0000000000000000000000000000000000000000..38f7b72026900a5bf2bedfb53bd1587bf4fc7d22 --- /dev/null +++ b/web/node_modules/local-pkg/package.json @@ -0,0 +1,65 @@ +{ + "name": "local-pkg", + "type": "module", + "version": "0.5.0", + "packageManager": "pnpm@8.8.0", + "description": "Get information on local packages.", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/antfu/local-pkg#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/antfu/local-pkg.git" + }, + "bugs": { + "url": "https://github.com/antfu/local-pkg/issues" + }, + "keywords": [ + "package" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + } + }, + "main": "dist/index.cjs", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "engines": { + "node": ">=14" + }, + "scripts": { + "prepublishOnly": "nr build", + "build": "unbuild", + "lint": "eslint .", + "release": "bumpp && npm publish", + "typecheck": "tsc --noEmit", + "test": "vitest run && node ./test/cjs.cjs && node ./test/esm.mjs" + }, + "dependencies": { + "mlly": "^1.4.2", + "pkg-types": "^1.0.3" + }, + "devDependencies": { + "@antfu/eslint-config": "^1.0.0-beta.18", + "@antfu/ni": "^0.21.8", + "@antfu/utils": "^0.7.6", + "@types/chai": "^4.3.6", + "@types/node": "^20.8.0", + "bumpp": "^9.2.0", + "chai": "^4.3.10", + "eslint": "^8.50.0", + "esno": "^0.17.0", + "find-up": "^6.3.0", + "typescript": "^5.2.2", + "unbuild": "^2.0.0", + "vitest": "^0.34.6" + } +} diff --git a/web/node_modules/loupe/CHANGELOG.md b/web/node_modules/loupe/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..11799db770601f760f5a481c58ac242e447cef1f --- /dev/null +++ b/web/node_modules/loupe/CHANGELOG.md @@ -0,0 +1,5 @@ + +0.0.1 / 2013-12-17 +================== + + * Initial port from chai.js diff --git a/web/node_modules/loupe/LICENSE b/web/node_modules/loupe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0c8a5aaa4a14b2a790606e1b40a6bb558a1fd08 --- /dev/null +++ b/web/node_modules/loupe/LICENSE @@ -0,0 +1,9 @@ +(The MIT License) + +Copyright (c) 2011-2013 Jake Luer jake@alogicalparadox.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/web/node_modules/loupe/README.md b/web/node_modules/loupe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..44f61d38d9bb78ce01e6795358e0ed6aee75bca4 --- /dev/null +++ b/web/node_modules/loupe/README.md @@ -0,0 +1,63 @@ +![npm](https://img.shields.io/npm/v/loupe?logo=npm) +![Build](https://github.com/chaijs/loupe/workflows/Build/badge.svg?branch=master) +![Codecov branch](https://img.shields.io/codecov/c/github/chaijs/loupe/master?logo=codecov) + +# What is loupe? + +Loupe turns the object you give it into a string. It's similar to Node.js' `util.inspect()` function, but it works cross platform, in most modern browsers as well as Node. + +## Installation + +### Node.js + +`loupe` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install loupe + +### Browsers + +You can also use it within the browser; install via npm and use the `loupe.js` file found within the download. For example: + +```html + +``` + +## Usage + +``` js +const { inspect } = require('loupe'); +``` + +```js +inspect({ foo: 'bar' }); // => "{ foo: 'bar' }" +inspect(1); // => '1' +inspect('foo'); // => "'foo'" +inspect([ 1, 2, 3 ]); // => '[ 1, 2, 3 ]' +inspect(/Test/g); // => '/Test/g' + +// ... +``` + +## Tests + +```bash +$ npm test +``` + +Coverage: + +```bash +$ npm run upload-coverage +``` + +## License + +(The MIT License) + +Copyright (c) 2011-2013 Jake Luer jake@alogicalparadox.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/web/node_modules/loupe/index.js b/web/node_modules/loupe/index.js new file mode 100644 index 0000000000000000000000000000000000000000..01e0b3cae5e3d5309d0d125ae32bcb2ac0c14f14 --- /dev/null +++ b/web/node_modules/loupe/index.js @@ -0,0 +1,219 @@ +/* ! + * loupe + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +import inspectArray from './lib/array' +import inspectTypedArray from './lib/typedarray' +import inspectDate from './lib/date' +import inspectFunction from './lib/function' +import inspectMap from './lib/map' +import inspectNumber from './lib/number' +import inspectBigInt from './lib/bigint' +import inspectRegExp from './lib/regexp' +import inspectSet from './lib/set' +import inspectString from './lib/string' +import inspectSymbol from './lib/symbol' +import inspectPromise from './lib/promise' +import inspectClass from './lib/class' +import inspectObject from './lib/object' +import inspectArguments from './lib/arguments' +import inspectError from './lib/error' +import inspectHTMLElement, { inspectHTMLCollection } from './lib/html' + +import { normaliseOptions } from './lib/helpers' + +const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function' +const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect' +let nodeInspect = false +try { + // eslint-disable-next-line global-require + const nodeUtil = require('util') + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false +} catch (noNodeInspect) { + nodeInspect = false +} + +function FakeMap() { + // eslint-disable-next-line prefer-template + this.key = 'chai/loupe__' + Math.random() + Date.now() +} +FakeMap.prototype = { + // eslint-disable-next-line object-shorthand + get: function get(key) { + return key[this.key] + }, + // eslint-disable-next-line object-shorthand + has: function has(key) { + return this.key in key + }, + // eslint-disable-next-line object-shorthand + set: function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this.key, { + // eslint-disable-next-line object-shorthand + value: value, + configurable: true, + }) + } + }, +} +const constructorMap = new (typeof WeakMap === 'function' ? WeakMap : FakeMap)() +const stringTagMap = {} +const baseTypesMap = { + undefined: (value, options) => options.stylize('undefined', 'undefined'), + null: (value, options) => options.stylize(null, 'null'), + + boolean: (value, options) => options.stylize(value, 'boolean'), + Boolean: (value, options) => options.stylize(value, 'boolean'), + + number: inspectNumber, + Number: inspectNumber, + + bigint: inspectBigInt, + BigInt: inspectBigInt, + + string: inspectString, + String: inspectString, + + function: inspectFunction, + Function: inspectFunction, + + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: inspectPromise, + + // WeakSet, WeakMap are totally opaque to us + WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'), + WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'), + + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + + Generator: () => '', + DataView: () => '', + ArrayBuffer: () => '', + + Error: inspectError, + + HTMLCollection: inspectHTMLCollection, + NodeList: inspectHTMLCollection, +} + +// eslint-disable-next-line complexity +const inspectCustom = (value, options, type) => { + if (chaiInspect in value && typeof value[chaiInspect] === 'function') { + return value[chaiInspect](options) + } + + if (nodeInspect && nodeInspect in value && typeof value[nodeInspect] === 'function') { + return value[nodeInspect](options.depth, options) + } + + if ('inspect' in value && typeof value.inspect === 'function') { + return value.inspect(options.depth, options) + } + + if ('constructor' in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options) + } + + if (stringTagMap[type]) { + return stringTagMap[type](value, options) + } + + return '' +} + +const toString = Object.prototype.toString + +// eslint-disable-next-line complexity +export function inspect(value, options) { + options = normaliseOptions(options) + options.inspect = inspect + const { customInspect } = options + let type = value === null ? 'null' : typeof value + if (type === 'object') { + type = toString.call(value).slice(8, -1) + } + + // If it is a base value that we already support, then use Loupe's inspector + if (baseTypesMap[type]) { + return baseTypesMap[type](value, options) + } + + // If `options.customInspect` is set to true then try to use the custom inspector + if (customInspect && value) { + const output = inspectCustom(value, options, type) + if (output) { + if (typeof output === 'string') return output + return inspect(output, options) + } + } + + const proto = value ? Object.getPrototypeOf(value) : false + // If it's a plain Object then use Loupe's inspector + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options) + } + + // Specifically account for HTMLElements + // eslint-disable-next-line no-undef + if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return inspectHTMLElement(value, options) + } + + if ('constructor' in value) { + // If it is a class, inspect it like an object but add the constructor name + if (value.constructor !== Object) { + return inspectClass(value, options) + } + + // If it is an object with an anonymous prototype, display it as an object. + return inspectObject(value, options) + } + + // last chance to check if it's an object + if (value === Object(value)) { + return inspectObject(value, options) + } + + // We have run out of options! Just stringify the value + return options.stylize(String(value), type) +} + +export function registerConstructor(constructor, inspector) { + if (constructorMap.has(constructor)) { + return false + } + constructorMap.set(constructor, inspector) + return true +} + +export function registerStringTag(stringTag, inspector) { + if (stringTag in stringTagMap) { + return false + } + stringTagMap[stringTag] = inspector + return true +} + +export const custom = chaiInspect + +export default inspect diff --git a/web/node_modules/loupe/lib/arguments.js b/web/node_modules/loupe/lib/arguments.js new file mode 100644 index 0000000000000000000000000000000000000000..e7d3a6df845daab1cedaf974427a4a3560b90daf --- /dev/null +++ b/web/node_modules/loupe/lib/arguments.js @@ -0,0 +1,7 @@ +import { inspectList } from './helpers' + +export default function inspectArguments(args, options) { + if (args.length === 0) return 'Arguments[]' + options.truncate -= 13 + return `Arguments[ ${inspectList(args, options)} ]` +} diff --git a/web/node_modules/loupe/lib/array.js b/web/node_modules/loupe/lib/array.js new file mode 100644 index 0000000000000000000000000000000000000000..c37702919618f97683f03523d810f294828ad37a --- /dev/null +++ b/web/node_modules/loupe/lib/array.js @@ -0,0 +1,20 @@ +import { inspectProperty, inspectList } from './helpers' + +export default function inspectArray(array, options) { + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length) + if (!array.length && !nonIndexProperties.length) return '[]' + options.truncate -= 4 + const listContents = inspectList(array, options) + options.truncate -= listContents.length + let propertyContents = '' + if (nonIndexProperties.length) { + propertyContents = inspectList( + nonIndexProperties.map(key => [key, array[key]]), + options, + inspectProperty + ) + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]` +} diff --git a/web/node_modules/loupe/lib/bigint.js b/web/node_modules/loupe/lib/bigint.js new file mode 100644 index 0000000000000000000000000000000000000000..d93db78860eb123a75828c16e07c633714dc5bc7 --- /dev/null +++ b/web/node_modules/loupe/lib/bigint.js @@ -0,0 +1,7 @@ +import { truncate, truncator } from './helpers' + +export default function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1) + if (nums !== truncator) nums += 'n' + return options.stylize(nums, 'bigint') +} diff --git a/web/node_modules/loupe/lib/class.js b/web/node_modules/loupe/lib/class.js new file mode 100644 index 0000000000000000000000000000000000000000..cd949af92b1adf097c32500a7dcd0a3557257a4b --- /dev/null +++ b/web/node_modules/loupe/lib/class.js @@ -0,0 +1,18 @@ +import getFuncName from 'get-func-name' +import inspectObject from './object' + +const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false + +export default function inspectClass(value, options) { + let name = '' + if (toStringTag && toStringTag in value) { + name = value[toStringTag] + } + name = name || getFuncName(value.constructor) + // Babel transforms anonymous classes to the name `_class` + if (!name || name === '_class') { + name = '' + } + options.truncate -= name.length + return `${name}${inspectObject(value, options)}` +} diff --git a/web/node_modules/loupe/lib/date.js b/web/node_modules/loupe/lib/date.js new file mode 100644 index 0000000000000000000000000000000000000000..9d1596293737742a40370283dd9d0972df1ff33c --- /dev/null +++ b/web/node_modules/loupe/lib/date.js @@ -0,0 +1,14 @@ +import { truncate } from './helpers' + +export default function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON() + + if (stringRepresentation === null) { + return 'Invalid Date' + } + + const split = stringRepresentation.split('T') + const date = split[0] + // If we need to - truncate the time portion, but never the date + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date') +} diff --git a/web/node_modules/loupe/lib/error.js b/web/node_modules/loupe/lib/error.js new file mode 100644 index 0000000000000000000000000000000000000000..1fabaa9d709732b14bc35d52667da017a5de4520 --- /dev/null +++ b/web/node_modules/loupe/lib/error.js @@ -0,0 +1,34 @@ +import { truncate, inspectList, inspectProperty } from './helpers' + +const errorKeys = [ + 'stack', + 'line', + 'column', + 'name', + 'message', + 'fileName', + 'lineNumber', + 'columnNumber', + 'number', + 'description', +] + +export default function inspectObject(error, options) { + const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1) + const name = error.name + options.truncate -= name.length + let message = '' + if (typeof error.message === 'string') { + message = truncate(error.message, options.truncate) + } else { + properties.unshift('message') + } + message = message ? `: ${message}` : '' + options.truncate -= message.length + 5 + const propertyContents = inspectList( + properties.map(key => [key, error[key]]), + options, + inspectProperty + ) + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}` +} diff --git a/web/node_modules/loupe/lib/function.js b/web/node_modules/loupe/lib/function.js new file mode 100644 index 0000000000000000000000000000000000000000..75b7c55bab88b412dceb01bbe4170e37a5894048 --- /dev/null +++ b/web/node_modules/loupe/lib/function.js @@ -0,0 +1,10 @@ +import getFunctionName from 'get-func-name' +import { truncate } from './helpers' + +export default function inspectFunction(func, options) { + const name = getFunctionName(func) + if (!name) { + return options.stylize('[Function]', 'special') + } + return options.stylize(`[Function ${truncate(name, options.truncate - 11)}]`, 'special') +} diff --git a/web/node_modules/loupe/lib/helpers.js b/web/node_modules/loupe/lib/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..8a883d6790c8d1be066e9cb0d0dee29126c41653 --- /dev/null +++ b/web/node_modules/loupe/lib/helpers.js @@ -0,0 +1,177 @@ +const ansiColors = { + bold: ['1', '22'], + dim: ['2', '22'], + italic: ['3', '23'], + underline: ['4', '24'], + // 5 & 6 are blinking + inverse: ['7', '27'], + hidden: ['8', '28'], + strike: ['9', '29'], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ['30', '39'], + red: ['31', '39'], + green: ['32', '39'], + yellow: ['33', '39'], + blue: ['34', '39'], + magenta: ['35', '39'], + cyan: ['36', '39'], + white: ['37', '39'], + + brightblack: ['30;1', '39'], + brightred: ['31;1', '39'], + brightgreen: ['32;1', '39'], + brightyellow: ['33;1', '39'], + brightblue: ['34;1', '39'], + brightmagenta: ['35;1', '39'], + brightcyan: ['36;1', '39'], + brightwhite: ['37;1', '39'], + + grey: ['90', '39'], +} + +const styles = { + special: 'cyan', + number: 'yellow', + bigint: 'yellow', + boolean: 'yellow', + undefined: 'grey', + null: 'bold', + string: 'green', + symbol: 'green', + date: 'magenta', + regexp: 'red', +} + +export const truncator = '…' + +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] + if (!color) { + return String(value) + } + return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m` +} + +export function normaliseOptions({ + showHidden = false, + depth = 2, + colors = false, + customInspect = true, + showProxy = false, + maxArrayLength = Infinity, + breakLength = Infinity, + seen = [], + // eslint-disable-next-line no-shadow + truncate = Infinity, + stylize = String, +} = {}) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate), + seen, + stylize, + } + if (options.colors) { + options.stylize = colorise + } + return options +} + +export function truncate(string, length, tail = truncator) { + string = String(string) + const tailLength = tail.length + const stringLength = string.length + if (tailLength > length && stringLength > tailLength) { + return tail + } + if (stringLength > length && stringLength > tailLength) { + return `${string.slice(0, length - tailLength)}${tail}` + } + return string +} + +// eslint-disable-next-line complexity +export function inspectList(list, options, inspectItem, separator = ', ') { + inspectItem = inspectItem || options.inspect + const size = list.length + if (size === 0) return '' + const originalLength = options.truncate + let output = '' + let peek = '' + let truncated = '' + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length + const secondToLast = i + 2 === list.length + truncated = `${truncator}(${list.length - i})` + const value = list[i] + + // If there is more than one remaining we need to account for a separator of `, ` + options.truncate = originalLength - output.length - (last ? 0 : separator.length) + const string = peek || inspectItem(value, options) + (last ? '' : separator) + const nextLength = output.length + string.length + const truncatedLength = nextLength + truncated.length + + // If this is the last element, and adding it would + // take us over length, but adding the truncator wouldn't - then break now + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break + } + + // If this isn't the last or second to last element to scan, + // but the string is already over length then break here + if (!last && !secondToLast && truncatedLength > originalLength) { + break + } + + // Peek at the next string to determine if we should + // break early before adding this item to the output + peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator) + + // If we have one element left, but this element and + // the next takes over length, the break early + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break + } + + output += string + + // If the next element takes us to length - + // but there are more after that, then we should truncate now + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})` + break + } + + truncated = '' + } + return `${output}${truncated}` +} + +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key + } + return JSON.stringify(key) + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'") +} + +export function inspectProperty([key, value], options) { + options.truncate -= 2 + if (typeof key === 'string') { + key = quoteComplexKey(key) + } else if (typeof key !== 'number') { + key = `[${options.inspect(key, options)}]` + } + options.truncate -= key.length + value = options.inspect(value, options) + return `${key}: ${value}` +} diff --git a/web/node_modules/loupe/lib/html.js b/web/node_modules/loupe/lib/html.js new file mode 100644 index 0000000000000000000000000000000000000000..e39cd343a319cc6569f8993c6afe7fd2490b20aa --- /dev/null +++ b/web/node_modules/loupe/lib/html.js @@ -0,0 +1,40 @@ +import { truncator, inspectList } from './helpers' + +export function inspectAttribute([key, value], options) { + options.truncate -= 3 + if (!value) { + return `${options.stylize(key, 'yellow')}` + } + return `${options.stylize(key, 'yellow')}=${options.stylize(`"${value}"`, 'string')}` +} + +export function inspectHTMLCollection(collection, options) { + // eslint-disable-next-line no-use-before-define + return inspectList(collection, options, inspectHTML, '\n') +} + +export default function inspectHTML(element, options) { + const properties = element.getAttributeNames() + const name = element.tagName.toLowerCase() + const head = options.stylize(`<${name}`, 'special') + const headClose = options.stylize(`>`, 'special') + const tail = options.stylize(``, 'special') + options.truncate -= name.length * 2 + 5 + let propertyContents = '' + if (properties.length > 0) { + propertyContents += ' ' + propertyContents += inspectList( + properties.map(key => [key, element.getAttribute(key)]), + options, + inspectAttribute, + ' ' + ) + } + options.truncate -= propertyContents.length + const truncate = options.truncate + let children = inspectHTMLCollection(element.children, options) + if (children && children.length > truncate) { + children = `${truncator}(${element.children.length})` + } + return `${head}${propertyContents}${headClose}${children}${tail}` +} diff --git a/web/node_modules/loupe/lib/map.js b/web/node_modules/loupe/lib/map.js new file mode 100644 index 0000000000000000000000000000000000000000..2842e309649859fbc88010cbf3aea83857fdf110 --- /dev/null +++ b/web/node_modules/loupe/lib/map.js @@ -0,0 +1,27 @@ +import { inspectList } from './helpers' + +function inspectMapEntry([key, value], options) { + options.truncate -= 4 + key = options.inspect(key, options) + options.truncate -= key.length + value = options.inspect(value, options) + return `${key} => ${value}` +} + +// IE11 doesn't support `map.entries()` +function mapToEntries(map) { + const entries = [] + map.forEach((value, key) => { + entries.push([key, value]) + }) + return entries +} + +export default function inspectMap(map, options) { + const size = map.size - 1 + if (size <= 0) { + return 'Map{}' + } + options.truncate -= 7 + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }` +} diff --git a/web/node_modules/loupe/lib/number.js b/web/node_modules/loupe/lib/number.js new file mode 100644 index 0000000000000000000000000000000000000000..9def128be940555e4eafc6ee07bd33a12796bc5e --- /dev/null +++ b/web/node_modules/loupe/lib/number.js @@ -0,0 +1,18 @@ +import { truncate } from './helpers' + +const isNaN = Number.isNaN || (i => i !== i) // eslint-disable-line no-self-compare +export default function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize('NaN', 'number') + } + if (number === Infinity) { + return options.stylize('Infinity', 'number') + } + if (number === -Infinity) { + return options.stylize('-Infinity', 'number') + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number') + } + return options.stylize(truncate(number, options.truncate), 'number') +} diff --git a/web/node_modules/loupe/lib/object.js b/web/node_modules/loupe/lib/object.js new file mode 100644 index 0000000000000000000000000000000000000000..4cbb87f6f90f3b7baac00377ed96c1be90baca64 --- /dev/null +++ b/web/node_modules/loupe/lib/object.js @@ -0,0 +1,31 @@ +import { inspectProperty, inspectList } from './helpers' + +export default function inspectObject(object, options) { + const properties = Object.getOwnPropertyNames(object) + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [] + if (properties.length === 0 && symbols.length === 0) { + return '{}' + } + options.truncate -= 4 + options.seen = options.seen || [] + if (options.seen.indexOf(object) >= 0) { + return '[Circular]' + } + options.seen.push(object) + const propertyContents = inspectList( + properties.map(key => [key, object[key]]), + options, + inspectProperty + ) + const symbolContents = inspectList( + symbols.map(key => [key, object[key]]), + options, + inspectProperty + ) + options.seen.pop() + let sep = '' + if (propertyContents && symbolContents) { + sep = ', ' + } + return `{ ${propertyContents}${sep}${symbolContents} }` +} diff --git a/web/node_modules/loupe/lib/promise.js b/web/node_modules/loupe/lib/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..327e9f42dae0722505f50e3f0e5048020b62264b --- /dev/null +++ b/web/node_modules/loupe/lib/promise.js @@ -0,0 +1,16 @@ +let getPromiseValue = () => 'Promise{…}' +try { + const { getPromiseDetails, kPending, kRejected } = process.binding('util') + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = (value, options) => { + const [state, innerValue] = getPromiseDetails(value) + if (state === kPending) { + return 'Promise{}' + } + return `Promise${state === kRejected ? '!' : ''}{${options.inspect(innerValue, options)}}` + } + } +} catch (notNode) { + /* ignore */ +} +export default getPromiseValue diff --git a/web/node_modules/loupe/lib/regexp.js b/web/node_modules/loupe/lib/regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..edad917c4e4ae5e8ab193c46a1b2ee03d5e41114 --- /dev/null +++ b/web/node_modules/loupe/lib/regexp.js @@ -0,0 +1,8 @@ +import { truncate } from './helpers' + +export default function inspectRegExp(value, options) { + const flags = value.toString().split('/')[2] + const sourceLength = options.truncate - (2 + flags.length) + const source = value.source + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp') +} diff --git a/web/node_modules/loupe/lib/set.js b/web/node_modules/loupe/lib/set.js new file mode 100644 index 0000000000000000000000000000000000000000..99a13006e40063009b2a2bee39c5a3692da6d68e --- /dev/null +++ b/web/node_modules/loupe/lib/set.js @@ -0,0 +1,16 @@ +import { inspectList } from './helpers' + +// IE11 doesn't support `Array.from(set)` +function arrayFromSet(set) { + const values = [] + set.forEach(value => { + values.push(value) + }) + return values +} + +export default function inspectSet(set, options) { + if (set.size === 0) return 'Set{}' + options.truncate -= 7 + return `Set{ ${inspectList(arrayFromSet(set), options)} }` +} diff --git a/web/node_modules/loupe/lib/string.js b/web/node_modules/loupe/lib/string.js new file mode 100644 index 0000000000000000000000000000000000000000..2af66cfa12ab4c6380f7ed0ea4769a1db6a3914d --- /dev/null +++ b/web/node_modules/loupe/lib/string.js @@ -0,0 +1,29 @@ +import { truncate } from './helpers' + +const stringEscapeChars = new RegExp( + "['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + + '\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', + 'g' +) + +const escapeCharacters = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\', +} +const hex = 16 +const unicodeLength = 4 +function escape(char) { + return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}` +} + +export default function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape) + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string') +} diff --git a/web/node_modules/loupe/lib/symbol.js b/web/node_modules/loupe/lib/symbol.js new file mode 100644 index 0000000000000000000000000000000000000000..f98beec1f5cc98f32c783288faccf00e1c3b3414 --- /dev/null +++ b/web/node_modules/loupe/lib/symbol.js @@ -0,0 +1,6 @@ +export default function inspectSymbol(value) { + if ('description' in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : 'Symbol()' + } + return value.toString() +} diff --git a/web/node_modules/loupe/lib/typedarray.js b/web/node_modules/loupe/lib/typedarray.js new file mode 100644 index 0000000000000000000000000000000000000000..b98c04577c0124a63d34e5d9624937d96af1e06f --- /dev/null +++ b/web/node_modules/loupe/lib/typedarray.js @@ -0,0 +1,45 @@ +import getFuncName from 'get-func-name' +import { truncator, truncate, inspectProperty, inspectList } from './helpers' + +const getArrayName = array => { + // We need to special case Node.js' Buffers, which report to be Uint8Array + if (typeof Buffer === 'function' && array instanceof Buffer) { + return 'Buffer' + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag] + } + return getFuncName(array.constructor) +} + +export default function inspectTypedArray(array, options) { + const name = getArrayName(array) + options.truncate -= name.length + 4 + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length) + if (!array.length && !nonIndexProperties.length) return `${name}[]` + // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply + // stylise the toString() value of them + let output = '' + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${ + i === array.length - 1 ? '' : ', ' + }` + options.truncate -= string.length + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})` + break + } + output += string + } + let propertyContents = '' + if (nonIndexProperties.length) { + propertyContents = inspectList( + nonIndexProperties.map(key => [key, array[key]]), + options, + inspectProperty + ) + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]` +} diff --git a/web/node_modules/loupe/loupe.js b/web/node_modules/loupe/loupe.js new file mode 100644 index 0000000000000000000000000000000000000000..5e1c2397122c84229af5f5f9c7fb90622eaa4b27 --- /dev/null +++ b/web/node_modules/loupe/loupe.js @@ -0,0 +1,891 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.loupe = {})); +}(this, (function (exports) { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + 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 _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var ansiColors = { + bold: ['1', '22'], + dim: ['2', '22'], + italic: ['3', '23'], + underline: ['4', '24'], + // 5 & 6 are blinking + inverse: ['7', '27'], + hidden: ['8', '28'], + strike: ['9', '29'], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ['30', '39'], + red: ['31', '39'], + green: ['32', '39'], + yellow: ['33', '39'], + blue: ['34', '39'], + magenta: ['35', '39'], + cyan: ['36', '39'], + white: ['37', '39'], + brightblack: ['30;1', '39'], + brightred: ['31;1', '39'], + brightgreen: ['32;1', '39'], + brightyellow: ['33;1', '39'], + brightblue: ['34;1', '39'], + brightmagenta: ['35;1', '39'], + brightcyan: ['36;1', '39'], + brightwhite: ['37;1', '39'], + grey: ['90', '39'] + }; + var styles = { + special: 'cyan', + number: 'yellow', + bigint: 'yellow', + boolean: 'yellow', + undefined: 'grey', + null: 'bold', + string: 'green', + symbol: 'green', + date: 'magenta', + regexp: 'red' + }; + var truncator = '…'; + + function colorise(value, styleType) { + var color = ansiColors[styles[styleType]] || ansiColors[styleType]; + + if (!color) { + return String(value); + } + + return "\x1B[".concat(color[0], "m").concat(String(value), "\x1B[").concat(color[1], "m"); + } + + function normaliseOptions() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$showHidden = _ref.showHidden, + showHidden = _ref$showHidden === void 0 ? false : _ref$showHidden, + _ref$depth = _ref.depth, + depth = _ref$depth === void 0 ? 2 : _ref$depth, + _ref$colors = _ref.colors, + colors = _ref$colors === void 0 ? false : _ref$colors, + _ref$customInspect = _ref.customInspect, + customInspect = _ref$customInspect === void 0 ? true : _ref$customInspect, + _ref$showProxy = _ref.showProxy, + showProxy = _ref$showProxy === void 0 ? false : _ref$showProxy, + _ref$maxArrayLength = _ref.maxArrayLength, + maxArrayLength = _ref$maxArrayLength === void 0 ? Infinity : _ref$maxArrayLength, + _ref$breakLength = _ref.breakLength, + breakLength = _ref$breakLength === void 0 ? Infinity : _ref$breakLength, + _ref$seen = _ref.seen, + seen = _ref$seen === void 0 ? [] : _ref$seen, + _ref$truncate = _ref.truncate, + truncate = _ref$truncate === void 0 ? Infinity : _ref$truncate, + _ref$stylize = _ref.stylize, + stylize = _ref$stylize === void 0 ? String : _ref$stylize; + + var options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate), + seen: seen, + stylize: stylize + }; + + if (options.colors) { + options.stylize = colorise; + } + + return options; + } + function truncate(string, length) { + var tail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : truncator; + string = String(string); + var tailLength = tail.length; + var stringLength = string.length; + + if (tailLength > length && stringLength > tailLength) { + return tail; + } + + if (stringLength > length && stringLength > tailLength) { + return "".concat(string.slice(0, length - tailLength)).concat(tail); + } + + return string; + } // eslint-disable-next-line complexity + + function inspectList(list, options, inspectItem) { + var separator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ', '; + inspectItem = inspectItem || options.inspect; + var size = list.length; + if (size === 0) return ''; + var originalLength = options.truncate; + var output = ''; + var peek = ''; + var truncated = ''; + + for (var i = 0; i < size; i += 1) { + var last = i + 1 === list.length; + var secondToLast = i + 2 === list.length; + truncated = "".concat(truncator, "(").concat(list.length - i, ")"); + var value = list[i]; // If there is more than one remaining we need to account for a separator of `, ` + + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + var string = peek || inspectItem(value, options) + (last ? '' : separator); + var nextLength = output.length + string.length; + var truncatedLength = nextLength + truncated.length; // If this is the last element, and adding it would + // take us over length, but adding the truncator wouldn't - then break now + + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } // If this isn't the last or second to last element to scan, + // but the string is already over length then break here + + + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } // Peek at the next string to determine if we should + // break early before adding this item to the output + + + peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator); // If we have one element left, but this element and + // the next takes over length, the break early + + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + + output += string; // If the next element takes us to length - + // but there are more after that, then we should truncate now + + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = "".concat(truncator, "(").concat(list.length - i - 1, ")"); + break; + } + + truncated = ''; + } + + return "".concat(output).concat(truncated); + } + + function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + + return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); + } + + function inspectProperty(_ref2, options) { + var _ref3 = _slicedToArray(_ref2, 2), + key = _ref3[0], + value = _ref3[1]; + + options.truncate -= 2; + + if (typeof key === 'string') { + key = quoteComplexKey(key); + } else if (typeof key !== 'number') { + key = "[".concat(options.inspect(key, options), "]"); + } + + options.truncate -= key.length; + value = options.inspect(value, options); + return "".concat(key, ": ").concat(value); + } + + function inspectArray(array, options) { + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + var nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) return '[]'; + options.truncate -= 4; + var listContents = inspectList(array, options); + options.truncate -= listContents.length; + var propertyContents = ''; + + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(function (key) { + return [key, array[key]]; + }), options, inspectProperty); + } + + return "[ ".concat(listContents).concat(propertyContents ? ", ".concat(propertyContents) : '', " ]"); + } + + /* ! + * Chai - getFuncName utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + + /** + * ### .getFuncName(constructorFn) + * + * Returns the name of a function. + * When a non-function instance is passed, returns `null`. + * This also includes a polyfill function if `aFunc.name` is not defined. + * + * @name getFuncName + * @param {Function} funct + * @namespace Utils + * @api public + */ + + var toString = Function.prototype.toString; + var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; + var maxFunctionSourceLength = 512; + function getFuncName(aFunc) { + if (typeof aFunc !== 'function') { + return null; + } + + var name = ''; + if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { + // eslint-disable-next-line prefer-reflect + var functionSource = toString.call(aFunc); + // To avoid unconstrained resource consumption due to pathalogically large function names, + // we limit the available return value to be less than 512 characters. + if (functionSource.indexOf('(') > maxFunctionSourceLength) { + return name; + } + // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined + var match = functionSource.match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + // If we've got a `name` property we just use it + name = aFunc.name; + } + + return name; + } + + var getFuncName_1 = getFuncName; + + var getArrayName = function getArrayName(array) { + // We need to special case Node.js' Buffers, which report to be Uint8Array + if (typeof Buffer === 'function' && array instanceof Buffer) { + return 'Buffer'; + } + + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + + return getFuncName_1(array.constructor); + }; + + function inspectTypedArray(array, options) { + var name = getArrayName(array); + options.truncate -= name.length + 4; // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + + var nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) return "".concat(name, "[]"); // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply + // stylise the toString() value of them + + var output = ''; + + for (var i = 0; i < array.length; i++) { + var string = "".concat(options.stylize(truncate(array[i], options.truncate), 'number')).concat(i === array.length - 1 ? '' : ', '); + options.truncate -= string.length; + + if (array[i] !== array.length && options.truncate <= 3) { + output += "".concat(truncator, "(").concat(array.length - array[i] + 1, ")"); + break; + } + + output += string; + } + + var propertyContents = ''; + + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(function (key) { + return [key, array[key]]; + }), options, inspectProperty); + } + + return "".concat(name, "[ ").concat(output).concat(propertyContents ? ", ".concat(propertyContents) : '', " ]"); + } + + function inspectDate(dateObject, options) { + var stringRepresentation = dateObject.toJSON(); + + if (stringRepresentation === null) { + return 'Invalid Date'; + } + + var split = stringRepresentation.split('T'); + var date = split[0]; // If we need to - truncate the time portion, but never the date + + return options.stylize("".concat(date, "T").concat(truncate(split[1], options.truncate - date.length - 1)), 'date'); + } + + function inspectFunction(func, options) { + var name = getFuncName_1(func); + + if (!name) { + return options.stylize('[Function]', 'special'); + } + + return options.stylize("[Function ".concat(truncate(name, options.truncate - 11), "]"), 'special'); + } + + function inspectMapEntry(_ref, options) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return "".concat(key, " => ").concat(value); + } // IE11 doesn't support `map.entries()` + + + function mapToEntries(map) { + var entries = []; + map.forEach(function (value, key) { + entries.push([key, value]); + }); + return entries; + } + + function inspectMap(map, options) { + var size = map.size - 1; + + if (size <= 0) { + return 'Map{}'; + } + + options.truncate -= 7; + return "Map{ ".concat(inspectList(mapToEntries(map), options, inspectMapEntry), " }"); + } + + var isNaN = Number.isNaN || function (i) { + return i !== i; + }; // eslint-disable-line no-self-compare + + + function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize('NaN', 'number'); + } + + if (number === Infinity) { + return options.stylize('Infinity', 'number'); + } + + if (number === -Infinity) { + return options.stylize('-Infinity', 'number'); + } + + if (number === 0) { + return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number'); + } + + return options.stylize(truncate(number, options.truncate), 'number'); + } + + function inspectBigInt(number, options) { + var nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) nums += 'n'; + return options.stylize(nums, 'bigint'); + } + + function inspectRegExp(value, options) { + var flags = value.toString().split('/')[2]; + var sourceLength = options.truncate - (2 + flags.length); + var source = value.source; + return options.stylize("/".concat(truncate(source, sourceLength), "/").concat(flags), 'regexp'); + } + + function arrayFromSet(set) { + var values = []; + set.forEach(function (value) { + values.push(value); + }); + return values; + } + + function inspectSet(set, options) { + if (set.size === 0) return 'Set{}'; + options.truncate -= 7; + return "Set{ ".concat(inspectList(arrayFromSet(set), options), " }"); + } + + var stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + "\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", 'g'); + var escapeCharacters = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\' + }; + var hex = 16; + var unicodeLength = 4; + + function escape(char) { + return escapeCharacters[char] || "\\u".concat("0000".concat(char.charCodeAt(0).toString(hex)).slice(-unicodeLength)); + } + + function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + + return options.stylize("'".concat(truncate(string, options.truncate - 2), "'"), 'string'); + } + + function inspectSymbol(value) { + if ('description' in Symbol.prototype) { + return value.description ? "Symbol(".concat(value.description, ")") : 'Symbol()'; + } + + return value.toString(); + } + + var getPromiseValue = function getPromiseValue() { + return 'Promise{…}'; + }; + + try { + var _process$binding = process.binding('util'), + getPromiseDetails = _process$binding.getPromiseDetails, + kPending = _process$binding.kPending, + kRejected = _process$binding.kRejected; + + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = function getPromiseValue(value, options) { + var _getPromiseDetails = getPromiseDetails(value), + _getPromiseDetails2 = _slicedToArray(_getPromiseDetails, 2), + state = _getPromiseDetails2[0], + innerValue = _getPromiseDetails2[1]; + + if (state === kPending) { + return 'Promise{}'; + } + + return "Promise".concat(state === kRejected ? '!' : '', "{").concat(options.inspect(innerValue, options), "}"); + }; + } + } catch (notNode) { + /* ignore */ + } + + var inspectPromise = getPromiseValue; + + function inspectObject(object, options) { + var properties = Object.getOwnPropertyNames(object); + var symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + + if (properties.length === 0 && symbols.length === 0) { + return '{}'; + } + + options.truncate -= 4; + options.seen = options.seen || []; + + if (options.seen.indexOf(object) >= 0) { + return '[Circular]'; + } + + options.seen.push(object); + var propertyContents = inspectList(properties.map(function (key) { + return [key, object[key]]; + }), options, inspectProperty); + var symbolContents = inspectList(symbols.map(function (key) { + return [key, object[key]]; + }), options, inspectProperty); + options.seen.pop(); + var sep = ''; + + if (propertyContents && symbolContents) { + sep = ', '; + } + + return "{ ".concat(propertyContents).concat(sep).concat(symbolContents, " }"); + } + + var toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false; + function inspectClass(value, options) { + var name = ''; + + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + + name = name || getFuncName_1(value.constructor); // Babel transforms anonymous classes to the name `_class` + + if (!name || name === '_class') { + name = ''; + } + + options.truncate -= name.length; + return "".concat(name).concat(inspectObject(value, options)); + } + + function inspectArguments(args, options) { + if (args.length === 0) return 'Arguments[]'; + options.truncate -= 13; + return "Arguments[ ".concat(inspectList(args, options), " ]"); + } + + var errorKeys = ['stack', 'line', 'column', 'name', 'message', 'fileName', 'lineNumber', 'columnNumber', 'number', 'description']; + function inspectObject$1(error, options) { + var properties = Object.getOwnPropertyNames(error).filter(function (key) { + return errorKeys.indexOf(key) === -1; + }); + var name = error.name; + options.truncate -= name.length; + var message = ''; + + if (typeof error.message === 'string') { + message = truncate(error.message, options.truncate); + } else { + properties.unshift('message'); + } + + message = message ? ": ".concat(message) : ''; + options.truncate -= message.length + 5; + var propertyContents = inspectList(properties.map(function (key) { + return [key, error[key]]; + }), options, inspectProperty); + return "".concat(name).concat(message).concat(propertyContents ? " { ".concat(propertyContents, " }") : ''); + } + + function inspectAttribute(_ref, options) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + + options.truncate -= 3; + + if (!value) { + return "".concat(options.stylize(key, 'yellow')); + } + + return "".concat(options.stylize(key, 'yellow'), "=").concat(options.stylize("\"".concat(value, "\""), 'string')); + } + function inspectHTMLCollection(collection, options) { + // eslint-disable-next-line no-use-before-define + return inspectList(collection, options, inspectHTML, '\n'); + } + function inspectHTML(element, options) { + var properties = element.getAttributeNames(); + var name = element.tagName.toLowerCase(); + var head = options.stylize("<".concat(name), 'special'); + var headClose = options.stylize(">", 'special'); + var tail = options.stylize(""), 'special'); + options.truncate -= name.length * 2 + 5; + var propertyContents = ''; + + if (properties.length > 0) { + propertyContents += ' '; + propertyContents += inspectList(properties.map(function (key) { + return [key, element.getAttribute(key)]; + }), options, inspectAttribute, ' '); + } + + options.truncate -= propertyContents.length; + var truncate = options.truncate; + var children = inspectHTMLCollection(element.children, options); + + if (children && children.length > truncate) { + children = "".concat(truncator, "(").concat(element.children.length, ")"); + } + + return "".concat(head).concat(propertyContents).concat(headClose).concat(children).concat(tail); + } + + var symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function'; + var chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect'; + var nodeInspect = false; + + try { + // eslint-disable-next-line global-require + var nodeUtil = require('util'); + + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; + } catch (noNodeInspect) { + nodeInspect = false; + } + + function FakeMap() { + // eslint-disable-next-line prefer-template + this.key = 'chai/loupe__' + Math.random() + Date.now(); + } + + FakeMap.prototype = { + // eslint-disable-next-line object-shorthand + get: function get(key) { + return key[this.key]; + }, + // eslint-disable-next-line object-shorthand + has: function has(key) { + return this.key in key; + }, + // eslint-disable-next-line object-shorthand + set: function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this.key, { + // eslint-disable-next-line object-shorthand + value: value, + configurable: true + }); + } + } + }; + var constructorMap = new (typeof WeakMap === 'function' ? WeakMap : FakeMap)(); + var stringTagMap = {}; + var baseTypesMap = { + undefined: function undefined$1(value, options) { + return options.stylize('undefined', 'undefined'); + }, + null: function _null(value, options) { + return options.stylize(null, 'null'); + }, + boolean: function boolean(value, options) { + return options.stylize(value, 'boolean'); + }, + Boolean: function Boolean(value, options) { + return options.stylize(value, 'boolean'); + }, + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: inspectPromise, + // WeakSet, WeakMap are totally opaque to us + WeakSet: function WeakSet(value, options) { + return options.stylize('WeakSet{…}', 'special'); + }, + WeakMap: function WeakMap(value, options) { + return options.stylize('WeakMap{…}', 'special'); + }, + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: function Generator() { + return ''; + }, + DataView: function DataView() { + return ''; + }, + ArrayBuffer: function ArrayBuffer() { + return ''; + }, + Error: inspectObject$1, + HTMLCollection: inspectHTMLCollection, + NodeList: inspectHTMLCollection + }; // eslint-disable-next-line complexity + + var inspectCustom = function inspectCustom(value, options, type) { + if (chaiInspect in value && typeof value[chaiInspect] === 'function') { + return value[chaiInspect](options); + } + + if (nodeInspect && nodeInspect in value && typeof value[nodeInspect] === 'function') { + return value[nodeInspect](options.depth, options); + } + + if ('inspect' in value && typeof value.inspect === 'function') { + return value.inspect(options.depth, options); + } + + if ('constructor' in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + + if (stringTagMap[type]) { + return stringTagMap[type](value, options); + } + + return ''; + }; + + var toString$1 = Object.prototype.toString; // eslint-disable-next-line complexity + + function inspect(value, options) { + options = normaliseOptions(options); + options.inspect = inspect; + var _options = options, + customInspect = _options.customInspect; + var type = value === null ? 'null' : _typeof(value); + + if (type === 'object') { + type = toString$1.call(value).slice(8, -1); + } // If it is a base value that we already support, then use Loupe's inspector + + + if (baseTypesMap[type]) { + return baseTypesMap[type](value, options); + } // If `options.customInspect` is set to true then try to use the custom inspector + + + if (customInspect && value) { + var output = inspectCustom(value, options, type); + + if (output) { + if (typeof output === 'string') return output; + return inspect(output, options); + } + } + + var proto = value ? Object.getPrototypeOf(value) : false; // If it's a plain Object then use Loupe's inspector + + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } // Specifically account for HTMLElements + // eslint-disable-next-line no-undef + + + if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + + if ('constructor' in value) { + // If it is a class, inspect it like an object but add the constructor name + if (value.constructor !== Object) { + return inspectClass(value, options); + } // If it is an object with an anonymous prototype, display it as an object. + + + return inspectObject(value, options); + } // last chance to check if it's an object + + + if (value === Object(value)) { + return inspectObject(value, options); + } // We have run out of options! Just stringify the value + + + return options.stylize(String(value), type); + } + function registerConstructor(constructor, inspector) { + if (constructorMap.has(constructor)) { + return false; + } + + constructorMap.set(constructor, inspector); + return true; + } + function registerStringTag(stringTag, inspector) { + if (stringTag in stringTagMap) { + return false; + } + + stringTagMap[stringTag] = inspector; + return true; + } + var custom = chaiInspect; + + exports.custom = custom; + exports.default = inspect; + exports.inspect = inspect; + exports.registerConstructor = registerConstructor; + exports.registerStringTag = registerStringTag; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/web/node_modules/loupe/package.json b/web/node_modules/loupe/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ae185c8279bdf5226326ae91a00e89c0fccd6694 --- /dev/null +++ b/web/node_modules/loupe/package.json @@ -0,0 +1,141 @@ +{ + "name": "loupe", + "version": "2.3.7", + "description": "Inspect utility for Node.js and browsers", + "homepage": "https://github.com/chaijs/loupe", + "license": "MIT", + "author": "Veselin Todorov ", + "contributors": [ + "Keith Cirkel (https://github.com/keithamus)" + ], + "main": "./loupe.js", + "module": "./index.js", + "browser": { + "./index.js": "./loupe.js", + "util": false + }, + "repository": { + "type": "git", + "url": "https://github.com/chaijs/loupe" + }, + "files": [ + "loupe.js", + "index.js", + "lib/*" + ], + "scripts": { + "bench": "node -r esm bench", + "commit-msg": "commitlint -x angular", + "lint": "eslint --ignore-path .gitignore .", + "prepare": "rollup -c rollup.conf.js", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "test": "npm run test:node && npm run test:browser", + "pretest:browser": "npm run prepare", + "test:browser": "karma start --singleRun=true", + "posttest:browser": "npm run upload-coverage", + "test:node": "nyc mocha -r esm", + "posttest:node": "nyc report --report-dir \"coverage/node-$(node --version)\" --reporter=lcovonly && npm run upload-coverage", + "upload-coverage": "codecov" + }, + "eslintConfig": { + "root": true, + "parserOptions": { + "ecmaVersion": 2020 + }, + "env": { + "es6": true + }, + "plugins": [ + "filenames", + "prettier" + ], + "extends": [ + "strict/es6" + ], + "rules": { + "comma-dangle": "off", + "func-style": "off", + "no-magic-numbers": "off", + "class-methods-use-this": "off", + "array-bracket-spacing": "off", + "array-element-newline": "off", + "space-before-function-paren": "off", + "arrow-parens": "off", + "template-curly-spacing": "off", + "quotes": "off", + "generator-star-spacing": "off", + "prefer-destructuring": "off", + "no-mixed-operators": "off", + "id-blacklist": "off", + "curly": "off", + "semi": [ + "error", + "never" + ], + "prettier/prettier": [ + "error", + { + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "arrowParens": "avoid", + "bracketSpacing": true + } + ] + } + }, + "prettier": { + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "arrowParens": "avoid", + "bracketSpacing": true + }, + "dependencies": { + "get-func-name": "^2.0.1" + }, + "devDependencies": { + "@babel/core": "^7.12.10", + "@babel/preset-env": "^7.12.11", + "@commitlint/cli": "^11.0.0", + "@rollup/plugin-commonjs": "^17.0.0", + "@rollup/plugin-node-resolve": "^11.1.0", + "benchmark": "^2.1.4", + "chai": "^4.2.0", + "codecov": "^3.8.1", + "commitlint-config-angular": "^11.0.0", + "core-js": "^3.8.3", + "cross-env": "^7.0.3", + "eslint": "^7.18.0", + "eslint-config-strict": "^14.0.1", + "eslint-plugin-filenames": "^1.3.2", + "eslint-plugin-prettier": "^3.3.1", + "esm": "^3.2.25", + "husky": "^4.3.8", + "karma": "^5.2.3", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage": "^2.0.3", + "karma-edge-launcher": "^0.4.2", + "karma-firefox-launcher": "^2.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-mocha": "^2.0.1", + "karma-opera-launcher": "^1.0.0", + "karma-safari-launcher": "^1.0.0", + "karma-safaritechpreview-launcher": "^2.0.2", + "karma-sauce-launcher": "^4.3.4", + "mocha": "^8.2.1", + "nyc": "^15.1.0", + "prettier": "^2.2.1", + "rollup": "^2.37.1", + "rollup-plugin-babel": "^4.4.0", + "rollup-plugin-istanbul": "^3.0.0", + "semantic-release": "^17.3.6", + "simple-assert": "^1.0.0" + } +} diff --git a/web/node_modules/magic-string/LICENSE b/web/node_modules/magic-string/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..667e8b45e4051a6f32008aafa25ecd8aefaaa1f9 --- /dev/null +++ b/web/node_modules/magic-string/LICENSE @@ -0,0 +1,7 @@ +Copyright 2018 Rich Harris + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/web/node_modules/magic-string/README.md b/web/node_modules/magic-string/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d775357c287476f831f7b1e910d9be73facddff6 --- /dev/null +++ b/web/node_modules/magic-string/README.md @@ -0,0 +1,299 @@ +# magic-string + + + build status + + + npm version + + + license + + +Suppose you have some source code. You want to make some light modifications to it - replacing a few characters here and there, wrapping it with a header and footer, etc - and ideally you'd like to generate a [source map](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/) at the end of it. You've thought about using something like [recast](https://github.com/benjamn/recast) (which allows you to generate an AST from some JavaScript, manipulate it, and reprint it with a sourcemap without losing your comments and formatting), but it seems like overkill for your needs (or maybe the source code isn't JavaScript). + +Your requirements are, frankly, rather niche. But they're requirements that I also have, and for which I made magic-string. It's a small, fast utility for manipulating strings and generating sourcemaps. + +## Installation + +magic-string works in both node.js and browser environments. For node, install with npm: + +```bash +npm i magic-string +``` + +To use in browser, grab the [magic-string.umd.js](https://unpkg.com/magic-string/dist/magic-string.umd.js) file and add it to your page: + +```html + +``` + +(It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).) + +## Usage + +These examples assume you're in node.js, or something similar: + +```js +import MagicString from 'magic-string'; +import fs from 'fs' + +const s = new MagicString('problems = 99'); + +s.update(0, 8, 'answer'); +s.toString(); // 'answer = 99' + +s.update(11, 13, '42'); // character indices always refer to the original string +s.toString(); // 'answer = 42' + +s.prepend('var ').append(';'); // most methods are chainable +s.toString(); // 'var answer = 42;' + +const map = s.generateMap({ + source: 'source.js', + file: 'converted.js.map', + includeContent: true +}); // generates a v3 sourcemap + +fs.writeFileSync('converted.js', s.toString()); +fs.writeFileSync('converted.js.map', map.toString()); +``` + +You can pass an options argument: + +```js +const s = new MagicString(someCode, { + // these options will be used if you later call `bundle.addSource( s )` - see below + filename: 'foo.js', + indentExclusionRanges: [/*...*/], + // market source as ignore in DevTools, see below #Bundling + ignoreList: false +}); +``` + +## Methods + +### s.addSourcemapLocation( index ) + +Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below). + +### s.append( content ) + +Appends the specified content to the end of the string. Returns `this`. + +### s.appendLeft( index, content ) + +Appends the specified `content` at the `index` in the original string. If a range *ending* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`. + +### s.appendRight( index, content ) + +Appends the specified `content` at the `index` in the original string. If a range *starting* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`. + +### s.clone() + +Does what you'd expect. + +### s.generateDecodedMap( options ) + +Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. + +### s.generateMap( options ) + +Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional: + +* `file` - the filename where you plan to write the sourcemap +* `source` - the filename of the file containing the original source +* `includeContent` - whether to include the original content in the map's `sourcesContent` array +* `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. You can also set `"boundary"` to generate a semi-hi-res mappings segmented per word boundary instead of per character, suitable for string semantics that are separated by words. If sourcemap locations have been specified with `s.addSourcemapLocation()`, they will be used here. + +The returned sourcemap has two (non-enumerable) methods attached for convenience: + +* `toString` - returns the equivalent of `JSON.stringify(map)` +* `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing: + +```js +code += '\n//# sourceMappingURL=' + map.toUrl(); +``` + +### s.hasChanged() + +Indicates if the string has been changed. + +### s.indent( prefix[, options] ) + +Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`. + +The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. + +### s.insertLeft( index, content ) + +**DEPRECATED** since 0.17 – use `s.appendLeft(...)` instead + +### s.insertRight( index, content ) + +**DEPRECATED** since 0.17 – use `s.prependRight(...)` instead + +### s.isEmpty() + +Returns true if the resulting source is empty (disregarding white space). + +### s.locate( index ) + +**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30) + +### s.locateOrigin( index ) + +**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30) + +### s.move( start, end, index ) + +Moves the characters from `start` and `end` to `index`. Returns `this`. + +### s.overwrite( start, end, content[, options] ) + +Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in that range. The same restrictions as `s.remove()` apply. Returns `this`. + +The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well. + +It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content. + +### s.prepend( content ) + +Prepends the string with the specified content. Returns `this`. + +### s.prependLeft ( index, content ) + +Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + +### s.prependRight ( index, content ) + +Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + +### s.replace( regexpOrString, substitution ) + +String replacement with RegExp or string. When using a RegExp, replacer function is also supported. Returns `this`. + +```ts +import MagicString from 'magic-string' + +const s = new MagicString(source) + +s.replace('foo', 'bar') +s.replace(/foo/g, 'bar') +s.replace(/(\w)(\d+)/g, (_, $1, $2) => $1.toUpperCase() + $2) +``` + +The differences from [`String.replace`]((https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)): +- It will always match against the **original string** +- It mutates the magic string state (use `.clone()` to be immutable) + +### s.replaceAll( regexpOrString, substitution ) + +Same as `s.replace`, but replace all matched strings instead of just one. +If `substitution` is a regex, then it must have the global (`g`) flag set, or a `TypeError` is thrown. Matches the behavior of the bultin [`String.property.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll). + +### s.remove( start, end ) + +Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`. + +### s.slice( start, end ) + +Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed. + +### s.snip( start, end ) + +Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. + +### s.toString() + +Returns the generated string. + +### s.trim([ charType ]) + +Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`. + +### s.trimStart([ charType ]) + +Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`. + +### s.trimEnd([ charType ]) + +Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`. + +### s.trimLines() + +Removes empty lines from the start and end. Returns `this`. + +### s.update( start, end, content[, options] ) + +Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`. + +The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and an `overwrite` property which defaults to `false` and determines whether anything that was appended/prepended to the range will be overwritten along with the original content. + +`s.update(start, end, content)` is equivalent to `s.overwrite(start, end, content, { contentOnly: true })`. + +## Bundling + +To concatenate several sources, use `MagicString.Bundle`: + +```js +const bundle = new MagicString.Bundle(); + +bundle.addSource({ + filename: 'foo.js', + content: new MagicString('var answer = 42;') +}); + +bundle.addSource({ + filename: 'bar.js', + content: new MagicString('console.log( answer )') +}); + +// Sources can be marked as ignore-listed, which provides a hint to debuggers +// to not step into this code and also don't show the source files depending +// on user preferences. +bundle.addSource({ + filename: 'some-3rdparty-library.js', + content: new MagicString('function myLib(){}'), + ignoreList: false // <-- +}) + +// Advanced: a source can include an `indentExclusionRanges` property +// alongside `filename` and `content`. This will be passed to `s.indent()` +// - see documentation above + +bundle.indent() // optionally, pass an indent string, otherwise it will be guessed + .prepend('(function () {\n') + .append('}());'); + +bundle.toString(); +// (function () { +// var answer = 42; +// console.log( answer ); +// }()); + +// options are as per `s.generateMap()` above +const map = bundle.generateMap({ + file: 'bundle.js', + includeContent: true, + hires: true +}); +``` + +As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself: + +```js +const bundle = new MagicString.Bundle(); +const source = new MagicString(someCode, { + filename: 'foo.js' +}); + +bundle.addSource(source); +``` + +## License + +MIT diff --git a/web/node_modules/magic-string/dist/magic-string.cjs.d.ts b/web/node_modules/magic-string/dist/magic-string.cjs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06b1a17c468950c43d3a316a825848bb4b0a9be3 --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.cjs.d.ts @@ -0,0 +1,268 @@ +export interface BundleOptions { + intro?: string; + separator?: string; +} + +export interface SourceMapOptions { + /** + * Whether the mapping should be high-resolution. + * Hi-res mappings map every single character, meaning (for example) your devtools will always + * be able to pinpoint the exact location of function calls and so on. + * With lo-res mappings, devtools may only be able to identify the correct + * line - but they're quicker to generate and less bulky. + * You can also set `"boundary"` to generate a semi-hi-res mappings segmented per word boundary + * instead of per character, suitable for string semantics that are separated by words. + * If sourcemap locations have been specified with s.addSourceMapLocation(), they will be used here. + */ + hires?: boolean | 'boundary'; + /** + * The filename where you plan to write the sourcemap. + */ + file?: string; + /** + * The filename of the file containing the original source. + */ + source?: string; + /** + * Whether to include the original content in the map's sourcesContent array. + */ + includeContent?: boolean; +} + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; + +export interface DecodedSourceMap { + file: string; + sources: string[]; + sourcesContent?: string[]; + names: string[]; + mappings: SourceMapSegment[][]; + x_google_ignoreList?: number[]; +} + +export class SourceMap { + constructor(properties: DecodedSourceMap); + + version: number; + file: string; + sources: string[]; + sourcesContent?: string[]; + names: string[]; + mappings: string; + x_google_ignoreList?: number[]; + + /** + * Returns the equivalent of `JSON.stringify(map)` + */ + toString(): string; + /** + * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing: + * `generateMap(options?: SourceMapOptions): SourceMap;` + */ + toUrl(): string; +} + +export class Bundle { + constructor(options?: BundleOptions); + /** + * Adds the specified source to the bundle, which can either be a `MagicString` object directly, + * or an options object that holds a magic string `content` property and optionally provides + * a `filename` for the source within the bundle, as well as an optional `ignoreList` hint + * (which defaults to `false`). The `filename` is used when constructing the source map for the + * bundle, to identify this `source` in the source map's `sources` field. The `ignoreList` hint + * is used to populate the `x_google_ignoreList` extension field in the source map, which is a + * mechanism for tools to signal to debuggers that certain sources should be ignored by default + * (depending on user preferences). + */ + addSource(source: MagicString | { filename?: string, content: MagicString, ignoreList?: boolean }): Bundle; + append(str: string, options?: BundleOptions): Bundle; + clone(): Bundle; + generateMap(options?: SourceMapOptions): Omit & { sourcesContent: Array }; + generateDecodedMap(options?: SourceMapOptions): Omit & { sourcesContent: Array }; + getIndentString(): string; + indent(indentStr?: string): Bundle; + indentExclusionRanges: ExclusionRange | Array; + prepend(str: string): Bundle; + toString(): string; + trimLines(): Bundle; + trim(charType?: string): Bundle; + trimStart(charType?: string): Bundle; + trimEnd(charType?: string): Bundle; + isEmpty(): boolean; + length(): number; +} + +export type ExclusionRange = [ number, number ]; + +export interface MagicStringOptions { + filename?: string, + indentExclusionRanges?: ExclusionRange | Array; +} + +export interface IndentOptions { + exclude?: ExclusionRange | Array; + indentStart?: boolean; +} + +export interface OverwriteOptions { + storeName?: boolean; + contentOnly?: boolean; +} + +export interface UpdateOptions { + storeName?: boolean; + overwrite?: boolean; +} + +export default class MagicString { + constructor(str: string, options?: MagicStringOptions); + /** + * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false. + */ + addSourcemapLocation(char: number): void; + /** + * Appends the specified content to the end of the string. + */ + append(content: string): MagicString; + /** + * Appends the specified content at the index in the original string. + * If a range *ending* with index is subsequently moved, the insert will be moved with it. + * See also `s.prependLeft(...)`. + */ + appendLeft(index: number, content: string): MagicString; + /** + * Appends the specified content at the index in the original string. + * If a range *starting* with index is subsequently moved, the insert will be moved with it. + * See also `s.prependRight(...)`. + */ + appendRight(index: number, content: string): MagicString; + /** + * Does what you'd expect. + */ + clone(): MagicString; + /** + * Generates a version 3 sourcemap. + */ + generateMap(options?: SourceMapOptions): SourceMap; + /** + * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. + * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. + */ + generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap; + getIndentString(): string; + + /** + * Prefixes each line of the string with prefix. + * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. + */ + indent(options?: IndentOptions): MagicString; + /** + * Prefixes each line of the string with prefix. + * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. + * + * The options argument can have an exclude property, which is an array of [start, end] character ranges. + * These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. + */ + indent(indentStr?: string, options?: IndentOptions): MagicString; + indentExclusionRanges: ExclusionRange | Array; + + /** + * Moves the characters from `start and `end` to `index`. + */ + move(start: number, end: number, index: number): MagicString; + /** + * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in + * that range. The same restrictions as `s.remove()` apply. + * + * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored + * for later inclusion in a sourcemap's names array — and a contentOnly property which determines whether only + * the content is overwritten, or anything that was appended/prepended to the range as well. + * + * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content. + */ + overwrite(start: number, end: number, content: string, options?: boolean | OverwriteOptions): MagicString; + /** + * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. + * + * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored + * for later inclusion in a sourcemap's names array — and an overwrite property which determines whether only + * the content is overwritten, or anything that was appended/prepended to the range as well. + */ + update(start: number, end: number, content: string, options?: boolean | UpdateOptions): MagicString; + /** + * Prepends the string with the specified content. + */ + prepend(content: string): MagicString; + /** + * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index + */ + prependLeft(index: number, content: string): MagicString; + /** + * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + */ + prependRight(index: number, content: string): MagicString; + /** + * Removes the characters from `start` to `end` (of the original string, **not** the generated string). + * Removing the same content twice, or making removals that partially overlap, will cause an error. + */ + remove(start: number, end: number): MagicString; + /** + * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string). + */ + reset(start: number, end: number): MagicString; + /** + * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. + * Throws error if the indices are for characters that were already removed. + */ + slice(start: number, end: number): string; + /** + * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. + */ + snip(start: number, end: number): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. + */ + trim(charType?: string): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. + */ + trimStart(charType?: string): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. + */ + trimEnd(charType?: string): MagicString; + /** + * Removes empty lines from the start and end. + */ + trimLines(): MagicString; + /** + * String replacement with RegExp or string. + */ + replace(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): MagicString; + /** + * Same as `s.replace`, but replace all matched strings instead of just one. + */ + replaceAll(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): MagicString; + + lastChar(): string; + lastLine(): string; + /** + * Returns true if the resulting source is empty (disregarding white space). + */ + isEmpty(): boolean; + length(): number; + + /** + * Indicates if the string has been changed. + */ + hasChanged(): boolean; + + original: string; + /** + * Returns the generated string. + */ + toString(): string; +} diff --git a/web/node_modules/magic-string/dist/magic-string.cjs.js b/web/node_modules/magic-string/dist/magic-string.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..db9c6ac69b911f25b38f9d65474839ab7bd5bb73 --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.cjs.js @@ -0,0 +1,1534 @@ +'use strict'; + +var sourcemapCodec = require('@jridgewell/sourcemap-codec'); + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + reset() { + this.intro = ''; + this.outro = ''; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa = /*#__PURE__*/ getBtoa(); + +class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = sourcemapCodec.encode(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + } +} + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + reset(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.reset(); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +const hasOwnProp = Object.prototype.hasOwnProperty; + +class Bundle { + constructor(options = {}) { + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; + } + + addSource(source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`', + ); + } + + ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => { + if (!hasOwnProp.call(source, option)) source[option] = source.content[option]; + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(`Illegal source: same filename (${source.filename}), different contents`); + } + } + } + + this.sources.push(source); + return this; + } + + append(str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; + } + + clone() { + const bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach((source) => { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; + } + + generateDecodedMap(options = {}) { + const names = []; + let x_google_ignoreList = undefined; + this.sources.forEach((source) => { + Object.keys(source.content.storedNames).forEach((name) => { + if (!~names.indexOf(name)) names.push(name); + }); + }); + + const mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach((source, i) => { + if (i > 0) { + mappings.advance(this.separator); + } + + const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1; + const magicString = source.content; + const locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations, + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + + if (source.ignoreList && sourceIndex !== -1) { + if (x_google_ignoreList === undefined) { + x_google_ignoreList = []; + } + x_google_ignoreList.push(sourceIndex); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: this.uniqueSources.map((source) => { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map((source) => { + return options.includeContent ? source.content : null; + }), + names, + mappings: mappings.raw, + x_google_ignoreList, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + getIndentString() { + const indentStringCounts = {}; + + this.sources.forEach((source) => { + const indentStr = source.content._getRawIndentString(); + + if (indentStr === null) return; + + if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0; + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort((a, b) => { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); + } + + indent(indentStr) { + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') return this; // noop + + let trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, (match, index) => { + return index > 0 ? indentStr + match : match; + }); + } + + return this; + } + + prepend(str) { + this.intro = str + this.intro; + return this; + } + + toString() { + const body = this.sources + .map((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; + } + + isEmpty() { + if (this.intro.length && this.intro.trim()) return false; + if (this.sources.some((source) => !source.content.isEmpty())) return false; + return true; + } + + length() { + return this.sources.reduce( + (length, source) => length + source.content.length(), + this.intro.length, + ); + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimStart(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + let source; + let i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; + } + + trimEnd(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + let source; + let i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; + } +} + +MagicString.Bundle = Bundle; +MagicString.SourceMap = SourceMap; +MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121 + +module.exports = MagicString; +//# sourceMappingURL=magic-string.cjs.js.map diff --git a/web/node_modules/magic-string/dist/magic-string.cjs.js.map b/web/node_modules/magic-string/dist/magic-string.cjs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6a84bfae080ab867958d3e38c7e657100fa312cd --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"magic-string.cjs.js","sources":["../src/BitSet.js","../src/Chunk.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js","../src/index-legacy.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + '' \n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from '@jridgewell/sourcemap-codec';\n\nfunction getBtoa() {\n\tif (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {\n\t\treturn (str) => globalThis.btoa(unescape(encodeURIComponent(str)));\n\t} else if (typeof Buffer === 'function') {\n\t\treturn (str) => Buffer.from(str, 'utf-8').toString('base64');\n\t} else {\n\t\treturn () => {\n\t\t\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n\t\t};\n\t}\n}\n\nconst btoa = /*#__PURE__*/ getBtoa();\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t\tif (typeof properties.x_google_ignoreList !== 'undefined') {\n\t\t\tthis.x_google_ignoreList = properties.x_google_ignoreList;\n\t\t}\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","const wordRegex = /\\w/;\n\nexport default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tlet contentLineEnd = content.indexOf('\\n', 0);\n\t\t\tlet previousContentLineEnd = -1;\n\t\t\twhile (contentLineEnd >= 0) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\t\tif (nameIndex >= 0) {\n\t\t\t\t\tsegment.push(nameIndex);\n\t\t\t\t}\n\t\t\t\tthis.rawSegments.push(segment);\n\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\n\t\t\t\tpreviousContentLineEnd = contentLineEnd;\n\t\t\t\tcontentLineEnd = content.indexOf('\\n', contentLineEnd + 1);\n\t\t\t}\n\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\n\t\t\tthis.advance(content.slice(previousContentLineEnd + 1));\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t\tthis.advance(content);\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\t\t// when iterating each char, check if it's in a word boundary\n\t\tlet charInHiresBoundary = false;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\n\t\t\t\tif (this.hires === 'boundary') {\n\t\t\t\t\t// in hires \"boundary\", group segments per word boundary than per char\n\t\t\t\t\tif (wordRegex.test(original[originalCharIndex])) {\n\t\t\t\t\t\t// for first char in the boundary found, start the boundary by pushing a segment\n\t\t\t\t\t\tif (!charInHiresBoundary) {\n\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\tcharInHiresBoundary = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// for non-word char, end the boundary by pushing a segment\n\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\tcharInHiresBoundary = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t} else {\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: undefined },\n\t\t\tignoreList: { writable: true, value: options.ignoreList },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: [\n\t\t\t\toptions.source ? getRelativePath(options.file || '', options.source) : options.file || '',\n\t\t\t],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : undefined,\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\t_ensureindentStr() {\n\t\tif (this.indentStr === undefined) {\n\t\t\tthis.indentStr = guessIndent(this.original);\n\t\t}\n\t}\n\n\t_getRawIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr;\n\t}\n\n\tgetIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tif (indentStr === undefined) {\n\t\t\tthis._ensureindentStr();\n\t\t\tindentStr = this.indentStr || '\\t';\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\toptions = options || {};\n\t\treturn this.update(start, end, content, { ...options, overwrite: !options.contentOnly });\n\t}\n\n\tupdate(start, end, content, options) {\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',\n\t\t\t\t); // eslint-disable-line no-console\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst overwrite = options !== undefined ? options.overwrite : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, {\n\t\t\t\twritable: true,\n\t\t\t\tvalue: true,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, !overwrite);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\treset(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('reset');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.reset();\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('reset');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`,\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n\n\thasChanged() {\n\t\treturn this.original !== this.toString();\n\t}\n\n\t_replaceRegexp(searchValue, replacement) {\n\t\tfunction getReplacement(match, str) {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treturn replacement.replace(/\\$(\\$|&|\\d+)/g, (_, i) => {\n\t\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter\n\t\t\t\t\tif (i === '$') return '$';\n\t\t\t\t\tif (i === '&') return match[0];\n\t\t\t\t\tconst num = +i;\n\t\t\t\t\tif (num < match.length) return match[+i];\n\t\t\t\t\treturn `$${i}`;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\treturn replacement(...match, match.index, str, match.groups);\n\t\t\t}\n\t\t}\n\t\tfunction matchAll(re, str) {\n\t\t\tlet match;\n\t\t\tconst matches = [];\n\t\t\twhile ((match = re.exec(str))) {\n\t\t\t\tmatches.push(match);\n\t\t\t}\n\t\t\treturn matches;\n\t\t}\n\t\tif (searchValue.global) {\n\t\t\tconst matches = matchAll(searchValue, this.original);\n\t\t\tmatches.forEach((match) => {\n\t\t\t\tif (match.index != null)\n\t\t\t\t\tthis.overwrite(\n\t\t\t\t\t\tmatch.index,\n\t\t\t\t\t\tmatch.index + match[0].length,\n\t\t\t\t\t\tgetReplacement(match, this.original),\n\t\t\t\t\t);\n\t\t\t});\n\t\t} else {\n\t\t\tconst match = this.original.match(searchValue);\n\t\t\tif (match && match.index != null)\n\t\t\t\tthis.overwrite(\n\t\t\t\t\tmatch.index,\n\t\t\t\t\tmatch.index + match[0].length,\n\t\t\t\t\tgetReplacement(match, this.original),\n\t\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\t_replaceString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst index = original.indexOf(string);\n\n\t\tif (index !== -1) {\n\t\t\tthis.overwrite(index, index + string.length, replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplace(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceString(searchValue, replacement);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n\n\t_replaceAllString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst stringLength = string.length;\n\t\tfor (\n\t\t\tlet index = original.indexOf(string);\n\t\t\tindex !== -1;\n\t\t\tindex = original.indexOf(string, index + stringLength)\n\t\t) {\n\t\t\tthis.overwrite(index, index + stringLength, replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplaceAll(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceAllString(searchValue, replacement);\n\t\t}\n\n\t\tif (!searchValue.global) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'MagicString.prototype.replaceAll called with a non-global RegExp argument',\n\t\t\t);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tlet x_google_ignoreList = undefined;\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\n\t\t\tif (source.ignoreList && sourceIndex !== -1) {\n\t\t\t\tif (x_google_ignoreList === undefined) {\n\t\t\t\t\tx_google_ignoreList = [];\n\t\t\t\t}\n\t\t\t\tx_google_ignoreList.push(sourceIndex);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content._getRawIndentString();\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length,\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport Bundle from './Bundle.js';\nimport SourceMap from './SourceMap.js';\n\nMagicString.Bundle = Bundle;\nMagicString.SourceMap = SourceMap;\nMagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121\n\nexport default MagicString;\n"],"names":["encode"],"mappings":";;;;AAAe,MAAM,MAAM,CAAC;AAC5B,CAAC,WAAW,CAAC,GAAG,EAAE;AAClB,EAAE,IAAI,CAAC,IAAI,GAAG,GAAG,YAAY,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC;AAC5D,EAAE;AACF;AACA,CAAC,GAAG,CAAC,CAAC,EAAE;AACR,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;AACrC,EAAE;AACF;AACA,CAAC,GAAG,CAAC,CAAC,EAAE;AACR,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;AACjD,EAAE;AACF;;ACZe,MAAM,KAAK,CAAC;AAC3B,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE;AAClC,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACrB,EAAE,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;AACjB,EAAE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC1B;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;AACzB,EAAE,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AACtB;AACA,EAMS;AACT,GAAG,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACxB,GAAG,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACpB,GAAG;AACH,EAAE;AACF;AACA,CAAC,UAAU,CAAC,OAAO,EAAE;AACrB,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACxB,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;AACpC,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC3B,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC3B,EAAE,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;AAC/B,EAAE,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACnC,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAC7B;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,QAAQ,CAAC,KAAK,EAAE;AACjB,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC;AAChD,EAAE;AACF;AACA,CAAC,QAAQ,CAAC,EAAE,EAAE;AACd,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AACnB,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;AACb,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH,EAAE;AACF;AACA,CAAC,YAAY,CAAC,EAAE,EAAE;AAClB,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AACnB,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;AACb,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC;AAC1B,GAAG;AACH,EAAE;AACF;AACA,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE;AACvC,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,WAAW,EAAE;AACpB,GAAG,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AACnB,GAAG,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AACnB,GAAG;AACH,EAAE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;AAC7B;AACA,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;AACrB;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACpC,EAAE;AACF;AACA,CAAC,YAAY,CAAC,OAAO,EAAE;AACvB,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACpC,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;AACnB,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC;AAChC,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;AAC1B,GAAG,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AACvB,GAAG;AACH,EAAE;AACF;AACA,CAAC,KAAK,CAAC,KAAK,EAAE;AACd,EAAE,MAAM,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AACxC;AACA,EAAE,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;AAC5D,EAAE,MAAM,aAAa,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AACxD;AACA,EAAE,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;AACjC;AACA,EAAE,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;AAC7D,EAAE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC9B,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB;AACA,EAAE,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC;AACnB;AACA,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;AAC5B,GAAG,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;AACrB,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,OAAO,GAAG,cAAc,CAAC;AACjC,GAAG;AACH;AACA,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;AAC5B,EAAE,IAAI,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACvD,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC3B,EAAE,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;AACvB;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AAChD,EAAE;AACF;AACA,CAAC,OAAO,CAAC,EAAE,EAAE;AACb,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C;AACA,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;AACtB,GAAG,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE;AACjC,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACtE,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB;AACA,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC9C,KAAK;AACL,IAAI;AACJ,GAAG,OAAO,IAAI,CAAC;AACf,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAClC;AACA,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC3C,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACtC,GAAG;AACH,EAAE;AACF;AACA,CAAC,SAAS,CAAC,EAAE,EAAE;AACf,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C;AACA,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;AACtB,GAAG,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE;AACjC,IAAI,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3D,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB;AACA,KAAK,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAClD,KAAK;AACL,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACnC,IAAI;AACJ,GAAG,OAAO,IAAI,CAAC;AACf,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAClC;AACA,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC3C,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACtC,GAAG;AACH,EAAE;AACF;;ACrLA,SAAS,OAAO,GAAG;AACnB,CAAC,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,UAAU,EAAE;AACjF,EAAE,OAAO,CAAC,GAAG,KAAK,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACrE,EAAE,MAAM,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;AAC1C,EAAE,OAAO,CAAC,GAAG,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAC/D,EAAE,MAAM;AACR,EAAE,OAAO,MAAM;AACf,GAAG,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;AAC9F,GAAG,CAAC;AACJ,EAAE;AACF,CAAC;AACD;AACA,MAAM,IAAI,iBAAiB,OAAO,EAAE,CAAC;AACrC;AACe,MAAM,SAAS,CAAC;AAC/B,CAAC,WAAW,CAAC,UAAU,EAAE;AACzB,EAAE,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC;AAC9B,EAAE,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;AACpC,EAAE,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;AAClD,EAAE,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;AAChC,EAAE,IAAI,CAAC,QAAQ,GAAGA,qBAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AAC9C,EAAE,IAAI,OAAO,UAAU,CAAC,mBAAmB,KAAK,WAAW,EAAE;AAC7D,GAAG,IAAI,CAAC,mBAAmB,GAAG,UAAU,CAAC,mBAAmB,CAAC;AAC7D,GAAG;AACH,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC9B,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,OAAO,6CAA6C,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC/E,EAAE;AACF;;ACpCe,SAAS,WAAW,CAAC,IAAI,EAAE;AAC1C,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC;AACA,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1D,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACjD,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA;AACA;AACA;AACA,CAAC,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;AACrC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA;AACA,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,OAAO,KAAK;AAClD,EAAE,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AACvC,EAAE,EAAE,QAAQ,CAAC,CAAC;AACd;AACA,CAAC,OAAO,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrC;;ACxBe,SAAS,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE;AAClD,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACvC,CAAC,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACnC;AACA,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC;AACjB;AACA,CAAC,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE;AACrC,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC;AACpB,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;AAClB,EAAE;AACF;AACA,CAAC,IAAI,SAAS,CAAC,MAAM,EAAE;AACvB,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC;AAC3B,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAClC,EAAE;AACF;AACA,CAAC,OAAO,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5C;;ACjBA,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;AAC3C;AACe,SAAS,QAAQ,CAAC,KAAK,EAAE;AACxC,CAAC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,iBAAiB,CAAC;AACnD;;ACJe,SAAS,UAAU,CAAC,MAAM,EAAE;AAC3C,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AACxB;AACA,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACzD,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACxB,EAAE,GAAG,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AACrC,EAAE;AACF;AACA,CAAC,OAAO,SAAS,MAAM,CAAC,KAAK,EAAE;AAC/B,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;AACZ,EAAE,IAAI,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC;AAC7B,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE;AAChB,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAC1B,GAAG,IAAI,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,IAAI,CAAC,GAAG,CAAC,CAAC;AACV,IAAI,MAAM;AACV,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,IAAI;AACJ,GAAG;AACH,EAAE,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;AACrB,EAAE,MAAM,MAAM,GAAG,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;AAC3C,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1B,EAAE,CAAC;AACH;;ACxBA,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB;AACe,MAAM,QAAQ,CAAC;AAC9B,CAAC,WAAW,CAAC,KAAK,EAAE;AACpB,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACrB,EAAE,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;AAC7B,EAAE,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AAC/B,EAAE,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;AAChB,EAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,CAAC;AAC3D,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE;AACF;AACA,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE;AAC/C,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;AACtB,GAAG,IAAI,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,GAAG,IAAI,sBAAsB,GAAG,CAAC,CAAC,CAAC;AACnC,GAAG,OAAO,cAAc,IAAI,CAAC,EAAE;AAC/B,IAAI,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AAClF,IAAI,IAAI,SAAS,IAAI,CAAC,EAAE;AACxB,KAAK,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAC7B,KAAK;AACL,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACnC;AACA,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;AAChC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;AAC7D,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AACjC;AACA,IAAI,sBAAsB,GAAG,cAAc,CAAC;AAC5C,IAAI,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,CAAC,CAAC,CAAC;AAC/D,IAAI;AACJ;AACA,GAAG,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AACjF,GAAG,IAAI,SAAS,IAAI,CAAC,EAAE;AACvB,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAC5B,IAAI;AACJ,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAClC;AACA,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,sBAAsB,GAAG,CAAC,CAAC,CAAC,CAAC;AAC3D,GAAG,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE;AAC3B,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACvC,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE;AACF;AACA,CAAC,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,kBAAkB,EAAE;AACzE,EAAE,IAAI,iBAAiB,GAAG,KAAK,CAAC,KAAK,CAAC;AACtC,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AACnB;AACA,EAAE,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAClC;AACA,EAAE,OAAO,iBAAiB,GAAG,KAAK,CAAC,GAAG,EAAE;AACxC,GAAG,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,IAAI,kBAAkB,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE;AACzE,IAAI,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AAClF;AACA,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,UAAU,EAAE;AACnC;AACA,KAAK,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,EAAE;AACtD;AACA,MAAM,IAAI,CAAC,mBAAmB,EAAE;AAChC,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACtC,OAAO,mBAAmB,GAAG,IAAI,CAAC;AAClC,OAAO;AACP,MAAM,MAAM;AACZ;AACA,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACrC,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAClC,MAAM;AACN,KAAK,MAAM;AACX,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,KAAK;AACL,IAAI;AACJ;AACA,GAAG,IAAI,QAAQ,CAAC,iBAAiB,CAAC,KAAK,IAAI,EAAE;AAC7C,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;AAClB,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;AACnB,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;AAChC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;AAC7D,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AACjC,IAAI,KAAK,GAAG,IAAI,CAAC;AACjB,IAAI,MAAM;AACV,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;AACpB,IAAI,IAAI,CAAC,mBAAmB,IAAI,CAAC,CAAC;AAClC,IAAI,KAAK,GAAG,KAAK,CAAC;AAClB,IAAI;AACJ;AACA,GAAG,iBAAiB,IAAI,CAAC,CAAC;AAC1B,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE;AACF;AACA,CAAC,OAAO,CAAC,GAAG,EAAE;AACd,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO;AACnB;AACA,EAAE,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC;AACA,EAAE,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;AACxB,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC9C,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;AAC7B,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;AAC7D,IAAI;AACJ,GAAG,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,mBAAmB,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;AAC7D,EAAE;AACF;;AClGA,MAAM,CAAC,GAAG,IAAI,CAAC;AACf;AACA,MAAM,MAAM,GAAG;AACf,CAAC,UAAU,EAAE,KAAK;AAClB,CAAC,WAAW,EAAE,KAAK;AACnB,CAAC,SAAS,EAAE,KAAK;AACjB,CAAC,CAAC;AACF;AACe,MAAM,WAAW,CAAC;AACjC,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,EAAE,EAAE;AACnC,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AACpD;AACA,EAAE,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE;AAChC,GAAG,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE;AAC9C,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACvC,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACvC,GAAG,UAAU,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;AAC/C,GAAG,SAAS,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;AAC9C,GAAG,iBAAiB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;AACtD,GAAG,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACzC,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACvC,GAAG,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,EAAE;AACxD,GAAG,qBAAqB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,qBAAqB,EAAE;AAClF,GAAG,kBAAkB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,MAAM,EAAE,EAAE;AAC9D,GAAG,WAAW,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AAC7C,GAAG,SAAS,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE;AAClD,GAAG,UAAU,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,EAAE;AAC5D,GAAG,CAAC,CAAC;AAKL;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;AAC1B,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;AACpC,EAAE;AACF;AACA,CAAC,oBAAoB,CAAC,IAAI,EAAE;AAC5B,EAAE,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACpC,EAAE;AACF;AACA,CAAC,MAAM,CAAC,OAAO,EAAE;AACjB,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;AACzF;AACA,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACxB,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;AAC5B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AAC7B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACzB,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAC9B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACzB,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC7E;AACA,EAAE,IAAI,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC;AACtC,EAAE,IAAI,WAAW,IAAI,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,iBAAiB,GAAG,aAAa,CAAC,KAAK,EAAE,CAAC,CAAC;AAC3F;AACA,EAAE,OAAO,aAAa,EAAE;AACxB,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,WAAW,CAAC;AACnD,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC;AAC/C;AACA,GAAG,MAAM,iBAAiB,GAAG,aAAa,CAAC,IAAI,CAAC;AAChD,GAAG,MAAM,eAAe,GAAG,iBAAiB,IAAI,iBAAiB,CAAC,KAAK,EAAE,CAAC;AAC1E;AACA,GAAG,IAAI,eAAe,EAAE;AACxB,IAAI,WAAW,CAAC,IAAI,GAAG,eAAe,CAAC;AACvC,IAAI,eAAe,CAAC,QAAQ,GAAG,WAAW,CAAC;AAC3C;AACA,IAAI,WAAW,GAAG,eAAe,CAAC;AAClC,IAAI;AACJ;AACA,GAAG,aAAa,GAAG,iBAAiB,CAAC;AACrC,GAAG;AACH;AACA,EAAE,MAAM,CAAC,SAAS,GAAG,WAAW,CAAC;AACjC;AACA,EAAE,IAAI,IAAI,CAAC,qBAAqB,EAAE;AAClC,GAAG,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC;AACrE,GAAG;AACH;AACA,EAAE,MAAM,CAAC,kBAAkB,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;AAClE;AACA,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC5B,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC5B;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA,CAAC,kBAAkB,CAAC,OAAO,EAAE;AAC7B,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA,EAAE,MAAM,WAAW,GAAG,CAAC,CAAC;AACxB,EAAE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC9C,EAAE,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,EAAE,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC3C;AACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;AAClB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,KAAK;AACtC,GAAG,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACnC;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACzD;AACA,GAAG,IAAI,KAAK,CAAC,MAAM,EAAE;AACrB,IAAI,QAAQ,CAAC,OAAO;AACpB,KAAK,WAAW;AAChB,KAAK,KAAK,CAAC,OAAO;AAClB,KAAK,GAAG;AACR,KAAK,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACzD,KAAK,CAAC;AACN,IAAI,MAAM;AACV,IAAI,QAAQ,CAAC,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;AAC/F,IAAI;AACJ;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACzD,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO;AACT,GAAG,IAAI,EAAE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,SAAS;AACrE,GAAG,OAAO,EAAE;AACZ,IAAI,OAAO,CAAC,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;AAC7F,IAAI;AACJ,GAAG,cAAc,EAAE,OAAO,CAAC,cAAc,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,SAAS;AACvE,GAAG,KAAK;AACR,GAAG,QAAQ,EAAE,QAAQ,CAAC,GAAG;AACzB,GAAG,mBAAmB,EAAE,IAAI,CAAC,UAAU,GAAG,CAAC,WAAW,CAAC,GAAG,SAAS;AACnE,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AACzD,EAAE;AACF;AACA,CAAC,gBAAgB,GAAG;AACpB,EAAE,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE;AACpC,GAAG,IAAI,CAAC,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/C,GAAG;AACH,EAAE;AACF;AACA,CAAC,mBAAmB,GAAG;AACvB,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;AAC1B,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC;AACxB,EAAE;AACF;AACA,CAAC,eAAe,GAAG;AACnB,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;AAC1B,EAAE,OAAO,IAAI,CAAC,SAAS,KAAK,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;AACzD,EAAE;AACF;AACA,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,EAAE;AAC5B,EAAE,MAAM,OAAO,GAAG,YAAY,CAAC;AAC/B;AACA,EAAE,IAAI,QAAQ,CAAC,SAAS,CAAC,EAAE;AAC3B,GAAG,OAAO,GAAG,SAAS,CAAC;AACvB,GAAG,SAAS,GAAG,SAAS,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAI,SAAS,KAAK,SAAS,EAAE;AAC/B,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;AAC3B,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;AACtC,GAAG;AACH;AACA,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC;AACpC;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA;AACA,EAAE,MAAM,UAAU,GAAG,EAAE,CAAC;AACxB;AACA,EAAE,IAAI,OAAO,CAAC,OAAO,EAAE;AACvB,GAAG,MAAM,UAAU;AACnB,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;AACjF,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,KAAK;AACrC,IAAI,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;AACzD,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAC1B,KAAK;AACL,IAAI,CAAC,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,yBAAyB,GAAG,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC;AAChE,EAAE,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK;AAC9B,GAAG,IAAI,yBAAyB,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AAChE,GAAG,yBAAyB,GAAG,IAAI,CAAC;AACpC,GAAG,OAAO,KAAK,CAAC;AAChB,GAAG,CAAC;AACJ;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD;AACA,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB;AACA,GAAG,IAAI,KAAK,CAAC,MAAM,EAAE;AACrB,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;AAChC,KAAK,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC9D;AACA,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;AAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC;AACnF,MAAM;AACN,KAAK;AACL,IAAI,MAAM;AACV,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC;AAC5B;AACA,IAAI,OAAO,SAAS,GAAG,GAAG,EAAE;AAC5B,KAAK,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;AACjC,MAAM,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAC5C;AACA,MAAM,IAAI,IAAI,KAAK,IAAI,EAAE;AACzB,OAAO,yBAAyB,GAAG,IAAI,CAAC;AACxC,OAAO,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,yBAAyB,EAAE;AAC7D,OAAO,yBAAyB,GAAG,KAAK,CAAC;AACzC;AACA,OAAO,IAAI,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE;AACtC,QAAQ,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACtC,QAAQ,MAAM;AACd,QAAQ,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC3C,QAAQ,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AAC3B,QAAQ,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACtC,QAAQ;AACR,OAAO;AACP,MAAM;AACN;AACA,KAAK,SAAS,IAAI,CAAC,CAAC;AACpB,KAAK;AACL,IAAI;AACJ;AACA,GAAG,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,GAAG;AACV,EAAE,MAAM,IAAI,KAAK;AACjB,GAAG,iFAAiF;AACpF,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;AAC5B,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE;AAC1B,GAAG,OAAO,CAAC,IAAI;AACf,IAAI,oFAAoF;AACxF,IAAI,CAAC;AACL,GAAG,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;AAC5B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AACzC,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7B,EAAE,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;AAC3B,GAAG,OAAO,CAAC,IAAI;AACf,IAAI,uFAAuF;AAC3F,IAAI,CAAC;AACL,GAAG,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC;AAC7B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAC3C,EAAE;AACF;AACA,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE;AACzB,EAAE,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AAG/F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC/B;AACA,EAAE,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC;AACjC,EAAE,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC;AAC7B;AACA,EAAE,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACvC,EAAE,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE,OAAO,IAAI,CAAC;AACxD,EAAE,MAAM,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;AAChE;AACA,EAAE,IAAI,OAAO,EAAE,OAAO,CAAC,IAAI,GAAG,QAAQ,CAAC;AACvC,EAAE,IAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC5C;AACA,EAAE,IAAI,OAAO,EAAE,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC;AACpC,EAAE,IAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AACzC;AACA,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;AACnD,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;AAClB,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,QAAQ,CAAC;AACnC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC;AAC9B,GAAG;AACH;AACA,EAAE,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC3B,EAAE,IAAI,CAAC,IAAI,GAAG,QAAQ,IAAI,IAAI,CAAC;AAC/B;AACA,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;AACxC,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;AAGvC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;AACzC,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;AAC3F,EAAE;AACF;AACA,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;AACtC,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,sCAAsC,CAAC,CAAC;AAC/F;AACA,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;AAC1E,EAAE,IAAI,KAAK,KAAK,GAAG;AACnB,GAAG,MAAM,IAAI,KAAK;AAClB,IAAI,+EAA+E;AACnF,IAAI,CAAC;AAGL;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,OAAO,KAAK,IAAI,EAAE;AACxB,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE;AAC1B,IAAI,OAAO,CAAC,IAAI;AAChB,KAAK,+HAA+H;AACpI,KAAK,CAAC;AACN,IAAI,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;AAC5B,IAAI;AACJ;AACA,GAAG,OAAO,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACjC,GAAG;AACH,EAAE,MAAM,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC;AACtE,EAAE,MAAM,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC;AACtE;AACA,EAAE,IAAI,SAAS,EAAE;AACjB,GAAG,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACpD,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE;AACrD,IAAI,QAAQ,EAAE,IAAI;AAClB,IAAI,KAAK,EAAE,IAAI;AACf,IAAI,UAAU,EAAE,IAAI;AACpB,IAAI,CAAC,CAAC;AACN,GAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC/B;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,IAAI,KAAK,GAAG,KAAK,CAAC;AACrB,GAAG,OAAO,KAAK,KAAK,IAAI,EAAE;AAC1B,IAAI,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;AAChD,KAAK,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AAC9D,KAAK;AACL,IAAI,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACvB,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;AAC1B,IAAI;AACJ;AACA,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,CAAC,SAAS,CAAC,CAAC;AAC9C,GAAG,MAAM;AACT;AACA,GAAG,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACvE;AACA;AACA,GAAG,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;AACxB,GAAG,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC5B,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,OAAO,EAAE;AAClB,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;AACzF;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACpC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAC9B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACrC,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE;AAC9B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;AAC/B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACrC,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE;AACpB,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE,OAAO,IAAI,CAAC;AACjC;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAC7F,EAAE,IAAI,KAAK,GAAG,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AAGrE;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;AACpB,GAAG,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;AACpB,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAClB;AACA,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAC5D,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE;AACnB,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE,OAAO,IAAI,CAAC;AACjC;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAC7F,EAAE,IAAI,KAAK,GAAG,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AAGrE;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;AACjB;AACA,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAC5D,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAClE,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B,EAAE,GAAG;AACL,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACtE,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAC5E,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACtE,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,QAAQ,GAAG;AACrC,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAClE,EAAE,OAAO,EAAE,CAAC;AACZ,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,IAAI,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC5C,EAAE,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;AAChE,EAAE,IAAI,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AAC3B,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B,EAAE,GAAG;AACL,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;AAC/B,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC3C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC7E,IAAI,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;AACpC,IAAI;AACJ;AACA,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;AACjC,IAAI,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC7C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC/E,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC;AACtC,IAAI;AACJ;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;AAC/B,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC3C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC7E,IAAI,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;AACpC,IAAI;AACJ,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,QAAQ,GAAG;AACrC,EAAE,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AACxC,EAAE,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC1E,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;AAC9B,EAAE;AACF;AACA,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE;AAC9C,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC;AAClB;AACA;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,OAAO,KAAK,KAAK,KAAK,CAAC,KAAK,GAAG,KAAK,IAAI,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,EAAE;AAC/D;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,GAAG,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,GAAG,EAAE;AAC9C,IAAI,OAAO,MAAM,CAAC;AAClB,IAAI;AACJ;AACA,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK;AACpD,GAAG,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC,CAAC;AACpF;AACA,EAAE,MAAM,UAAU,GAAG,KAAK,CAAC;AAC3B,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,IAAI,KAAK,CAAC,KAAK,KAAK,UAAU,KAAK,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,EAAE;AACvE,IAAI,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;AAC1B,IAAI;AACJ;AACA,GAAG,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,GAAG,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC;AAC7D,GAAG,IAAI,WAAW,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG;AACvD,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;AACjF;AACA,GAAG,MAAM,UAAU,GAAG,UAAU,KAAK,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;AACrE,GAAG,MAAM,QAAQ,GAAG,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;AAChG;AACA,GAAG,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;AACvD;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE;AAC3D,IAAI,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;AAC1B,IAAI;AACJ;AACA,GAAG,IAAI,WAAW,EAAE;AACpB,IAAI,MAAM;AACV,IAAI;AACJ;AACA,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA;AACA,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE;AAClB,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;AAC7B,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AACzB,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC3C;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,MAAM,CAAC,KAAK,EAAE;AACf,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,OAAO;AAGvD;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,iBAAiB,CAAC;AACrC,EAAE,MAAM,aAAa,GAAG,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC;AAC1C;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACpE;AACA,GAAG,KAAK,GAAG,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7E,GAAG;AACH,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE;AAC3B,EAAE,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;AAC5C;AACA,GAAG,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC;AAChD,GAAG,MAAM,IAAI,KAAK;AAClB,IAAI,CAAC,mDAAmD,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;AACzG,IAAI,CAAC;AACL,GAAG;AACH;AACA,EAAE,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACtC;AACA,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;AAC5B,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC;AACjC,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;AACtC;AACA,EAAE,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;AAC1D;AACA,EAAE,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;AAEjC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AACvB;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,GAAG,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;AAC3B,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AAC1B,EAAE;AACF;AACA,CAAC,OAAO,GAAG;AACX,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,GAAG;AACL,GAAG;AACH,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE;AAC7C,KAAK,KAAK,CAAC,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;AAClD,KAAK,KAAK,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;AAC9C;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,IAAI,GAAG;AACjC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,GAAG;AACV,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AACjB,EAAE,GAAG;AACL,GAAG,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;AAC5E,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,IAAI,GAAG;AACjC,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA,CAAC,SAAS,GAAG;AACb,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAC/B,EAAE;AACF;AACA,CAAC,IAAI,CAAC,QAAQ,EAAE;AAChB,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,EAAE;AACF;AACA,CAAC,cAAc,CAAC,QAAQ,EAAE;AAC1B,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B;AACA,EAAE,GAAG;AACL,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB,GAAG,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;AACrC;AACA;AACA,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,EAAE;AAC1B,IAAI,IAAI,IAAI,CAAC,SAAS,KAAK,KAAK,EAAE;AAClC,KAAK,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;AACjC,KAAK;AACL;AACA,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAClC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAChD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAC5C,IAAI;AACJ;AACA,GAAG,IAAI,OAAO,EAAE,OAAO,IAAI,CAAC;AAC5B,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC;AAC1B,GAAG,QAAQ,KAAK,EAAE;AAClB;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,OAAO,CAAC,QAAQ,EAAE;AACnB,EAAE,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAChC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF,CAAC,gBAAgB,CAAC,QAAQ,EAAE;AAC5B,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AACzD;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B;AACA,EAAE,GAAG;AACL,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB,GAAG,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;AACvC;AACA,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,EAAE;AAC1B;AACA,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;AAC9D;AACA,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAClC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAChD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAC5C,IAAI;AACJ;AACA,GAAG,IAAI,OAAO,EAAE,OAAO,IAAI,CAAC;AAC5B,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG,QAAQ,KAAK,EAAE;AAClB;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,SAAS,CAAC,QAAQ,EAAE;AACrB,EAAE,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;AAClC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,UAAU,GAAG;AACd,EAAE,OAAO,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE,CAAC;AAC3C,EAAE;AACF;AACA,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,EAAE;AAC1C,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE;AACtC,GAAG,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACxC,IAAI,OAAO,WAAW,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK;AAC1D;AACA,KAAK,IAAI,CAAC,KAAK,GAAG,EAAE,OAAO,GAAG,CAAC;AAC/B,KAAK,IAAI,CAAC,KAAK,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AACpC,KAAK,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC;AACpB,KAAK,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9C,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACpB,KAAK,CAAC,CAAC;AACP,IAAI,MAAM;AACV,IAAI,OAAO,WAAW,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;AACjE,IAAI;AACJ,GAAG;AACH,EAAE,SAAS,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE;AAC7B,GAAG,IAAI,KAAK,CAAC;AACb,GAAG,MAAM,OAAO,GAAG,EAAE,CAAC;AACtB,GAAG,QAAQ,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;AAClC,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxB,IAAI;AACJ,GAAG,OAAO,OAAO,CAAC;AAClB,GAAG;AACH,EAAE,IAAI,WAAW,CAAC,MAAM,EAAE;AAC1B,GAAG,MAAM,OAAO,GAAG,QAAQ,CAAC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AACxD,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,KAAK;AAC9B,IAAI,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI;AAC3B,KAAK,IAAI,CAAC,SAAS;AACnB,MAAM,KAAK,CAAC,KAAK;AACjB,MAAM,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;AACnC,MAAM,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC;AAC1C,MAAM,CAAC;AACP,IAAI,CAAC,CAAC;AACN,GAAG,MAAM;AACT,GAAG,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AAClD,GAAG,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI;AACnC,IAAI,IAAI,CAAC,SAAS;AAClB,KAAK,KAAK,CAAC,KAAK;AAChB,KAAK,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;AAClC,KAAK,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC;AACzC,KAAK,CAAC;AACN,GAAG;AACH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE;AACrC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;AAC5B,EAAE,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACzC;AACA,EAAE,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;AACpB,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAC7D,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,EAAE;AACnC,EAAE,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACvC,GAAG,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACxD,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACvD,EAAE;AACF;AACA,CAAC,iBAAiB,CAAC,MAAM,EAAE,WAAW,EAAE;AACxC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;AAC5B,EAAE,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;AACrC,EAAE;AACF,GAAG,IAAI,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC;AACvC,GAAG,KAAK,KAAK,CAAC,CAAC;AACf,GAAG,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,GAAG,YAAY,CAAC;AACzD,IAAI;AACJ,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,YAAY,EAAE,WAAW,CAAC,CAAC;AAC5D,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,UAAU,CAAC,WAAW,EAAE,WAAW,EAAE;AACtC,EAAE,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACvC,GAAG,OAAO,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AAC3D,GAAG;AACH;AACA,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE;AAC3B,GAAG,MAAM,IAAI,SAAS;AACtB,IAAI,2EAA2E;AAC/E,IAAI,CAAC;AACL,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACvD,EAAE;AACF;;ACz1BA,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD;AACe,MAAM,MAAM,CAAC;AAC5B,CAAC,WAAW,CAAC,OAAO,GAAG,EAAE,EAAE;AAC3B,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC;AACnC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;AAC9E,EAAE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;AACpB,EAAE,IAAI,CAAC,aAAa,GAAG,EAAE,CAAC;AAC1B,EAAE,IAAI,CAAC,2BAA2B,GAAG,EAAE,CAAC;AACxC,EAAE;AACF;AACA,CAAC,SAAS,CAAC,MAAM,EAAE;AACnB,EAAE,IAAI,MAAM,YAAY,WAAW,EAAE;AACrC,GAAG,OAAO,IAAI,CAAC,SAAS,CAAC;AACzB,IAAI,OAAO,EAAE,MAAM;AACnB,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ;AAC7B,IAAI,SAAS,EAAE,IAAI,CAAC,SAAS;AAC7B,IAAI,CAAC,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;AAC5C,GAAG,MAAM,IAAI,KAAK;AAClB,IAAI,sIAAsI;AAC1I,IAAI,CAAC;AACL,GAAG;AACH;AACA,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,uBAAuB,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACvF,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACjF,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE;AACtC;AACA,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACrC,GAAG;AACH;AACA,EAAE,IAAI,MAAM,CAAC,QAAQ,EAAE;AACvB,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,2BAA2B,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE;AAC5E,IAAI,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;AAClF,IAAI,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC7F,IAAI,MAAM;AACV,IAAI,MAAM,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC/F,IAAI,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,KAAK,YAAY,CAAC,OAAO,EAAE;AAC1D,KAAK,MAAM,IAAI,KAAK,CAAC,CAAC,+BAA+B,EAAE,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC;AAC/F,KAAK;AACL,IAAI;AACJ,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE;AACtB,EAAE,IAAI,CAAC,SAAS,CAAC;AACjB,GAAG,OAAO,EAAE,IAAI,WAAW,CAAC,GAAG,CAAC;AAChC,GAAG,SAAS,EAAE,CAAC,OAAO,IAAI,OAAO,CAAC,SAAS,KAAK,EAAE;AAClD,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC;AAC5B,GAAG,KAAK,EAAE,IAAI,CAAC,KAAK;AACpB,GAAG,SAAS,EAAE,IAAI,CAAC,SAAS;AAC5B,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACnC,GAAG,MAAM,CAAC,SAAS,CAAC;AACpB,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ;AAC7B,IAAI,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE;AACnC,IAAI,SAAS,EAAE,MAAM,CAAC,SAAS;AAC/B,IAAI,CAAC,CAAC;AACN,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA,CAAC,kBAAkB,CAAC,OAAO,GAAG,EAAE,EAAE;AAClC,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;AACnB,EAAE,IAAI,mBAAmB,GAAG,SAAS,CAAC;AACtC,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACnC,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,KAAK;AAC7D,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAChD,IAAI,CAAC,CAAC;AACN,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;AAClB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;AACtC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE;AACd,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AACrC,IAAI;AACJ;AACA,GAAG,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;AAChG,GAAG,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC;AACtC,GAAG,MAAM,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACnD;AACA,GAAG,IAAI,WAAW,CAAC,KAAK,EAAE;AAC1B,IAAI,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AACxC,IAAI;AACJ;AACA,GAAG,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,KAAK;AAC9C,IAAI,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACpC;AACA,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1D;AACA,IAAI,IAAI,MAAM,CAAC,QAAQ,EAAE;AACzB,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;AACvB,MAAM,QAAQ,CAAC,OAAO;AACtB,OAAO,WAAW;AAClB,OAAO,KAAK,CAAC,OAAO;AACpB,OAAO,GAAG;AACV,OAAO,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC3D,OAAO,CAAC;AACR,MAAM,MAAM;AACZ,MAAM,QAAQ,CAAC,gBAAgB;AAC/B,OAAO,WAAW;AAClB,OAAO,KAAK;AACZ,OAAO,WAAW,CAAC,QAAQ;AAC3B,OAAO,GAAG;AACV,OAAO,WAAW,CAAC,kBAAkB;AACrC,OAAO,CAAC;AACR,MAAM;AACN,KAAK,MAAM;AACX,KAAK,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACrC,KAAK;AACL;AACA,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1D,IAAI,CAAC,CAAC;AACN;AACA,GAAG,IAAI,WAAW,CAAC,KAAK,EAAE;AAC1B,IAAI,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AACxC,IAAI;AACJ;AACA,GAAG,IAAI,MAAM,CAAC,UAAU,IAAI,WAAW,KAAK,CAAC,CAAC,EAAE;AAChD,IAAI,IAAI,mBAAmB,KAAK,SAAS,EAAE;AAC3C,KAAK,mBAAmB,GAAG,EAAE,CAAC;AAC9B,KAAK;AACL,IAAI,mBAAmB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC1C,IAAI;AACJ,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO;AACT,GAAG,IAAI,EAAE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,SAAS;AACrE,GAAG,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK;AAC/C,IAAI,OAAO,OAAO,CAAC,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC3F,IAAI,CAAC;AACL,GAAG,cAAc,EAAE,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK;AACtD,IAAI,OAAO,OAAO,CAAC,cAAc,GAAG,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;AAC1D,IAAI,CAAC;AACL,GAAG,KAAK;AACR,GAAG,QAAQ,EAAE,QAAQ,CAAC,GAAG;AACzB,GAAG,mBAAmB;AACtB,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AACzD,EAAE;AACF;AACA,CAAC,eAAe,GAAG;AACnB,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAChC;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACnC,GAAG,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,mBAAmB,EAAE,CAAC;AAC1D;AACA,GAAG,IAAI,SAAS,KAAK,IAAI,EAAE,OAAO;AAClC;AACA,GAAG,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,kBAAkB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AACzE,GAAG,kBAAkB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AACtC,GAAG,CAAC,CAAC;AACL;AACA,EAAE;AACF,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK;AAClD,IAAI,OAAO,kBAAkB,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC,CAAC,CAAC,CAAC;AACzD,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;AAChB,IAAI;AACJ,EAAE;AACF;AACA,CAAC,MAAM,CAAC,SAAS,EAAE;AACnB,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE;AACzB,GAAG,SAAS,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;AACtC,GAAG;AACH;AACA,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC;AACpC;AACA,EAAE,IAAI,eAAe,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;AACrE;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;AACtC,GAAG,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACxF,GAAG,MAAM,WAAW,GAAG,eAAe,KAAK,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9E;AACA,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE;AACpC,IAAI,OAAO,EAAE,MAAM,CAAC,qBAAqB;AACzC,IAAI,WAAW;AACf,IAAI,CAAC,CAAC;AACN;AACA,GAAG,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC;AACxD,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;AAClB,GAAG,IAAI,CAAC,KAAK;AACb,IAAI,SAAS;AACb,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK;AACrD,KAAK,OAAO,KAAK,GAAG,CAAC,GAAG,SAAS,GAAG,KAAK,GAAG,KAAK,CAAC;AAClD,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,GAAG,EAAE;AACd,EAAE,IAAI,CAAC,KAAK,GAAG,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AAChC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO;AAC3B,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;AACvB,IAAI,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACzF,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,EAAE,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;AACrE;AACA,IAAI,OAAO,GAAG,CAAC;AACf,IAAI,CAAC;AACL,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;AACb;AACA,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;AAC3B,EAAE;AACF;AACA,CAAC,OAAO,GAAG;AACX,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,KAAK,CAAC;AAC3D,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,OAAO,KAAK,CAAC;AAC7E,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,GAAG;AACV,EAAE,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM;AAC5B,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE;AACvD,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM;AACpB,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,SAAS,GAAG;AACb,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAC/B,EAAE;AACF;AACA,CAAC,IAAI,CAAC,QAAQ,EAAE;AAChB,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,EAAE;AACF;AACA,CAAC,SAAS,CAAC,QAAQ,EAAE;AACrB,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AACzD,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C;AACA,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;AACnB,GAAG,IAAI,MAAM,CAAC;AACd,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AACb;AACA,GAAG,GAAG;AACN,IAAI,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC/B,IAAI,IAAI,CAAC,MAAM,EAAE;AACjB,KAAK,MAAM;AACX,KAAK;AACL,IAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;AACxD,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,QAAQ,EAAE;AACnB,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;AACA,EAAE,IAAI,MAAM,CAAC;AACb,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAClC;AACA,EAAE,GAAG;AACL,GAAG,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC9B,GAAG,IAAI,CAAC,MAAM,EAAE;AAChB,IAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5C,IAAI,MAAM;AACV,IAAI;AACJ,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;AACrD;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;;ACpSA,WAAW,CAAC,MAAM,GAAG,MAAM,CAAC;AAC5B,WAAW,CAAC,SAAS,GAAG,SAAS,CAAC;AAClC,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC;;;;"} \ No newline at end of file diff --git a/web/node_modules/magic-string/dist/magic-string.es.d.mts b/web/node_modules/magic-string/dist/magic-string.es.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..06b1a17c468950c43d3a316a825848bb4b0a9be3 --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.es.d.mts @@ -0,0 +1,268 @@ +export interface BundleOptions { + intro?: string; + separator?: string; +} + +export interface SourceMapOptions { + /** + * Whether the mapping should be high-resolution. + * Hi-res mappings map every single character, meaning (for example) your devtools will always + * be able to pinpoint the exact location of function calls and so on. + * With lo-res mappings, devtools may only be able to identify the correct + * line - but they're quicker to generate and less bulky. + * You can also set `"boundary"` to generate a semi-hi-res mappings segmented per word boundary + * instead of per character, suitable for string semantics that are separated by words. + * If sourcemap locations have been specified with s.addSourceMapLocation(), they will be used here. + */ + hires?: boolean | 'boundary'; + /** + * The filename where you plan to write the sourcemap. + */ + file?: string; + /** + * The filename of the file containing the original source. + */ + source?: string; + /** + * Whether to include the original content in the map's sourcesContent array. + */ + includeContent?: boolean; +} + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; + +export interface DecodedSourceMap { + file: string; + sources: string[]; + sourcesContent?: string[]; + names: string[]; + mappings: SourceMapSegment[][]; + x_google_ignoreList?: number[]; +} + +export class SourceMap { + constructor(properties: DecodedSourceMap); + + version: number; + file: string; + sources: string[]; + sourcesContent?: string[]; + names: string[]; + mappings: string; + x_google_ignoreList?: number[]; + + /** + * Returns the equivalent of `JSON.stringify(map)` + */ + toString(): string; + /** + * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing: + * `generateMap(options?: SourceMapOptions): SourceMap;` + */ + toUrl(): string; +} + +export class Bundle { + constructor(options?: BundleOptions); + /** + * Adds the specified source to the bundle, which can either be a `MagicString` object directly, + * or an options object that holds a magic string `content` property and optionally provides + * a `filename` for the source within the bundle, as well as an optional `ignoreList` hint + * (which defaults to `false`). The `filename` is used when constructing the source map for the + * bundle, to identify this `source` in the source map's `sources` field. The `ignoreList` hint + * is used to populate the `x_google_ignoreList` extension field in the source map, which is a + * mechanism for tools to signal to debuggers that certain sources should be ignored by default + * (depending on user preferences). + */ + addSource(source: MagicString | { filename?: string, content: MagicString, ignoreList?: boolean }): Bundle; + append(str: string, options?: BundleOptions): Bundle; + clone(): Bundle; + generateMap(options?: SourceMapOptions): Omit & { sourcesContent: Array }; + generateDecodedMap(options?: SourceMapOptions): Omit & { sourcesContent: Array }; + getIndentString(): string; + indent(indentStr?: string): Bundle; + indentExclusionRanges: ExclusionRange | Array; + prepend(str: string): Bundle; + toString(): string; + trimLines(): Bundle; + trim(charType?: string): Bundle; + trimStart(charType?: string): Bundle; + trimEnd(charType?: string): Bundle; + isEmpty(): boolean; + length(): number; +} + +export type ExclusionRange = [ number, number ]; + +export interface MagicStringOptions { + filename?: string, + indentExclusionRanges?: ExclusionRange | Array; +} + +export interface IndentOptions { + exclude?: ExclusionRange | Array; + indentStart?: boolean; +} + +export interface OverwriteOptions { + storeName?: boolean; + contentOnly?: boolean; +} + +export interface UpdateOptions { + storeName?: boolean; + overwrite?: boolean; +} + +export default class MagicString { + constructor(str: string, options?: MagicStringOptions); + /** + * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false. + */ + addSourcemapLocation(char: number): void; + /** + * Appends the specified content to the end of the string. + */ + append(content: string): MagicString; + /** + * Appends the specified content at the index in the original string. + * If a range *ending* with index is subsequently moved, the insert will be moved with it. + * See also `s.prependLeft(...)`. + */ + appendLeft(index: number, content: string): MagicString; + /** + * Appends the specified content at the index in the original string. + * If a range *starting* with index is subsequently moved, the insert will be moved with it. + * See also `s.prependRight(...)`. + */ + appendRight(index: number, content: string): MagicString; + /** + * Does what you'd expect. + */ + clone(): MagicString; + /** + * Generates a version 3 sourcemap. + */ + generateMap(options?: SourceMapOptions): SourceMap; + /** + * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. + * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. + */ + generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap; + getIndentString(): string; + + /** + * Prefixes each line of the string with prefix. + * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. + */ + indent(options?: IndentOptions): MagicString; + /** + * Prefixes each line of the string with prefix. + * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. + * + * The options argument can have an exclude property, which is an array of [start, end] character ranges. + * These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. + */ + indent(indentStr?: string, options?: IndentOptions): MagicString; + indentExclusionRanges: ExclusionRange | Array; + + /** + * Moves the characters from `start and `end` to `index`. + */ + move(start: number, end: number, index: number): MagicString; + /** + * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in + * that range. The same restrictions as `s.remove()` apply. + * + * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored + * for later inclusion in a sourcemap's names array — and a contentOnly property which determines whether only + * the content is overwritten, or anything that was appended/prepended to the range as well. + * + * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content. + */ + overwrite(start: number, end: number, content: string, options?: boolean | OverwriteOptions): MagicString; + /** + * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. + * + * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored + * for later inclusion in a sourcemap's names array — and an overwrite property which determines whether only + * the content is overwritten, or anything that was appended/prepended to the range as well. + */ + update(start: number, end: number, content: string, options?: boolean | UpdateOptions): MagicString; + /** + * Prepends the string with the specified content. + */ + prepend(content: string): MagicString; + /** + * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index + */ + prependLeft(index: number, content: string): MagicString; + /** + * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` + */ + prependRight(index: number, content: string): MagicString; + /** + * Removes the characters from `start` to `end` (of the original string, **not** the generated string). + * Removing the same content twice, or making removals that partially overlap, will cause an error. + */ + remove(start: number, end: number): MagicString; + /** + * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string). + */ + reset(start: number, end: number): MagicString; + /** + * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. + * Throws error if the indices are for characters that were already removed. + */ + slice(start: number, end: number): string; + /** + * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. + */ + snip(start: number, end: number): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. + */ + trim(charType?: string): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. + */ + trimStart(charType?: string): MagicString; + /** + * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. + */ + trimEnd(charType?: string): MagicString; + /** + * Removes empty lines from the start and end. + */ + trimLines(): MagicString; + /** + * String replacement with RegExp or string. + */ + replace(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): MagicString; + /** + * Same as `s.replace`, but replace all matched strings instead of just one. + */ + replaceAll(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): MagicString; + + lastChar(): string; + lastLine(): string; + /** + * Returns true if the resulting source is empty (disregarding white space). + */ + isEmpty(): boolean; + length(): number; + + /** + * Indicates if the string has been changed. + */ + hasChanged(): boolean; + + original: string; + /** + * Returns the generated string. + */ + toString(): string; +} diff --git a/web/node_modules/magic-string/dist/magic-string.es.mjs b/web/node_modules/magic-string/dist/magic-string.es.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f14a05a0f3b86ff1364bfd61c352b5ebaaf90481 --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.es.mjs @@ -0,0 +1,1528 @@ +import { encode } from '@jridgewell/sourcemap-codec'; + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + reset() { + this.intro = ''; + this.outro = ''; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa = /*#__PURE__*/ getBtoa(); + +class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + } +} + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + reset(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.reset(); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +const hasOwnProp = Object.prototype.hasOwnProperty; + +class Bundle { + constructor(options = {}) { + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; + } + + addSource(source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`', + ); + } + + ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => { + if (!hasOwnProp.call(source, option)) source[option] = source.content[option]; + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(`Illegal source: same filename (${source.filename}), different contents`); + } + } + } + + this.sources.push(source); + return this; + } + + append(str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; + } + + clone() { + const bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach((source) => { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; + } + + generateDecodedMap(options = {}) { + const names = []; + let x_google_ignoreList = undefined; + this.sources.forEach((source) => { + Object.keys(source.content.storedNames).forEach((name) => { + if (!~names.indexOf(name)) names.push(name); + }); + }); + + const mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach((source, i) => { + if (i > 0) { + mappings.advance(this.separator); + } + + const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1; + const magicString = source.content; + const locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations, + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + + if (source.ignoreList && sourceIndex !== -1) { + if (x_google_ignoreList === undefined) { + x_google_ignoreList = []; + } + x_google_ignoreList.push(sourceIndex); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: this.uniqueSources.map((source) => { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map((source) => { + return options.includeContent ? source.content : null; + }), + names, + mappings: mappings.raw, + x_google_ignoreList, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + getIndentString() { + const indentStringCounts = {}; + + this.sources.forEach((source) => { + const indentStr = source.content._getRawIndentString(); + + if (indentStr === null) return; + + if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0; + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort((a, b) => { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); + } + + indent(indentStr) { + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') return this; // noop + + let trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, (match, index) => { + return index > 0 ? indentStr + match : match; + }); + } + + return this; + } + + prepend(str) { + this.intro = str + this.intro; + return this; + } + + toString() { + const body = this.sources + .map((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; + } + + isEmpty() { + if (this.intro.length && this.intro.trim()) return false; + if (this.sources.some((source) => !source.content.isEmpty())) return false; + return true; + } + + length() { + return this.sources.reduce( + (length, source) => length + source.content.length(), + this.intro.length, + ); + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimStart(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + let source; + let i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; + } + + trimEnd(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + let source; + let i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; + } +} + +export { Bundle, SourceMap, MagicString as default }; +//# sourceMappingURL=magic-string.es.mjs.map diff --git a/web/node_modules/magic-string/dist/magic-string.es.mjs.map b/web/node_modules/magic-string/dist/magic-string.es.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f2b12279e75079739a911d9ca62a7931051b7954 --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.es.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"magic-string.es.mjs","sources":["../src/BitSet.js","../src/Chunk.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + '' \n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from '@jridgewell/sourcemap-codec';\n\nfunction getBtoa() {\n\tif (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {\n\t\treturn (str) => globalThis.btoa(unescape(encodeURIComponent(str)));\n\t} else if (typeof Buffer === 'function') {\n\t\treturn (str) => Buffer.from(str, 'utf-8').toString('base64');\n\t} else {\n\t\treturn () => {\n\t\t\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n\t\t};\n\t}\n}\n\nconst btoa = /*#__PURE__*/ getBtoa();\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t\tif (typeof properties.x_google_ignoreList !== 'undefined') {\n\t\t\tthis.x_google_ignoreList = properties.x_google_ignoreList;\n\t\t}\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","const wordRegex = /\\w/;\n\nexport default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tlet contentLineEnd = content.indexOf('\\n', 0);\n\t\t\tlet previousContentLineEnd = -1;\n\t\t\twhile (contentLineEnd >= 0) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\t\tif (nameIndex >= 0) {\n\t\t\t\t\tsegment.push(nameIndex);\n\t\t\t\t}\n\t\t\t\tthis.rawSegments.push(segment);\n\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\n\t\t\t\tpreviousContentLineEnd = contentLineEnd;\n\t\t\t\tcontentLineEnd = content.indexOf('\\n', contentLineEnd + 1);\n\t\t\t}\n\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\n\t\t\tthis.advance(content.slice(previousContentLineEnd + 1));\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t\tthis.advance(content);\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\t\t// when iterating each char, check if it's in a word boundary\n\t\tlet charInHiresBoundary = false;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\n\t\t\t\tif (this.hires === 'boundary') {\n\t\t\t\t\t// in hires \"boundary\", group segments per word boundary than per char\n\t\t\t\t\tif (wordRegex.test(original[originalCharIndex])) {\n\t\t\t\t\t\t// for first char in the boundary found, start the boundary by pushing a segment\n\t\t\t\t\t\tif (!charInHiresBoundary) {\n\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\tcharInHiresBoundary = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// for non-word char, end the boundary by pushing a segment\n\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\tcharInHiresBoundary = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t} else {\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: undefined },\n\t\t\tignoreList: { writable: true, value: options.ignoreList },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: [\n\t\t\t\toptions.source ? getRelativePath(options.file || '', options.source) : options.file || '',\n\t\t\t],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : undefined,\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\t_ensureindentStr() {\n\t\tif (this.indentStr === undefined) {\n\t\t\tthis.indentStr = guessIndent(this.original);\n\t\t}\n\t}\n\n\t_getRawIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr;\n\t}\n\n\tgetIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tif (indentStr === undefined) {\n\t\t\tthis._ensureindentStr();\n\t\t\tindentStr = this.indentStr || '\\t';\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\toptions = options || {};\n\t\treturn this.update(start, end, content, { ...options, overwrite: !options.contentOnly });\n\t}\n\n\tupdate(start, end, content, options) {\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',\n\t\t\t\t); // eslint-disable-line no-console\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst overwrite = options !== undefined ? options.overwrite : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, {\n\t\t\t\twritable: true,\n\t\t\t\tvalue: true,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, !overwrite);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\treset(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('reset');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.reset();\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('reset');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`,\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n\n\thasChanged() {\n\t\treturn this.original !== this.toString();\n\t}\n\n\t_replaceRegexp(searchValue, replacement) {\n\t\tfunction getReplacement(match, str) {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treturn replacement.replace(/\\$(\\$|&|\\d+)/g, (_, i) => {\n\t\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter\n\t\t\t\t\tif (i === '$') return '$';\n\t\t\t\t\tif (i === '&') return match[0];\n\t\t\t\t\tconst num = +i;\n\t\t\t\t\tif (num < match.length) return match[+i];\n\t\t\t\t\treturn `$${i}`;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\treturn replacement(...match, match.index, str, match.groups);\n\t\t\t}\n\t\t}\n\t\tfunction matchAll(re, str) {\n\t\t\tlet match;\n\t\t\tconst matches = [];\n\t\t\twhile ((match = re.exec(str))) {\n\t\t\t\tmatches.push(match);\n\t\t\t}\n\t\t\treturn matches;\n\t\t}\n\t\tif (searchValue.global) {\n\t\t\tconst matches = matchAll(searchValue, this.original);\n\t\t\tmatches.forEach((match) => {\n\t\t\t\tif (match.index != null)\n\t\t\t\t\tthis.overwrite(\n\t\t\t\t\t\tmatch.index,\n\t\t\t\t\t\tmatch.index + match[0].length,\n\t\t\t\t\t\tgetReplacement(match, this.original),\n\t\t\t\t\t);\n\t\t\t});\n\t\t} else {\n\t\t\tconst match = this.original.match(searchValue);\n\t\t\tif (match && match.index != null)\n\t\t\t\tthis.overwrite(\n\t\t\t\t\tmatch.index,\n\t\t\t\t\tmatch.index + match[0].length,\n\t\t\t\t\tgetReplacement(match, this.original),\n\t\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\t_replaceString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst index = original.indexOf(string);\n\n\t\tif (index !== -1) {\n\t\t\tthis.overwrite(index, index + string.length, replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplace(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceString(searchValue, replacement);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n\n\t_replaceAllString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst stringLength = string.length;\n\t\tfor (\n\t\t\tlet index = original.indexOf(string);\n\t\t\tindex !== -1;\n\t\t\tindex = original.indexOf(string, index + stringLength)\n\t\t) {\n\t\t\tthis.overwrite(index, index + stringLength, replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplaceAll(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceAllString(searchValue, replacement);\n\t\t}\n\n\t\tif (!searchValue.global) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'MagicString.prototype.replaceAll called with a non-global RegExp argument',\n\t\t\t);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tlet x_google_ignoreList = undefined;\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\n\t\t\tif (source.ignoreList && sourceIndex !== -1) {\n\t\t\t\tif (x_google_ignoreList === undefined) {\n\t\t\t\t\tx_google_ignoreList = [];\n\t\t\t\t}\n\t\t\t\tx_google_ignoreList.push(sourceIndex);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content._getRawIndentString();\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length,\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\n}\n"],"names":[],"mappings":";;AAAe,MAAM,MAAM,CAAC;AAC5B,CAAC,WAAW,CAAC,GAAG,EAAE;AAClB,EAAE,IAAI,CAAC,IAAI,GAAG,GAAG,YAAY,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC;AAC5D,EAAE;AACF;AACA,CAAC,GAAG,CAAC,CAAC,EAAE;AACR,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;AACrC,EAAE;AACF;AACA,CAAC,GAAG,CAAC,CAAC,EAAE;AACR,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;AACjD,EAAE;AACF;;ACZe,MAAM,KAAK,CAAC;AAC3B,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE;AAClC,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACrB,EAAE,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;AACjB,EAAE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC1B;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;AACzB,EAAE,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AACtB;AACA,EAMS;AACT,GAAG,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACxB,GAAG,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACpB,GAAG;AACH,EAAE;AACF;AACA,CAAC,UAAU,CAAC,OAAO,EAAE;AACrB,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACxB,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;AACpC,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC3B,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC3B,EAAE,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;AAC/B,EAAE,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACnC,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAC7B;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,QAAQ,CAAC,KAAK,EAAE;AACjB,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC;AAChD,EAAE;AACF;AACA,CAAC,QAAQ,CAAC,EAAE,EAAE;AACd,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AACnB,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;AACb,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH,EAAE;AACF;AACA,CAAC,YAAY,CAAC,EAAE,EAAE;AAClB,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AACnB,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;AACb,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC;AAC1B,GAAG;AACH,EAAE;AACF;AACA,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE;AACvC,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,WAAW,EAAE;AACpB,GAAG,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AACnB,GAAG,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AACnB,GAAG;AACH,EAAE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;AAC7B;AACA,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;AACrB;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACpC,EAAE;AACF;AACA,CAAC,YAAY,CAAC,OAAO,EAAE;AACvB,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACpC,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;AACnB,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC;AAChC,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;AAC1B,GAAG,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AACvB,GAAG;AACH,EAAE;AACF;AACA,CAAC,KAAK,CAAC,KAAK,EAAE;AACd,EAAE,MAAM,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AACxC;AACA,EAAE,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;AAC5D,EAAE,MAAM,aAAa,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AACxD;AACA,EAAE,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;AACjC;AACA,EAAE,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;AAC7D,EAAE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC9B,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB;AACA,EAAE,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC;AACnB;AACA,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;AAC5B,GAAG,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;AACrB,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,OAAO,GAAG,cAAc,CAAC;AACjC,GAAG;AACH;AACA,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;AAC5B,EAAE,IAAI,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACvD,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC3B,EAAE,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;AACvB;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AAChD,EAAE;AACF;AACA,CAAC,OAAO,CAAC,EAAE,EAAE;AACb,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C;AACA,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;AACtB,GAAG,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE;AACjC,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACtE,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB;AACA,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC9C,KAAK;AACL,IAAI;AACJ,GAAG,OAAO,IAAI,CAAC;AACf,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAClC;AACA,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC3C,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACtC,GAAG;AACH,EAAE;AACF;AACA,CAAC,SAAS,CAAC,EAAE,EAAE;AACf,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C;AACA,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;AACtB,GAAG,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE;AACjC,IAAI,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3D,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB;AACA,KAAK,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAClD,KAAK;AACL,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACnC,IAAI;AACJ,GAAG,OAAO,IAAI,CAAC;AACf,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAClC;AACA,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC3C,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACtC,GAAG;AACH,EAAE;AACF;;ACrLA,SAAS,OAAO,GAAG;AACnB,CAAC,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,UAAU,EAAE;AACjF,EAAE,OAAO,CAAC,GAAG,KAAK,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACrE,EAAE,MAAM,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;AAC1C,EAAE,OAAO,CAAC,GAAG,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAC/D,EAAE,MAAM;AACR,EAAE,OAAO,MAAM;AACf,GAAG,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;AAC9F,GAAG,CAAC;AACJ,EAAE;AACF,CAAC;AACD;AACA,MAAM,IAAI,iBAAiB,OAAO,EAAE,CAAC;AACrC;AACe,MAAM,SAAS,CAAC;AAC/B,CAAC,WAAW,CAAC,UAAU,EAAE;AACzB,EAAE,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC;AAC9B,EAAE,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;AACpC,EAAE,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;AAClD,EAAE,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;AAChC,EAAE,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;AAC9C,EAAE,IAAI,OAAO,UAAU,CAAC,mBAAmB,KAAK,WAAW,EAAE;AAC7D,GAAG,IAAI,CAAC,mBAAmB,GAAG,UAAU,CAAC,mBAAmB,CAAC;AAC7D,GAAG;AACH,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC9B,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,OAAO,6CAA6C,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC/E,EAAE;AACF;;ACpCe,SAAS,WAAW,CAAC,IAAI,EAAE;AAC1C,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC;AACA,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1D,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACjD,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA;AACA;AACA;AACA,CAAC,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;AACrC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA;AACA,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,OAAO,KAAK;AAClD,EAAE,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AACvC,EAAE,EAAE,QAAQ,CAAC,CAAC;AACd;AACA,CAAC,OAAO,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrC;;ACxBe,SAAS,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE;AAClD,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACvC,CAAC,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACnC;AACA,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC;AACjB;AACA,CAAC,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE;AACrC,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC;AACpB,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;AAClB,EAAE;AACF;AACA,CAAC,IAAI,SAAS,CAAC,MAAM,EAAE;AACvB,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC;AAC3B,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAClC,EAAE;AACF;AACA,CAAC,OAAO,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5C;;ACjBA,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;AAC3C;AACe,SAAS,QAAQ,CAAC,KAAK,EAAE;AACxC,CAAC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,iBAAiB,CAAC;AACnD;;ACJe,SAAS,UAAU,CAAC,MAAM,EAAE;AAC3C,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AACxB;AACA,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACzD,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACxB,EAAE,GAAG,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AACrC,EAAE;AACF;AACA,CAAC,OAAO,SAAS,MAAM,CAAC,KAAK,EAAE;AAC/B,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;AACZ,EAAE,IAAI,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC;AAC7B,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE;AAChB,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAC1B,GAAG,IAAI,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,IAAI,CAAC,GAAG,CAAC,CAAC;AACV,IAAI,MAAM;AACV,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,IAAI;AACJ,GAAG;AACH,EAAE,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;AACrB,EAAE,MAAM,MAAM,GAAG,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;AAC3C,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1B,EAAE,CAAC;AACH;;ACxBA,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB;AACe,MAAM,QAAQ,CAAC;AAC9B,CAAC,WAAW,CAAC,KAAK,EAAE;AACpB,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACrB,EAAE,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;AAC7B,EAAE,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AAC/B,EAAE,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;AAChB,EAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,CAAC;AAC3D,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE;AACF;AACA,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE;AAC/C,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;AACtB,GAAG,IAAI,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,GAAG,IAAI,sBAAsB,GAAG,CAAC,CAAC,CAAC;AACnC,GAAG,OAAO,cAAc,IAAI,CAAC,EAAE;AAC/B,IAAI,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AAClF,IAAI,IAAI,SAAS,IAAI,CAAC,EAAE;AACxB,KAAK,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAC7B,KAAK;AACL,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACnC;AACA,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;AAChC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;AAC7D,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AACjC;AACA,IAAI,sBAAsB,GAAG,cAAc,CAAC;AAC5C,IAAI,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,CAAC,CAAC,CAAC;AAC/D,IAAI;AACJ;AACA,GAAG,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AACjF,GAAG,IAAI,SAAS,IAAI,CAAC,EAAE;AACvB,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAC5B,IAAI;AACJ,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAClC;AACA,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,sBAAsB,GAAG,CAAC,CAAC,CAAC,CAAC;AAC3D,GAAG,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE;AAC3B,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACvC,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE;AACF;AACA,CAAC,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,kBAAkB,EAAE;AACzE,EAAE,IAAI,iBAAiB,GAAG,KAAK,CAAC,KAAK,CAAC;AACtC,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AACnB;AACA,EAAE,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAClC;AACA,EAAE,OAAO,iBAAiB,GAAG,KAAK,CAAC,GAAG,EAAE;AACxC,GAAG,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,IAAI,kBAAkB,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE;AACzE,IAAI,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AAClF;AACA,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,UAAU,EAAE;AACnC;AACA,KAAK,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,EAAE;AACtD;AACA,MAAM,IAAI,CAAC,mBAAmB,EAAE;AAChC,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACtC,OAAO,mBAAmB,GAAG,IAAI,CAAC;AAClC,OAAO;AACP,MAAM,MAAM;AACZ;AACA,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACrC,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAClC,MAAM;AACN,KAAK,MAAM;AACX,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,KAAK;AACL,IAAI;AACJ;AACA,GAAG,IAAI,QAAQ,CAAC,iBAAiB,CAAC,KAAK,IAAI,EAAE;AAC7C,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;AAClB,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;AACnB,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;AAChC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;AAC7D,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AACjC,IAAI,KAAK,GAAG,IAAI,CAAC;AACjB,IAAI,MAAM;AACV,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;AACpB,IAAI,IAAI,CAAC,mBAAmB,IAAI,CAAC,CAAC;AAClC,IAAI,KAAK,GAAG,KAAK,CAAC;AAClB,IAAI;AACJ;AACA,GAAG,iBAAiB,IAAI,CAAC,CAAC;AAC1B,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE;AACF;AACA,CAAC,OAAO,CAAC,GAAG,EAAE;AACd,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO;AACnB;AACA,EAAE,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC;AACA,EAAE,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;AACxB,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC9C,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;AAC7B,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;AAC7D,IAAI;AACJ,GAAG,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,mBAAmB,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;AAC7D,EAAE;AACF;;AClGA,MAAM,CAAC,GAAG,IAAI,CAAC;AACf;AACA,MAAM,MAAM,GAAG;AACf,CAAC,UAAU,EAAE,KAAK;AAClB,CAAC,WAAW,EAAE,KAAK;AACnB,CAAC,SAAS,EAAE,KAAK;AACjB,CAAC,CAAC;AACF;AACe,MAAM,WAAW,CAAC;AACjC,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,EAAE,EAAE;AACnC,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AACpD;AACA,EAAE,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE;AAChC,GAAG,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE;AAC9C,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACvC,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACvC,GAAG,UAAU,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;AAC/C,GAAG,SAAS,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;AAC9C,GAAG,iBAAiB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;AACtD,GAAG,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACzC,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AACvC,GAAG,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,EAAE;AACxD,GAAG,qBAAqB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,qBAAqB,EAAE;AAClF,GAAG,kBAAkB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,MAAM,EAAE,EAAE;AAC9D,GAAG,WAAW,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;AAC7C,GAAG,SAAS,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE;AAClD,GAAG,UAAU,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,EAAE;AAC5D,GAAG,CAAC,CAAC;AAKL;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;AAC1B,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;AACpC,EAAE;AACF;AACA,CAAC,oBAAoB,CAAC,IAAI,EAAE;AAC5B,EAAE,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACpC,EAAE;AACF;AACA,CAAC,MAAM,CAAC,OAAO,EAAE;AACjB,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;AACzF;AACA,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACxB,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;AAC5B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AAC7B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACzB,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAC9B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;AACzB,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC7E;AACA,EAAE,IAAI,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC;AACtC,EAAE,IAAI,WAAW,IAAI,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,iBAAiB,GAAG,aAAa,CAAC,KAAK,EAAE,CAAC,CAAC;AAC3F;AACA,EAAE,OAAO,aAAa,EAAE;AACxB,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,WAAW,CAAC;AACnD,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC;AAC/C;AACA,GAAG,MAAM,iBAAiB,GAAG,aAAa,CAAC,IAAI,CAAC;AAChD,GAAG,MAAM,eAAe,GAAG,iBAAiB,IAAI,iBAAiB,CAAC,KAAK,EAAE,CAAC;AAC1E;AACA,GAAG,IAAI,eAAe,EAAE;AACxB,IAAI,WAAW,CAAC,IAAI,GAAG,eAAe,CAAC;AACvC,IAAI,eAAe,CAAC,QAAQ,GAAG,WAAW,CAAC;AAC3C;AACA,IAAI,WAAW,GAAG,eAAe,CAAC;AAClC,IAAI;AACJ;AACA,GAAG,aAAa,GAAG,iBAAiB,CAAC;AACrC,GAAG;AACH;AACA,EAAE,MAAM,CAAC,SAAS,GAAG,WAAW,CAAC;AACjC;AACA,EAAE,IAAI,IAAI,CAAC,qBAAqB,EAAE;AAClC,GAAG,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC;AACrE,GAAG;AACH;AACA,EAAE,MAAM,CAAC,kBAAkB,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;AAClE;AACA,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC5B,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC5B;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA,CAAC,kBAAkB,CAAC,OAAO,EAAE;AAC7B,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA,EAAE,MAAM,WAAW,GAAG,CAAC,CAAC;AACxB,EAAE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC9C,EAAE,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,EAAE,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC3C;AACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;AAClB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,KAAK;AACtC,GAAG,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACnC;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACzD;AACA,GAAG,IAAI,KAAK,CAAC,MAAM,EAAE;AACrB,IAAI,QAAQ,CAAC,OAAO;AACpB,KAAK,WAAW;AAChB,KAAK,KAAK,CAAC,OAAO;AAClB,KAAK,GAAG;AACR,KAAK,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACzD,KAAK,CAAC;AACN,IAAI,MAAM;AACV,IAAI,QAAQ,CAAC,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;AAC/F,IAAI;AACJ;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACzD,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO;AACT,GAAG,IAAI,EAAE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,SAAS;AACrE,GAAG,OAAO,EAAE;AACZ,IAAI,OAAO,CAAC,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;AAC7F,IAAI;AACJ,GAAG,cAAc,EAAE,OAAO,CAAC,cAAc,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,SAAS;AACvE,GAAG,KAAK;AACR,GAAG,QAAQ,EAAE,QAAQ,CAAC,GAAG;AACzB,GAAG,mBAAmB,EAAE,IAAI,CAAC,UAAU,GAAG,CAAC,WAAW,CAAC,GAAG,SAAS;AACnE,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AACzD,EAAE;AACF;AACA,CAAC,gBAAgB,GAAG;AACpB,EAAE,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE;AACpC,GAAG,IAAI,CAAC,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/C,GAAG;AACH,EAAE;AACF;AACA,CAAC,mBAAmB,GAAG;AACvB,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;AAC1B,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC;AACxB,EAAE;AACF;AACA,CAAC,eAAe,GAAG;AACnB,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;AAC1B,EAAE,OAAO,IAAI,CAAC,SAAS,KAAK,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;AACzD,EAAE;AACF;AACA,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,EAAE;AAC5B,EAAE,MAAM,OAAO,GAAG,YAAY,CAAC;AAC/B;AACA,EAAE,IAAI,QAAQ,CAAC,SAAS,CAAC,EAAE;AAC3B,GAAG,OAAO,GAAG,SAAS,CAAC;AACvB,GAAG,SAAS,GAAG,SAAS,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAI,SAAS,KAAK,SAAS,EAAE;AAC/B,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;AAC3B,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;AACtC,GAAG;AACH;AACA,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC;AACpC;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA;AACA,EAAE,MAAM,UAAU,GAAG,EAAE,CAAC;AACxB;AACA,EAAE,IAAI,OAAO,CAAC,OAAO,EAAE;AACvB,GAAG,MAAM,UAAU;AACnB,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;AACjF,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,KAAK;AACrC,IAAI,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;AACzD,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAC1B,KAAK;AACL,IAAI,CAAC,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,yBAAyB,GAAG,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC;AAChE,EAAE,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK;AAC9B,GAAG,IAAI,yBAAyB,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AAChE,GAAG,yBAAyB,GAAG,IAAI,CAAC;AACpC,GAAG,OAAO,KAAK,CAAC;AAChB,GAAG,CAAC;AACJ;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD;AACA,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB;AACA,GAAG,IAAI,KAAK,CAAC,MAAM,EAAE;AACrB,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;AAChC,KAAK,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC9D;AACA,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;AAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC;AACnF,MAAM;AACN,KAAK;AACL,IAAI,MAAM;AACV,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC;AAC5B;AACA,IAAI,OAAO,SAAS,GAAG,GAAG,EAAE;AAC5B,KAAK,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;AACjC,MAAM,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAC5C;AACA,MAAM,IAAI,IAAI,KAAK,IAAI,EAAE;AACzB,OAAO,yBAAyB,GAAG,IAAI,CAAC;AACxC,OAAO,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,yBAAyB,EAAE;AAC7D,OAAO,yBAAyB,GAAG,KAAK,CAAC;AACzC;AACA,OAAO,IAAI,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE;AACtC,QAAQ,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACtC,QAAQ,MAAM;AACd,QAAQ,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC3C,QAAQ,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AAC3B,QAAQ,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AACtC,QAAQ;AACR,OAAO;AACP,MAAM;AACN;AACA,KAAK,SAAS,IAAI,CAAC,CAAC;AACpB,KAAK;AACL,IAAI;AACJ;AACA,GAAG,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,GAAG;AACV,EAAE,MAAM,IAAI,KAAK;AACjB,GAAG,iFAAiF;AACpF,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;AAC5B,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE;AAC1B,GAAG,OAAO,CAAC,IAAI;AACf,IAAI,oFAAoF;AACxF,IAAI,CAAC;AACL,GAAG,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;AAC5B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AACzC,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7B,EAAE,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;AAC3B,GAAG,OAAO,CAAC,IAAI;AACf,IAAI,uFAAuF;AAC3F,IAAI,CAAC;AACL,GAAG,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC;AAC7B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAC3C,EAAE;AACF;AACA,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE;AACzB,EAAE,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AAG/F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC/B;AACA,EAAE,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC;AACjC,EAAE,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC;AAC7B;AACA,EAAE,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACvC,EAAE,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE,OAAO,IAAI,CAAC;AACxD,EAAE,MAAM,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;AAChE;AACA,EAAE,IAAI,OAAO,EAAE,OAAO,CAAC,IAAI,GAAG,QAAQ,CAAC;AACvC,EAAE,IAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC5C;AACA,EAAE,IAAI,OAAO,EAAE,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC;AACpC,EAAE,IAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AACzC;AACA,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;AACnD,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;AAClB,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,QAAQ,CAAC;AACnC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC;AAC9B,GAAG;AACH;AACA,EAAE,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC3B,EAAE,IAAI,CAAC,IAAI,GAAG,QAAQ,IAAI,IAAI,CAAC;AAC/B;AACA,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;AACxC,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;AAGvC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;AACzC,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;AAC3F,EAAE;AACF;AACA,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;AACtC,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,sCAAsC,CAAC,CAAC;AAC/F;AACA,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;AAC1E,EAAE,IAAI,KAAK,KAAK,GAAG;AACnB,GAAG,MAAM,IAAI,KAAK;AAClB,IAAI,+EAA+E;AACnF,IAAI,CAAC;AAGL;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,OAAO,KAAK,IAAI,EAAE;AACxB,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE;AAC1B,IAAI,OAAO,CAAC,IAAI;AAChB,KAAK,+HAA+H;AACpI,KAAK,CAAC;AACN,IAAI,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;AAC5B,IAAI;AACJ;AACA,GAAG,OAAO,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACjC,GAAG;AACH,EAAE,MAAM,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC;AACtE,EAAE,MAAM,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC;AACtE;AACA,EAAE,IAAI,SAAS,EAAE;AACjB,GAAG,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACpD,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE;AACrD,IAAI,QAAQ,EAAE,IAAI;AAClB,IAAI,KAAK,EAAE,IAAI;AACf,IAAI,UAAU,EAAE,IAAI;AACpB,IAAI,CAAC,CAAC;AACN,GAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC/B;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,IAAI,KAAK,GAAG,KAAK,CAAC;AACrB,GAAG,OAAO,KAAK,KAAK,IAAI,EAAE;AAC1B,IAAI,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;AAChD,KAAK,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AAC9D,KAAK;AACL,IAAI,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACvB,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;AAC1B,IAAI;AACJ;AACA,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,CAAC,SAAS,CAAC,CAAC;AAC9C,GAAG,MAAM;AACT;AACA,GAAG,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACvE;AACA;AACA,GAAG,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;AACxB,GAAG,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC5B,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,OAAO,EAAE;AAClB,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;AACzF;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACpC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAC9B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACrC,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE;AAC9B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;AACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC;AACA,EAAE,IAAI,KAAK,EAAE;AACb,GAAG,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;AAC/B,GAAG,MAAM;AACT,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AACrC,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE;AACpB,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE,OAAO,IAAI,CAAC;AACjC;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAC7F,EAAE,IAAI,KAAK,GAAG,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AAGrE;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;AACpB,GAAG,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;AACpB,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAClB;AACA,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAC5D,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE;AACnB,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE,OAAO,IAAI,CAAC;AACjC;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAC7F,EAAE,IAAI,KAAK,GAAG,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AAGrE;AACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAClC;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;AACjB;AACA,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAC5D,GAAG;AAGH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAClE,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B,EAAE,GAAG;AACL,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACtE,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAC5E,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACtE,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,QAAQ,GAAG;AACrC,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAClE,EAAE,OAAO,EAAE,CAAC;AACZ,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,IAAI,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC5C,EAAE,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;AAChE,EAAE,IAAI,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;AAC3B,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B,EAAE,GAAG;AACL,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;AAC/B,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC3C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC7E,IAAI,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;AACpC,IAAI;AACJ;AACA,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;AACjC,IAAI,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC7C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC/E,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC;AACtC,IAAI;AACJ;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;AAC/B,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAC3C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC7E,IAAI,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;AACpC,IAAI;AACJ,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,QAAQ,GAAG;AACrC,EAAE,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AACxC,EAAE,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC1E,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;AAC9B,EAAE;AACF;AACA,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE;AAC9C,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;AACA,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC;AAClB;AACA;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,OAAO,KAAK,KAAK,KAAK,CAAC,KAAK,GAAG,KAAK,IAAI,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,EAAE;AAC/D;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,GAAG,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,GAAG,EAAE;AAC9C,IAAI,OAAO,MAAM,CAAC;AAClB,IAAI;AACJ;AACA,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK;AACpD,GAAG,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC,CAAC;AACpF;AACA,EAAE,MAAM,UAAU,GAAG,KAAK,CAAC;AAC3B,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,IAAI,KAAK,CAAC,KAAK,KAAK,UAAU,KAAK,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,EAAE;AACvE,IAAI,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;AAC1B,IAAI;AACJ;AACA,GAAG,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,GAAG,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC;AAC7D,GAAG,IAAI,WAAW,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG;AACvD,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;AACjF;AACA,GAAG,MAAM,UAAU,GAAG,UAAU,KAAK,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;AACrE,GAAG,MAAM,QAAQ,GAAG,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;AAChG;AACA,GAAG,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;AACvD;AACA,GAAG,IAAI,KAAK,CAAC,KAAK,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE;AAC3D,IAAI,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;AAC1B,IAAI;AACJ;AACA,GAAG,IAAI,WAAW,EAAE;AACpB,IAAI,MAAM;AACV,IAAI;AACJ;AACA,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA;AACA,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE;AAClB,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;AAC7B,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AACzB,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC3C;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,MAAM,CAAC,KAAK,EAAE;AACf,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,OAAO;AAGvD;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,iBAAiB,CAAC;AACrC,EAAE,MAAM,aAAa,GAAG,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC;AAC1C;AACA,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACpE;AACA,GAAG,KAAK,GAAG,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7E,GAAG;AACH,EAAE;AACF;AACA,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE;AAC3B,EAAE,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;AAC5C;AACA,GAAG,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC;AAChD,GAAG,MAAM,IAAI,KAAK;AAClB,IAAI,CAAC,mDAAmD,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;AACzG,IAAI,CAAC;AACL,GAAG;AACH;AACA,EAAE,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACtC;AACA,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;AAC5B,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC;AACjC,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;AACtC;AACA,EAAE,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;AAC1D;AACA,EAAE,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;AAEjC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AACvB;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,OAAO,KAAK,EAAE;AAChB,GAAG,GAAG,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;AAC3B,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AAC1B,EAAE;AACF;AACA,CAAC,OAAO,GAAG;AACX,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,GAAG;AACL,GAAG;AACH,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE;AAC7C,KAAK,KAAK,CAAC,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;AAClD,KAAK,KAAK,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;AAC9C;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,IAAI,GAAG;AACjC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,GAAG;AACV,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AACjB,EAAE,GAAG;AACL,GAAG,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;AAC5E,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,IAAI,GAAG;AACjC,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA,CAAC,SAAS,GAAG;AACb,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAC/B,EAAE;AACF;AACA,CAAC,IAAI,CAAC,QAAQ,EAAE;AAChB,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,EAAE;AACF;AACA,CAAC,cAAc,CAAC,QAAQ,EAAE;AAC1B,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B;AACA,EAAE,GAAG;AACL,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB,GAAG,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;AACrC;AACA;AACA,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,EAAE;AAC1B,IAAI,IAAI,IAAI,CAAC,SAAS,KAAK,KAAK,EAAE;AAClC,KAAK,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;AACjC,KAAK;AACL;AACA,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAClC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAChD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAC5C,IAAI;AACJ;AACA,GAAG,IAAI,OAAO,EAAE,OAAO,IAAI,CAAC;AAC5B,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC;AAC1B,GAAG,QAAQ,KAAK,EAAE;AAClB;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,OAAO,CAAC,QAAQ,EAAE;AACnB,EAAE,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAChC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF,CAAC,gBAAgB,CAAC,QAAQ,EAAE;AAC5B,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AACzD;AACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B;AACA,EAAE,GAAG;AACL,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB,GAAG,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;AACvC;AACA,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,EAAE;AAC1B;AACA,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;AAC9D;AACA,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAClC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAChD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;AAC5C,IAAI;AACJ;AACA,GAAG,IAAI,OAAO,EAAE,OAAO,IAAI,CAAC;AAC5B,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;AACtB,GAAG,QAAQ,KAAK,EAAE;AAClB;AACA,EAAE,OAAO,KAAK,CAAC;AACf,EAAE;AACF;AACA,CAAC,SAAS,CAAC,QAAQ,EAAE;AACrB,EAAE,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;AAClC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,UAAU,GAAG;AACd,EAAE,OAAO,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE,CAAC;AAC3C,EAAE;AACF;AACA,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,EAAE;AAC1C,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE;AACtC,GAAG,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACxC,IAAI,OAAO,WAAW,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK;AAC1D;AACA,KAAK,IAAI,CAAC,KAAK,GAAG,EAAE,OAAO,GAAG,CAAC;AAC/B,KAAK,IAAI,CAAC,KAAK,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AACpC,KAAK,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC;AACpB,KAAK,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9C,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACpB,KAAK,CAAC,CAAC;AACP,IAAI,MAAM;AACV,IAAI,OAAO,WAAW,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;AACjE,IAAI;AACJ,GAAG;AACH,EAAE,SAAS,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE;AAC7B,GAAG,IAAI,KAAK,CAAC;AACb,GAAG,MAAM,OAAO,GAAG,EAAE,CAAC;AACtB,GAAG,QAAQ,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;AAClC,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxB,IAAI;AACJ,GAAG,OAAO,OAAO,CAAC;AAClB,GAAG;AACH,EAAE,IAAI,WAAW,CAAC,MAAM,EAAE;AAC1B,GAAG,MAAM,OAAO,GAAG,QAAQ,CAAC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AACxD,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,KAAK;AAC9B,IAAI,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI;AAC3B,KAAK,IAAI,CAAC,SAAS;AACnB,MAAM,KAAK,CAAC,KAAK;AACjB,MAAM,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;AACnC,MAAM,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC;AAC1C,MAAM,CAAC;AACP,IAAI,CAAC,CAAC;AACN,GAAG,MAAM;AACT,GAAG,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AAClD,GAAG,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI;AACnC,IAAI,IAAI,CAAC,SAAS;AAClB,KAAK,KAAK,CAAC,KAAK;AAChB,KAAK,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;AAClC,KAAK,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC;AACzC,KAAK,CAAC;AACN,GAAG;AACH,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE;AACrC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;AAC5B,EAAE,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACzC;AACA,EAAE,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;AACpB,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAC7D,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,EAAE;AACnC,EAAE,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACvC,GAAG,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACxD,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACvD,EAAE;AACF;AACA,CAAC,iBAAiB,CAAC,MAAM,EAAE,WAAW,EAAE;AACxC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;AAC5B,EAAE,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;AACrC,EAAE;AACF,GAAG,IAAI,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC;AACvC,GAAG,KAAK,KAAK,CAAC,CAAC;AACf,GAAG,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,GAAG,YAAY,CAAC;AACzD,IAAI;AACJ,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,YAAY,EAAE,WAAW,CAAC,CAAC;AAC5D,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,UAAU,CAAC,WAAW,EAAE,WAAW,EAAE;AACtC,EAAE,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACvC,GAAG,OAAO,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AAC3D,GAAG;AACH;AACA,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE;AAC3B,GAAG,MAAM,IAAI,SAAS;AACtB,IAAI,2EAA2E;AAC/E,IAAI,CAAC;AACL,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;AACvD,EAAE;AACF;;ACz1BA,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD;AACe,MAAM,MAAM,CAAC;AAC5B,CAAC,WAAW,CAAC,OAAO,GAAG,EAAE,EAAE;AAC3B,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC;AACnC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;AAC9E,EAAE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;AACpB,EAAE,IAAI,CAAC,aAAa,GAAG,EAAE,CAAC;AAC1B,EAAE,IAAI,CAAC,2BAA2B,GAAG,EAAE,CAAC;AACxC,EAAE;AACF;AACA,CAAC,SAAS,CAAC,MAAM,EAAE;AACnB,EAAE,IAAI,MAAM,YAAY,WAAW,EAAE;AACrC,GAAG,OAAO,IAAI,CAAC,SAAS,CAAC;AACzB,IAAI,OAAO,EAAE,MAAM;AACnB,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ;AAC7B,IAAI,SAAS,EAAE,IAAI,CAAC,SAAS;AAC7B,IAAI,CAAC,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;AAC5C,GAAG,MAAM,IAAI,KAAK;AAClB,IAAI,sIAAsI;AAC1I,IAAI,CAAC;AACL,GAAG;AACH;AACA,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,uBAAuB,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACvF,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACjF,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE;AACtC;AACA,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACrC,GAAG;AACH;AACA,EAAE,IAAI,MAAM,CAAC,QAAQ,EAAE;AACvB,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,2BAA2B,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE;AAC5E,IAAI,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;AAClF,IAAI,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC7F,IAAI,MAAM;AACV,IAAI,MAAM,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC/F,IAAI,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,KAAK,YAAY,CAAC,OAAO,EAAE;AAC1D,KAAK,MAAM,IAAI,KAAK,CAAC,CAAC,+BAA+B,EAAE,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC;AAC/F,KAAK;AACL,IAAI;AACJ,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE;AACtB,EAAE,IAAI,CAAC,SAAS,CAAC;AACjB,GAAG,OAAO,EAAE,IAAI,WAAW,CAAC,GAAG,CAAC;AAChC,GAAG,SAAS,EAAE,CAAC,OAAO,IAAI,OAAO,CAAC,SAAS,KAAK,EAAE;AAClD,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,KAAK,GAAG;AACT,EAAE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC;AAC5B,GAAG,KAAK,EAAE,IAAI,CAAC,KAAK;AACpB,GAAG,SAAS,EAAE,IAAI,CAAC,SAAS;AAC5B,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACnC,GAAG,MAAM,CAAC,SAAS,CAAC;AACpB,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ;AAC7B,IAAI,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE;AACnC,IAAI,SAAS,EAAE,MAAM,CAAC,SAAS;AAC/B,IAAI,CAAC,CAAC;AACN,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,EAAE;AACF;AACA,CAAC,kBAAkB,CAAC,OAAO,GAAG,EAAE,EAAE;AAClC,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;AACnB,EAAE,IAAI,mBAAmB,GAAG,SAAS,CAAC;AACtC,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACnC,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,KAAK;AAC7D,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAChD,IAAI,CAAC,CAAC;AACN,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;AAClB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;AACtC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE;AACd,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AACrC,IAAI;AACJ;AACA,GAAG,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;AAChG,GAAG,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC;AACtC,GAAG,MAAM,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACnD;AACA,GAAG,IAAI,WAAW,CAAC,KAAK,EAAE;AAC1B,IAAI,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AACxC,IAAI;AACJ;AACA,GAAG,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,KAAK;AAC9C,IAAI,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACpC;AACA,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1D;AACA,IAAI,IAAI,MAAM,CAAC,QAAQ,EAAE;AACzB,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;AACvB,MAAM,QAAQ,CAAC,OAAO;AACtB,OAAO,WAAW;AAClB,OAAO,KAAK,CAAC,OAAO;AACpB,OAAO,GAAG;AACV,OAAO,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC3D,OAAO,CAAC;AACR,MAAM,MAAM;AACZ,MAAM,QAAQ,CAAC,gBAAgB;AAC/B,OAAO,WAAW;AAClB,OAAO,KAAK;AACZ,OAAO,WAAW,CAAC,QAAQ;AAC3B,OAAO,GAAG;AACV,OAAO,WAAW,CAAC,kBAAkB;AACrC,OAAO,CAAC;AACR,MAAM;AACN,KAAK,MAAM;AACX,KAAK,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACrC,KAAK;AACL;AACA,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1D,IAAI,CAAC,CAAC;AACN;AACA,GAAG,IAAI,WAAW,CAAC,KAAK,EAAE;AAC1B,IAAI,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AACxC,IAAI;AACJ;AACA,GAAG,IAAI,MAAM,CAAC,UAAU,IAAI,WAAW,KAAK,CAAC,CAAC,EAAE;AAChD,IAAI,IAAI,mBAAmB,KAAK,SAAS,EAAE;AAC3C,KAAK,mBAAmB,GAAG,EAAE,CAAC;AAC9B,KAAK;AACL,IAAI,mBAAmB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC1C,IAAI;AACJ,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO;AACT,GAAG,IAAI,EAAE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,SAAS;AACrE,GAAG,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK;AAC/C,IAAI,OAAO,OAAO,CAAC,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC3F,IAAI,CAAC;AACL,GAAG,cAAc,EAAE,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK;AACtD,IAAI,OAAO,OAAO,CAAC,cAAc,GAAG,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;AAC1D,IAAI,CAAC;AACL,GAAG,KAAK;AACR,GAAG,QAAQ,EAAE,QAAQ,CAAC,GAAG;AACzB,GAAG,mBAAmB;AACtB,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,WAAW,CAAC,OAAO,EAAE;AACtB,EAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AACzD,EAAE;AACF;AACA,CAAC,eAAe,GAAG;AACnB,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAChC;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AACnC,GAAG,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,mBAAmB,EAAE,CAAC;AAC1D;AACA,GAAG,IAAI,SAAS,KAAK,IAAI,EAAE,OAAO;AAClC;AACA,GAAG,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,kBAAkB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AACzE,GAAG,kBAAkB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AACtC,GAAG,CAAC,CAAC;AACL;AACA,EAAE;AACF,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK;AAClD,IAAI,OAAO,kBAAkB,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC,CAAC,CAAC,CAAC;AACzD,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;AAChB,IAAI;AACJ,EAAE;AACF;AACA,CAAC,MAAM,CAAC,SAAS,EAAE;AACnB,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE;AACzB,GAAG,SAAS,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;AACtC,GAAG;AACH;AACA,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC;AACpC;AACA,EAAE,IAAI,eAAe,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;AACrE;AACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;AACtC,GAAG,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACxF,GAAG,MAAM,WAAW,GAAG,eAAe,KAAK,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9E;AACA,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE;AACpC,IAAI,OAAO,EAAE,MAAM,CAAC,qBAAqB;AACzC,IAAI,WAAW;AACf,IAAI,CAAC,CAAC;AACN;AACA,GAAG,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC;AACxD,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;AAClB,GAAG,IAAI,CAAC,KAAK;AACb,IAAI,SAAS;AACb,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK;AACrD,KAAK,OAAO,KAAK,GAAG,CAAC,GAAG,SAAS,GAAG,KAAK,GAAG,KAAK,CAAC;AAClD,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,GAAG,EAAE;AACd,EAAE,IAAI,CAAC,KAAK,GAAG,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AAChC,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,QAAQ,GAAG;AACZ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO;AAC3B,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;AACvB,IAAI,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACzF,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,EAAE,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;AACrE;AACA,IAAI,OAAO,GAAG,CAAC;AACf,IAAI,CAAC;AACL,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;AACb;AACA,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;AAC3B,EAAE;AACF;AACA,CAAC,OAAO,GAAG;AACX,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,KAAK,CAAC;AAC3D,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,OAAO,KAAK,CAAC;AAC7E,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,MAAM,GAAG;AACV,EAAE,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM;AAC5B,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE;AACvD,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM;AACpB,GAAG,CAAC;AACJ,EAAE;AACF;AACA,CAAC,SAAS,GAAG;AACb,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAC/B,EAAE;AACF;AACA,CAAC,IAAI,CAAC,QAAQ,EAAE;AAChB,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,EAAE;AACF;AACA,CAAC,SAAS,CAAC,QAAQ,EAAE;AACrB,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AACzD,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C;AACA,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;AACnB,GAAG,IAAI,MAAM,CAAC;AACd,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AACb;AACA,GAAG,GAAG;AACN,IAAI,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC/B,IAAI,IAAI,CAAC,MAAM,EAAE;AACjB,KAAK,MAAM;AACX,KAAK;AACL,IAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;AACxD,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;AACA,CAAC,OAAO,CAAC,QAAQ,EAAE;AACnB,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;AACA,EAAE,IAAI,MAAM,CAAC;AACb,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAClC;AACA,EAAE,GAAG;AACL,GAAG,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC9B,GAAG,IAAI,CAAC,MAAM,EAAE;AAChB,IAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5C,IAAI,MAAM;AACV,IAAI;AACJ,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;AACrD;AACA,EAAE,OAAO,IAAI,CAAC;AACd,EAAE;AACF;;;;"} \ No newline at end of file diff --git a/web/node_modules/magic-string/dist/magic-string.umd.js b/web/node_modules/magic-string/dist/magic-string.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..d3c5a82b11abc49fbf9bdc5bbb9d62cf138c1668 --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.umd.js @@ -0,0 +1,1626 @@ +(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.MagicString = factory()); +})(this, (function () { 'use strict'; + + class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } + } + + class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + reset() { + this.intro = ''; + this.outro = ''; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } + } + + const comma = ','.charCodeAt(0); + 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; + } + // Provide a fallback for older environments. + const 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; + }, + }; + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + function getBtoa() { + if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } + } + + const btoa = /*#__PURE__*/ getBtoa(); + + class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + } + } + + function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); + } + + function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); + } + + const toString = Object.prototype.toString; + + function isObject(thing) { + return toString.call(thing) === '[object Object]'; + } + + function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; + } + + const wordRegex = /\w/; + + class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } + } + + const n = '\n'; + + const warned = { + insertLeft: false, + insertRight: false, + storeName: false, + }; + + class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + reset(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.reset(); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } + } + + const hasOwnProp = Object.prototype.hasOwnProperty; + + class Bundle { + constructor(options = {}) { + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; + } + + addSource(source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`', + ); + } + + ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => { + if (!hasOwnProp.call(source, option)) source[option] = source.content[option]; + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(`Illegal source: same filename (${source.filename}), different contents`); + } + } + } + + this.sources.push(source); + return this; + } + + append(str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; + } + + clone() { + const bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach((source) => { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; + } + + generateDecodedMap(options = {}) { + const names = []; + let x_google_ignoreList = undefined; + this.sources.forEach((source) => { + Object.keys(source.content.storedNames).forEach((name) => { + if (!~names.indexOf(name)) names.push(name); + }); + }); + + const mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach((source, i) => { + if (i > 0) { + mappings.advance(this.separator); + } + + const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1; + const magicString = source.content; + const locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations, + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + + if (source.ignoreList && sourceIndex !== -1) { + if (x_google_ignoreList === undefined) { + x_google_ignoreList = []; + } + x_google_ignoreList.push(sourceIndex); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: this.uniqueSources.map((source) => { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map((source) => { + return options.includeContent ? source.content : null; + }), + names, + mappings: mappings.raw, + x_google_ignoreList, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + getIndentString() { + const indentStringCounts = {}; + + this.sources.forEach((source) => { + const indentStr = source.content._getRawIndentString(); + + if (indentStr === null) return; + + if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0; + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort((a, b) => { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); + } + + indent(indentStr) { + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') return this; // noop + + let trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, (match, index) => { + return index > 0 ? indentStr + match : match; + }); + } + + return this; + } + + prepend(str) { + this.intro = str + this.intro; + return this; + } + + toString() { + const body = this.sources + .map((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; + } + + isEmpty() { + if (this.intro.length && this.intro.trim()) return false; + if (this.sources.some((source) => !source.content.isEmpty())) return false; + return true; + } + + length() { + return this.sources.reduce( + (length, source) => length + source.content.length(), + this.intro.length, + ); + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimStart(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + let source; + let i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; + } + + trimEnd(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + let source; + let i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; + } + } + + MagicString.Bundle = Bundle; + MagicString.SourceMap = SourceMap; + MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121 + + return MagicString; + +})); +//# sourceMappingURL=magic-string.umd.js.map diff --git a/web/node_modules/magic-string/dist/magic-string.umd.js.map b/web/node_modules/magic-string/dist/magic-string.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..922df4639cf323824b8fe6922aa670e700f7715e --- /dev/null +++ b/web/node_modules/magic-string/dist/magic-string.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"magic-string.umd.js","sources":["../src/BitSet.js","../src/Chunk.js","../node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js","../src/index-legacy.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + '' \n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","const comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n// Provide a fallback for older environments.\nconst td = typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\nfunction decode(mappings) {\n const state = new Int32Array(5);\n const decoded = [];\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n for (let i = index; i < semi; i++) {\n let seg;\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol)\n sorted = false;\n lastCol = col;\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n }\n else {\n seg = [col, state[1], state[2], state[3]];\n }\n }\n else {\n seg = [col];\n }\n line.push(seg);\n }\n if (!sorted)\n sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n return decoded;\n}\nfunction indexOf(mappings, index) {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\nfunction decodeInteger(mappings, pos, state, j) {\n let value = 0;\n let shift = 0;\n let integer = 0;\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n const shouldNegate = value & 1;\n value >>>= 1;\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n state[j] += value;\n return pos;\n}\nfunction hasMoreVlq(mappings, i, length) {\n if (i >= length)\n return false;\n return mappings.charCodeAt(i) !== comma;\n}\nfunction sort(line) {\n line.sort(sortComparator);\n}\nfunction sortComparator(a, b) {\n return a[0] - b[0];\n}\nfunction encode(decoded) {\n const state = new Int32Array(5);\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0)\n continue;\n state[0] = 0;\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0)\n buf[pos++] = comma;\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n if (segment.length === 1)\n continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n if (segment.length === 4)\n continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n return out + td.decode(buf.subarray(0, pos));\n}\nfunction encodeInteger(buf, pos, state, segment, j) {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0)\n clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n return pos;\n}\n\nexport { decode, encode };\n//# sourceMappingURL=sourcemap-codec.mjs.map\n","import { encode } from '@jridgewell/sourcemap-codec';\n\nfunction getBtoa() {\n\tif (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {\n\t\treturn (str) => globalThis.btoa(unescape(encodeURIComponent(str)));\n\t} else if (typeof Buffer === 'function') {\n\t\treturn (str) => Buffer.from(str, 'utf-8').toString('base64');\n\t} else {\n\t\treturn () => {\n\t\t\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n\t\t};\n\t}\n}\n\nconst btoa = /*#__PURE__*/ getBtoa();\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t\tif (typeof properties.x_google_ignoreList !== 'undefined') {\n\t\t\tthis.x_google_ignoreList = properties.x_google_ignoreList;\n\t\t}\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","const wordRegex = /\\w/;\n\nexport default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tlet contentLineEnd = content.indexOf('\\n', 0);\n\t\t\tlet previousContentLineEnd = -1;\n\t\t\twhile (contentLineEnd >= 0) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\t\tif (nameIndex >= 0) {\n\t\t\t\t\tsegment.push(nameIndex);\n\t\t\t\t}\n\t\t\t\tthis.rawSegments.push(segment);\n\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\n\t\t\t\tpreviousContentLineEnd = contentLineEnd;\n\t\t\t\tcontentLineEnd = content.indexOf('\\n', contentLineEnd + 1);\n\t\t\t}\n\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\n\t\t\tthis.advance(content.slice(previousContentLineEnd + 1));\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t\tthis.advance(content);\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\t\t// when iterating each char, check if it's in a word boundary\n\t\tlet charInHiresBoundary = false;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\n\t\t\t\tif (this.hires === 'boundary') {\n\t\t\t\t\t// in hires \"boundary\", group segments per word boundary than per char\n\t\t\t\t\tif (wordRegex.test(original[originalCharIndex])) {\n\t\t\t\t\t\t// for first char in the boundary found, start the boundary by pushing a segment\n\t\t\t\t\t\tif (!charInHiresBoundary) {\n\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\tcharInHiresBoundary = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// for non-word char, end the boundary by pushing a segment\n\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\tcharInHiresBoundary = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t} else {\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: undefined },\n\t\t\tignoreList: { writable: true, value: options.ignoreList },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: [\n\t\t\t\toptions.source ? getRelativePath(options.file || '', options.source) : options.file || '',\n\t\t\t],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : undefined,\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\t_ensureindentStr() {\n\t\tif (this.indentStr === undefined) {\n\t\t\tthis.indentStr = guessIndent(this.original);\n\t\t}\n\t}\n\n\t_getRawIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr;\n\t}\n\n\tgetIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tif (indentStr === undefined) {\n\t\t\tthis._ensureindentStr();\n\t\t\tindentStr = this.indentStr || '\\t';\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',\n\t\t\t); // eslint-disable-line no-console\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\toptions = options || {};\n\t\treturn this.update(start, end, content, { ...options, overwrite: !options.contentOnly });\n\t}\n\n\tupdate(start, end, content, options) {\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',\n\t\t\t\t); // eslint-disable-line no-console\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst overwrite = options !== undefined ? options.overwrite : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, {\n\t\t\t\twritable: true,\n\t\t\t\tvalue: true,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, !overwrite);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\treset(start, end) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('reset');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.reset();\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('reset');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length) {\n\t\twhile (start < 0) start += this.original.length;\n\t\twhile (end < 0) end += this.original.length;\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`,\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n\n\thasChanged() {\n\t\treturn this.original !== this.toString();\n\t}\n\n\t_replaceRegexp(searchValue, replacement) {\n\t\tfunction getReplacement(match, str) {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treturn replacement.replace(/\\$(\\$|&|\\d+)/g, (_, i) => {\n\t\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter\n\t\t\t\t\tif (i === '$') return '$';\n\t\t\t\t\tif (i === '&') return match[0];\n\t\t\t\t\tconst num = +i;\n\t\t\t\t\tif (num < match.length) return match[+i];\n\t\t\t\t\treturn `$${i}`;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\treturn replacement(...match, match.index, str, match.groups);\n\t\t\t}\n\t\t}\n\t\tfunction matchAll(re, str) {\n\t\t\tlet match;\n\t\t\tconst matches = [];\n\t\t\twhile ((match = re.exec(str))) {\n\t\t\t\tmatches.push(match);\n\t\t\t}\n\t\t\treturn matches;\n\t\t}\n\t\tif (searchValue.global) {\n\t\t\tconst matches = matchAll(searchValue, this.original);\n\t\t\tmatches.forEach((match) => {\n\t\t\t\tif (match.index != null)\n\t\t\t\t\tthis.overwrite(\n\t\t\t\t\t\tmatch.index,\n\t\t\t\t\t\tmatch.index + match[0].length,\n\t\t\t\t\t\tgetReplacement(match, this.original),\n\t\t\t\t\t);\n\t\t\t});\n\t\t} else {\n\t\t\tconst match = this.original.match(searchValue);\n\t\t\tif (match && match.index != null)\n\t\t\t\tthis.overwrite(\n\t\t\t\t\tmatch.index,\n\t\t\t\t\tmatch.index + match[0].length,\n\t\t\t\t\tgetReplacement(match, this.original),\n\t\t\t\t);\n\t\t}\n\t\treturn this;\n\t}\n\n\t_replaceString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst index = original.indexOf(string);\n\n\t\tif (index !== -1) {\n\t\t\tthis.overwrite(index, index + string.length, replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplace(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceString(searchValue, replacement);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n\n\t_replaceAllString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst stringLength = string.length;\n\t\tfor (\n\t\t\tlet index = original.indexOf(string);\n\t\t\tindex !== -1;\n\t\t\tindex = original.indexOf(string, index + stringLength)\n\t\t) {\n\t\t\tthis.overwrite(index, index + stringLength, replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplaceAll(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceAllString(searchValue, replacement);\n\t\t}\n\n\t\tif (!searchValue.global) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'MagicString.prototype.replaceAll called with a non-global RegExp argument',\n\t\t\t);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tlet x_google_ignoreList = undefined;\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\n\t\t\tif (source.ignoreList && sourceIndex !== -1) {\n\t\t\t\tif (x_google_ignoreList === undefined) {\n\t\t\t\t\tx_google_ignoreList = [];\n\t\t\t\t}\n\t\t\t\tx_google_ignoreList.push(sourceIndex);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content._getRawIndentString();\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length,\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\n}\n","import MagicString from './MagicString.js';\nimport Bundle from './Bundle.js';\nimport SourceMap from './SourceMap.js';\n\nMagicString.Bundle = Bundle;\nMagicString.SourceMap = SourceMap;\nMagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121\n\nexport default MagicString;\n"],"names":[],"mappings":";;;;;;CAAe,MAAM,MAAM,CAAC;CAC5B,CAAC,WAAW,CAAC,GAAG,EAAE;CAClB,EAAE,IAAI,CAAC,IAAI,GAAG,GAAG,YAAY,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC;CAC5D,EAAE;AACF;CACA,CAAC,GAAG,CAAC,CAAC,EAAE;CACR,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;CACrC,EAAE;AACF;CACA,CAAC,GAAG,CAAC,CAAC,EAAE;CACR,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;CACjD,EAAE;CACF;;CCZe,MAAM,KAAK,CAAC;CAC3B,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE;CAClC,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;CACrB,EAAE,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;CACjB,EAAE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC1B;CACA,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;CAClB,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB;CACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;CACzB,EAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;CACzB,EAAE,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AACtB;CACA,EAMS;CACT,GAAG,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;CACxB,GAAG,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;CACpB,GAAG;CACH,EAAE;AACF;CACA,CAAC,UAAU,CAAC,OAAO,EAAE;CACrB,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;CACxB,EAAE;AACF;CACA,CAAC,WAAW,CAAC,OAAO,EAAE;CACtB,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;CACpC,EAAE;AACF;CACA,CAAC,KAAK,GAAG;CACT,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/D;CACA,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;CAC3B,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;CAC3B,EAAE,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;CAC/B,EAAE,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;CACnC,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAC7B;CACA,EAAE,OAAO,KAAK,CAAC;CACf,EAAE;AACF;CACA,CAAC,QAAQ,CAAC,KAAK,EAAE;CACjB,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC;CAChD,EAAE;AACF;CACA,CAAC,QAAQ,CAAC,EAAE,EAAE;CACd,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;CACnB,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;CACb,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACtB,GAAG;CACH,EAAE;AACF;CACA,CAAC,YAAY,CAAC,EAAE,EAAE;CAClB,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;CACnB,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;CACb,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC;CAC1B,GAAG;CACH,EAAE;AACF;CACA,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE;CACvC,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;CACzB,EAAE,IAAI,CAAC,WAAW,EAAE;CACpB,GAAG,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;CACnB,GAAG,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;CACnB,GAAG;CACH,EAAE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;AAC7B;CACA,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;AACrB;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,WAAW,CAAC,OAAO,EAAE;CACtB,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CACpC,EAAE;AACF;CACA,CAAC,YAAY,CAAC,OAAO,EAAE;CACvB,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CACpC,EAAE;AACF;CACA,CAAC,KAAK,GAAG;CACT,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;CAClB,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;CAClB,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;CACnB,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC;CAChC,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;CAC1B,GAAG,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;CACvB,GAAG;CACH,EAAE;AACF;CACA,CAAC,KAAK,CAAC,KAAK,EAAE;CACd,EAAE,MAAM,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AACxC;CACA,EAAE,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;CAC5D,EAAE,MAAM,aAAa,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AACxD;CACA,EAAE,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;AACjC;CACA,EAAE,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;CAC7D,EAAE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;CAC9B,EAAE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;AAClB;CACA,EAAE,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC;AACnB;CACA,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;CAC5B,GAAG,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;CACrB,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,OAAO,GAAG,cAAc,CAAC;CACjC,GAAG;AACH;CACA,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;CAC5B,EAAE,IAAI,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;CACvD,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;CAC3B,EAAE,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;AACvB;CACA,EAAE,OAAO,QAAQ,CAAC;CAClB,EAAE;AACF;CACA,CAAC,QAAQ,GAAG;CACZ,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CAChD,EAAE;AACF;CACA,CAAC,OAAO,CAAC,EAAE,EAAE;CACb,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;CACA,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C;CACA,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;CACtB,GAAG,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE;CACjC,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;CACtE,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;CACrB;CACA,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;CAC9C,KAAK;CACL,IAAI;CACJ,GAAG,OAAO,IAAI,CAAC;CACf,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAClC;CACA,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC3C,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;CACtC,GAAG;CACH,EAAE;AACF;CACA,CAAC,SAAS,CAAC,EAAE,EAAE;CACf,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;CACA,EAAE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C;CACA,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;CACtB,GAAG,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE;CACjC,IAAI,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC3D,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;CACrB;CACA,KAAK,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;CAClD,KAAK;CACL,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;CACnC,IAAI;CACJ,GAAG,OAAO,IAAI,CAAC;CACf,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAClC;CACA,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC3C,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;CACtC,GAAG;CACH,EAAE;CACF;;CCvLA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;CAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;CACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;CACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;CACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;CACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;CACvC,IAAI,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;CAClC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CACrB,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CACrB,CAAC;CACD;CACA,MAAM,EAAE,GAAG,OAAO,WAAW,KAAK,WAAW;CAC7C,sBAAsB,IAAI,WAAW,EAAE;CACvC,MAAM,OAAO,MAAM,KAAK,WAAW;CACnC,UAAU;CACV,YAAY,MAAM,CAAC,GAAG,EAAE;CACxB,gBAAgB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;CACpF,gBAAgB,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;CACtC,aAAa;CACb,SAAS;CACT,UAAU;CACV,YAAY,MAAM,CAAC,GAAG,EAAE;CACxB,gBAAgB,IAAI,GAAG,GAAG,EAAE,CAAC;CAC7B,gBAAgB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;CACrD,oBAAoB,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;CACvD,iBAAiB;CACjB,gBAAgB,OAAO,GAAG,CAAC;CAC3B,aAAa;CACb,SAAS,CAAC;CA2EV,SAAS,MAAM,CAAC,OAAO,EAAE;CACzB,IAAI,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;CACpC,IAAI,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;CAChC,IAAI,MAAM,SAAS,GAAG,SAAS,GAAG,EAAE,CAAC;CACrC,IAAI,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC;CAC1C,IAAI,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;CAC3C,IAAI,IAAI,GAAG,GAAG,CAAC,CAAC;CAChB,IAAI,IAAI,GAAG,GAAG,EAAE,CAAC;CACjB,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;CAC7C,QAAQ,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAChC,QAAQ,IAAI,CAAC,GAAG,CAAC,EAAE;CACnB,YAAY,IAAI,GAAG,KAAK,SAAS,EAAE;CACnC,gBAAgB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;CACtC,gBAAgB,GAAG,GAAG,CAAC,CAAC;CACxB,aAAa;CACb,YAAY,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC;CACnC,SAAS;CACT,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;CAC7B,YAAY,SAAS;CACrB,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CACrB,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;CAC9C,YAAY,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CACpC;CACA;CACA,YAAY,IAAI,GAAG,GAAG,SAAS,EAAE;CACjC,gBAAgB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;CACtC,gBAAgB,GAAG,CAAC,UAAU,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;CAClD,gBAAgB,GAAG,IAAI,SAAS,CAAC;CACjC,aAAa;CACb,YAAY,IAAI,CAAC,GAAG,CAAC;CACrB,gBAAgB,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;CACnC,YAAY,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;CAC7D,YAAY,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;CACpC,gBAAgB,SAAS;CACzB,YAAY,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;CAC7D,YAAY,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;CAC7D,YAAY,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;CAC7D,YAAY,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;CACpC,gBAAgB,SAAS;CACzB,YAAY,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;CAC7D,SAAS;CACT,KAAK;CACL,IAAI,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;CACjD,CAAC;CACD,SAAS,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE;CACpD,IAAI,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC5B,IAAI,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;CAC9B,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;CACpB,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;CAC/C,IAAI,GAAG;CACP,QAAQ,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;CACrC,QAAQ,GAAG,MAAM,CAAC,CAAC;CACnB,QAAQ,IAAI,GAAG,GAAG,CAAC;CACnB,YAAY,OAAO,IAAI,QAAQ,CAAC;CAChC,QAAQ,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;CACxC,KAAK,QAAQ,GAAG,GAAG,CAAC,EAAE;CACtB,IAAI,OAAO,GAAG,CAAC;CACf;;CC9JA,SAAS,OAAO,GAAG;CACnB,CAAC,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,UAAU,EAAE;CACjF,EAAE,OAAO,CAAC,GAAG,KAAK,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CACrE,EAAE,MAAM,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;CAC1C,EAAE,OAAO,CAAC,GAAG,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;CAC/D,EAAE,MAAM;CACR,EAAE,OAAO,MAAM;CACf,GAAG,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;CAC9F,GAAG,CAAC;CACJ,EAAE;CACF,CAAC;AACD;CACA,MAAM,IAAI,iBAAiB,OAAO,EAAE,CAAC;AACrC;CACe,MAAM,SAAS,CAAC;CAC/B,CAAC,WAAW,CAAC,UAAU,EAAE;CACzB,EAAE,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;CACnB,EAAE,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC;CAC9B,EAAE,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;CACpC,EAAE,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;CAClD,EAAE,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;CAChC,EAAE,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;CAC9C,EAAE,IAAI,OAAO,UAAU,CAAC,mBAAmB,KAAK,WAAW,EAAE;CAC7D,GAAG,IAAI,CAAC,mBAAmB,GAAG,UAAU,CAAC,mBAAmB,CAAC;CAC7D,GAAG;CACH,EAAE;AACF;CACA,CAAC,QAAQ,GAAG;CACZ,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;CAC9B,EAAE;AACF;CACA,CAAC,KAAK,GAAG;CACT,EAAE,OAAO,6CAA6C,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;CAC/E,EAAE;CACF;;CCpCe,SAAS,WAAW,CAAC,IAAI,EAAE;CAC1C,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC;CACA,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;CAC1D,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D;CACA,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;CACjD,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA;CACA;CACA;CACA,CAAC,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;CACrC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA;CACA,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,OAAO,KAAK;CAClD,EAAE,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;CAClD,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;CACvC,EAAE,EAAE,QAAQ,CAAC,CAAC;AACd;CACA,CAAC,OAAO,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;CACrC;;CCxBe,SAAS,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE;CAClD,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;CACvC,CAAC,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACnC;CACA,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC;AACjB;CACA,CAAC,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE;CACrC,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC;CACpB,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;CAClB,EAAE;AACF;CACA,CAAC,IAAI,SAAS,CAAC,MAAM,EAAE;CACvB,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC;CAC3B,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;CAClC,EAAE;AACF;CACA,CAAC,OAAO,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;CAC5C;;CCjBA,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;AAC3C;CACe,SAAS,QAAQ,CAAC,KAAK,EAAE;CACxC,CAAC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,iBAAiB,CAAC;CACnD;;CCJe,SAAS,UAAU,CAAC,MAAM,EAAE;CAC3C,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;CAC1C,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AACxB;CACA,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;CACzD,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;CACxB,EAAE,GAAG,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;CACrC,EAAE;AACF;CACA,CAAC,OAAO,SAAS,MAAM,CAAC,KAAK,EAAE;CAC/B,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;CACZ,EAAE,IAAI,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC;CAC7B,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE;CAChB,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;CAC1B,GAAG,IAAI,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE;CAC/B,IAAI,CAAC,GAAG,CAAC,CAAC;CACV,IAAI,MAAM;CACV,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;CACd,IAAI;CACJ,GAAG;CACH,EAAE,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;CACrB,EAAE,MAAM,MAAM,GAAG,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;CAC3C,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;CAC1B,EAAE,CAAC;CACH;;CCxBA,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB;CACe,MAAM,QAAQ,CAAC;CAC9B,CAAC,WAAW,CAAC,KAAK,EAAE;CACpB,EAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;CACrB,EAAE,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;CAC7B,EAAE,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;CAC/B,EAAE,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;CAChB,EAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,CAAC;CAC3D,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;CACtB,EAAE;AACF;CACA,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE;CAC/C,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE;CACtB,GAAG,IAAI,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;CACjD,GAAG,IAAI,sBAAsB,GAAG,CAAC,CAAC,CAAC;CACnC,GAAG,OAAO,cAAc,IAAI,CAAC,EAAE;CAC/B,IAAI,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAClF,IAAI,IAAI,SAAS,IAAI,CAAC,EAAE;CACxB,KAAK,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;CAC7B,KAAK;CACL,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACnC;CACA,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;CAChC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;CAC7D,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;AACjC;CACA,IAAI,sBAAsB,GAAG,cAAc,CAAC;CAC5C,IAAI,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,CAAC,CAAC,CAAC;CAC/D,IAAI;AACJ;CACA,GAAG,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACjF,GAAG,IAAI,SAAS,IAAI,CAAC,EAAE;CACvB,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;CAC5B,IAAI;CACJ,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAClC;CACA,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,sBAAsB,GAAG,CAAC,CAAC,CAAC,CAAC;CAC3D,GAAG,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE;CAC3B,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;CACvC,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;CACzB,GAAG;AACH;CACA,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;CACtB,EAAE;AACF;CACA,CAAC,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,kBAAkB,EAAE;CACzE,EAAE,IAAI,iBAAiB,GAAG,KAAK,CAAC,KAAK,CAAC;CACtC,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;CACnB;CACA,EAAE,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAClC;CACA,EAAE,OAAO,iBAAiB,GAAG,KAAK,CAAC,GAAG,EAAE;CACxC,GAAG,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,IAAI,kBAAkB,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE;CACzE,IAAI,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AAClF;CACA,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,UAAU,EAAE;CACnC;CACA,KAAK,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,EAAE;CACtD;CACA,MAAM,IAAI,CAAC,mBAAmB,EAAE;CAChC,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;CACtC,OAAO,mBAAmB,GAAG,IAAI,CAAC;CAClC,OAAO;CACP,MAAM,MAAM;CACZ;CACA,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;CACrC,MAAM,mBAAmB,GAAG,KAAK,CAAC;CAClC,MAAM;CACN,KAAK,MAAM;CACX,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;CACpC,KAAK;CACL,IAAI;AACJ;CACA,GAAG,IAAI,QAAQ,CAAC,iBAAiB,CAAC,KAAK,IAAI,EAAE;CAC7C,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;CAClB,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;CACnB,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;CAChC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;CAC7D,IAAI,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;CACjC,IAAI,KAAK,GAAG,IAAI,CAAC;CACjB,IAAI,MAAM;CACV,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;CACpB,IAAI,IAAI,CAAC,mBAAmB,IAAI,CAAC,CAAC;CAClC,IAAI,KAAK,GAAG,KAAK,CAAC;CAClB,IAAI;AACJ;CACA,GAAG,iBAAiB,IAAI,CAAC,CAAC;CAC1B,GAAG;AACH;CACA,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;CACtB,EAAE;AACF;CACA,CAAC,OAAO,CAAC,GAAG,EAAE;CACd,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO;AACnB;CACA,EAAE,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC;CACA,EAAE,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;CACxB,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;CAC9C,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;CAC7B,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;CAC7D,IAAI;CACJ,GAAG,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;CAChC,GAAG;AACH;CACA,EAAE,IAAI,CAAC,mBAAmB,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;CAC7D,EAAE;CACF;;CClGA,MAAM,CAAC,GAAG,IAAI,CAAC;AACf;CACA,MAAM,MAAM,GAAG;CACf,CAAC,UAAU,EAAE,KAAK;CAClB,CAAC,WAAW,EAAE,KAAK;CACnB,CAAC,SAAS,EAAE,KAAK;CACjB,CAAC,CAAC;AACF;CACe,MAAM,WAAW,CAAC;CACjC,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,EAAE,EAAE;CACnC,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AACpD;CACA,EAAE,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE;CAChC,GAAG,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE;CAC9C,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;CACvC,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;CACvC,GAAG,UAAU,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;CAC/C,GAAG,SAAS,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;CAC9C,GAAG,iBAAiB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE;CACtD,GAAG,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;CACzC,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;CACvC,GAAG,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,EAAE;CACxD,GAAG,qBAAqB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,qBAAqB,EAAE;CAClF,GAAG,kBAAkB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,MAAM,EAAE,EAAE;CAC9D,GAAG,WAAW,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE;CAC7C,GAAG,SAAS,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE;CAClD,GAAG,UAAU,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,EAAE;CAC5D,GAAG,CAAC,CAAC;AAKL;CACA,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;CAC1B,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;CACpC,EAAE;AACF;CACA,CAAC,oBAAoB,CAAC,IAAI,EAAE;CAC5B,EAAE,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;CACpC,EAAE;AACF;CACA,CAAC,MAAM,CAAC,OAAO,EAAE;CACjB,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;AACzF;CACA,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;CACxB,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;CAC5B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;CACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC;CACA,EAAE,IAAI,KAAK,EAAE;CACb,GAAG,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;CAC7B,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;CACzB,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;CAC7B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;CACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC;CACA,EAAE,IAAI,KAAK,EAAE;CACb,GAAG,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;CAC9B,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC;CACzB,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,KAAK,GAAG;CACT,EAAE,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC7E;CACA,EAAE,IAAI,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC;CACtC,EAAE,IAAI,WAAW,IAAI,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,iBAAiB,GAAG,aAAa,CAAC,KAAK,EAAE,CAAC,CAAC;AAC3F;CACA,EAAE,OAAO,aAAa,EAAE;CACxB,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,WAAW,CAAC;CACnD,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC;AAC/C;CACA,GAAG,MAAM,iBAAiB,GAAG,aAAa,CAAC,IAAI,CAAC;CAChD,GAAG,MAAM,eAAe,GAAG,iBAAiB,IAAI,iBAAiB,CAAC,KAAK,EAAE,CAAC;AAC1E;CACA,GAAG,IAAI,eAAe,EAAE;CACxB,IAAI,WAAW,CAAC,IAAI,GAAG,eAAe,CAAC;CACvC,IAAI,eAAe,CAAC,QAAQ,GAAG,WAAW,CAAC;AAC3C;CACA,IAAI,WAAW,GAAG,eAAe,CAAC;CAClC,IAAI;AACJ;CACA,GAAG,aAAa,GAAG,iBAAiB,CAAC;CACrC,GAAG;AACH;CACA,EAAE,MAAM,CAAC,SAAS,GAAG,WAAW,CAAC;AACjC;CACA,EAAE,IAAI,IAAI,CAAC,qBAAqB,EAAE;CAClC,GAAG,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC;CACrE,GAAG;AACH;CACA,EAAE,MAAM,CAAC,kBAAkB,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;AAClE;CACA,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;CAC5B,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;AAC5B;CACA,EAAE,OAAO,MAAM,CAAC;CAChB,EAAE;AACF;CACA,CAAC,kBAAkB,CAAC,OAAO,EAAE;CAC7B,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;CACA,EAAE,MAAM,WAAW,GAAG,CAAC,CAAC;CACxB,EAAE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;CAC9C,EAAE,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/C;CACA,EAAE,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC3C;CACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;CAClB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;CAChC,GAAG;AACH;CACA,EAAE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,KAAK;CACtC,GAAG,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACnC;CACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACzD;CACA,GAAG,IAAI,KAAK,CAAC,MAAM,EAAE;CACrB,IAAI,QAAQ,CAAC,OAAO;CACpB,KAAK,WAAW;CAChB,KAAK,KAAK,CAAC,OAAO;CAClB,KAAK,GAAG;CACR,KAAK,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;CACzD,KAAK,CAAC;CACN,IAAI,MAAM;CACV,IAAI,QAAQ,CAAC,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;CAC/F,IAAI;AACJ;CACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;CACzD,GAAG,CAAC,CAAC;AACL;CACA,EAAE,OAAO;CACT,GAAG,IAAI,EAAE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,SAAS;CACrE,GAAG,OAAO,EAAE;CACZ,IAAI,OAAO,CAAC,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;CAC7F,IAAI;CACJ,GAAG,cAAc,EAAE,OAAO,CAAC,cAAc,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,SAAS;CACvE,GAAG,KAAK;CACR,GAAG,QAAQ,EAAE,QAAQ,CAAC,GAAG;CACzB,GAAG,mBAAmB,EAAE,IAAI,CAAC,UAAU,GAAG,CAAC,WAAW,CAAC,GAAG,SAAS;CACnE,GAAG,CAAC;CACJ,EAAE;AACF;CACA,CAAC,WAAW,CAAC,OAAO,EAAE;CACtB,EAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;CACzD,EAAE;AACF;CACA,CAAC,gBAAgB,GAAG;CACpB,EAAE,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE;CACpC,GAAG,IAAI,CAAC,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;CAC/C,GAAG;CACH,EAAE;AACF;CACA,CAAC,mBAAmB,GAAG;CACvB,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;CAC1B,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC;CACxB,EAAE;AACF;CACA,CAAC,eAAe,GAAG;CACnB,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;CAC1B,EAAE,OAAO,IAAI,CAAC,SAAS,KAAK,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;CACzD,EAAE;AACF;CACA,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,EAAE;CAC5B,EAAE,MAAM,OAAO,GAAG,YAAY,CAAC;AAC/B;CACA,EAAE,IAAI,QAAQ,CAAC,SAAS,CAAC,EAAE;CAC3B,GAAG,OAAO,GAAG,SAAS,CAAC;CACvB,GAAG,SAAS,GAAG,SAAS,CAAC;CACzB,GAAG;AACH;CACA,EAAE,IAAI,SAAS,KAAK,SAAS,EAAE;CAC/B,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;CAC3B,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;CACtC,GAAG;AACH;CACA,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC;AACpC;CACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;CACA;CACA,EAAE,MAAM,UAAU,GAAG,EAAE,CAAC;AACxB;CACA,EAAE,IAAI,OAAO,CAAC,OAAO,EAAE;CACvB,GAAG,MAAM,UAAU;CACnB,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;CACjF,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,KAAK;CACrC,IAAI,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE;CACzD,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;CAC1B,KAAK;CACL,IAAI,CAAC,CAAC;CACN,GAAG;AACH;CACA,EAAE,IAAI,yBAAyB,GAAG,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC;CAChE,EAAE,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK;CAC9B,GAAG,IAAI,yBAAyB,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;CAChE,GAAG,yBAAyB,GAAG,IAAI,CAAC;CACpC,GAAG,OAAO,KAAK,CAAC;CAChB,GAAG,CAAC;AACJ;CACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD;CACA,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC;CACpB,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B;CACA,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;AACzB;CACA,GAAG,IAAI,KAAK,CAAC,MAAM,EAAE;CACrB,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;CAChC,KAAK,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC9D;CACA,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;CAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC;CACnF,MAAM;CACN,KAAK;CACL,IAAI,MAAM;CACV,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC;AAC5B;CACA,IAAI,OAAO,SAAS,GAAG,GAAG,EAAE;CAC5B,KAAK,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;CACjC,MAAM,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAC5C;CACA,MAAM,IAAI,IAAI,KAAK,IAAI,EAAE;CACzB,OAAO,yBAAyB,GAAG,IAAI,CAAC;CACxC,OAAO,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,yBAAyB,EAAE;CAC7D,OAAO,yBAAyB,GAAG,KAAK,CAAC;AACzC;CACA,OAAO,IAAI,SAAS,KAAK,KAAK,CAAC,KAAK,EAAE;CACtC,QAAQ,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;CACtC,QAAQ,MAAM;CACd,QAAQ,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;CAC3C,QAAQ,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CAC3B,QAAQ,KAAK,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;CACtC,QAAQ;CACR,OAAO;CACP,MAAM;AACN;CACA,KAAK,SAAS,IAAI,CAAC,CAAC;CACpB,KAAK;CACL,IAAI;AACJ;CACA,GAAG,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC;CACzB,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACtB,GAAG;AACH;CACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,MAAM,GAAG;CACV,EAAE,MAAM,IAAI,KAAK;CACjB,GAAG,iFAAiF;CACpF,GAAG,CAAC;CACJ,EAAE;AACF;CACA,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE;CAC5B,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE;CAC1B,GAAG,OAAO,CAAC,IAAI;CACf,IAAI,oFAAoF;CACxF,IAAI,CAAC;CACL,GAAG,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;CAC5B,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;CACzC,EAAE;AACF;CACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;CAC7B,EAAE,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;CAC3B,GAAG,OAAO,CAAC,IAAI;CACf,IAAI,uFAAuF;CAC3F,IAAI,CAAC;CACL,GAAG,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC;CAC7B,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;CAC3C,EAAE;AACF;CACA,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE;CACzB,EAAE,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AAG/F;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;CACnB,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;CACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;CACpC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC/B;CACA,EAAE,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC;CACjC,EAAE,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC;AAC7B;CACA,EAAE,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;CACvC,EAAE,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE,OAAO,IAAI,CAAC;CACxD,EAAE,MAAM,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;AAChE;CACA,EAAE,IAAI,OAAO,EAAE,OAAO,CAAC,IAAI,GAAG,QAAQ,CAAC;CACvC,EAAE,IAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,OAAO,CAAC;AAC5C;CACA,EAAE,IAAI,OAAO,EAAE,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC;CACpC,EAAE,IAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;AACzC;CACA,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;CACnD,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;CAClB,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,QAAQ,CAAC;CACnC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC;CAC9B,GAAG;AACH;CACA,EAAE,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC;CAC3B,EAAE,IAAI,CAAC,IAAI,GAAG,QAAQ,IAAI,IAAI,CAAC;AAC/B;CACA,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;CACxC,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;CAGvC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;CACzC,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;CAC1B,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CAC3F,EAAE;AACF;CACA,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE;CACtC,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,sCAAsC,CAAC,CAAC;AAC/F;CACA,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;CAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;CACA,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;CAC1E,EAAE,IAAI,KAAK,KAAK,GAAG;CACnB,GAAG,MAAM,IAAI,KAAK;CAClB,IAAI,+EAA+E;CACnF,IAAI,CAAC;AAGL;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;CACA,EAAE,IAAI,OAAO,KAAK,IAAI,EAAE;CACxB,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE;CAC1B,IAAI,OAAO,CAAC,IAAI;CAChB,KAAK,+HAA+H;CACpI,KAAK,CAAC;CACN,IAAI,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;CAC5B,IAAI;AACJ;CACA,GAAG,OAAO,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;CACjC,GAAG;CACH,EAAE,MAAM,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC;CACtE,EAAE,MAAM,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC;AACtE;CACA,EAAE,IAAI,SAAS,EAAE;CACjB,GAAG,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;CACpD,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE;CACrD,IAAI,QAAQ,EAAE,IAAI;CAClB,IAAI,KAAK,EAAE,IAAI;CACf,IAAI,UAAU,EAAE,IAAI;CACpB,IAAI,CAAC,CAAC;CACN,GAAG;AACH;CACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;CACpC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC/B;CACA,EAAE,IAAI,KAAK,EAAE;CACb,GAAG,IAAI,KAAK,GAAG,KAAK,CAAC;CACrB,GAAG,OAAO,KAAK,KAAK,IAAI,EAAE;CAC1B,IAAI,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;CAChD,KAAK,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;CAC9D,KAAK;CACL,IAAI,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACvB,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;CAC1B,IAAI;AACJ;CACA,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,CAAC,SAAS,CAAC,CAAC;CAC9C,GAAG,MAAM;CACT;CACA,GAAG,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACvE;CACA;CACA,GAAG,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;CACxB,GAAG,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC;CAC5B,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,OAAO,CAAC,OAAO,EAAE;CAClB,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;AACzF;CACA,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CACpC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE;CAC7B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;CACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAClC;CACA,EAAE,IAAI,KAAK,EAAE;CACb,GAAG,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;CAC9B,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CACrC,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE;CAC9B,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;AAG5F;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrB;CACA,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC;CACA,EAAE,IAAI,KAAK,EAAE;CACb,GAAG,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;CAC/B,GAAG,MAAM;CACT,GAAG,IAAI,CAAC,KAAK,GAAG,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CACrC,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE;CACpB,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;CAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;CACA,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE,OAAO,IAAI,CAAC;AACjC;CACA,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;CAC7F,EAAE,IAAI,KAAK,GAAG,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AAGrE;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAClC;CACA,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;CACpB,GAAG,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;CACpB,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAClB;CACA,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;CAC5D,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE;CACnB,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;CAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;CACA,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE,OAAO,IAAI,CAAC;AACjC;CACA,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;CAC7F,EAAE,IAAI,KAAK,GAAG,GAAG,EAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AAGrE;CACA,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;CACrB,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACnB;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAClC;CACA,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;AACjB;CACA,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;CAC5D,GAAG;CAGH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,QAAQ,GAAG;CACZ,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;CAClE,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;CAC7B,EAAE,GAAG;CACL,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;CACtE,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;CAC5E,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;CACtE,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,QAAQ,GAAG;CACrC,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;CAClE,EAAE,OAAO,EAAE,CAAC;CACZ,EAAE;AACF;CACA,CAAC,QAAQ,GAAG;CACZ,EAAE,IAAI,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAC5C,EAAE,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;CAChE,EAAE,IAAI,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;CAC3B,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;CAC7B,EAAE,GAAG;CACL,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;CAC/B,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAC3C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;CAC7E,IAAI,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;CACpC,IAAI;AACJ;CACA,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;CACjC,IAAI,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAC7C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;CAC/E,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC;CACtC,IAAI;AACJ;CACA,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;CAC/B,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAC3C,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;CAC7E,IAAI,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;CACpC,IAAI;CACJ,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,QAAQ,GAAG;CACrC,EAAE,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CACxC,EAAE,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;CAC1E,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;CAC9B,EAAE;AACF;CACA,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE;CAC9C,EAAE,OAAO,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;CAClD,EAAE,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC9C;CACA,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC;AAClB;CACA;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;CAC9B,EAAE,OAAO,KAAK,KAAK,KAAK,CAAC,KAAK,GAAG,KAAK,IAAI,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,EAAE;CAC/D;CACA,GAAG,IAAI,KAAK,CAAC,KAAK,GAAG,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,GAAG,EAAE;CAC9C,IAAI,OAAO,MAAM,CAAC;CAClB,IAAI;AACJ;CACA,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACtB,GAAG;AACH;CACA,EAAE,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK;CACpD,GAAG,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC,CAAC;AACpF;CACA,EAAE,MAAM,UAAU,GAAG,KAAK,CAAC;CAC3B,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,IAAI,KAAK,CAAC,KAAK,KAAK,UAAU,KAAK,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,EAAE;CACvE,IAAI,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;CAC1B,IAAI;AACJ;CACA,GAAG,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,GAAG,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC;CAC7D,GAAG,IAAI,WAAW,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG;CACvD,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;AACjF;CACA,GAAG,MAAM,UAAU,GAAG,UAAU,KAAK,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;CACrE,GAAG,MAAM,QAAQ,GAAG,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;AAChG;CACA,GAAG,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;AACvD;CACA,GAAG,IAAI,KAAK,CAAC,KAAK,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE;CAC3D,IAAI,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC;CAC1B,IAAI;AACJ;CACA,GAAG,IAAI,WAAW,EAAE;CACpB,IAAI,MAAM;CACV,IAAI;AACJ;CACA,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACtB,GAAG;AACH;CACA,EAAE,OAAO,MAAM,CAAC;CAChB,EAAE;AACF;CACA;CACA,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE;CAClB,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;CAC7B,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;CACzB,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC3C;CACA,EAAE,OAAO,KAAK,CAAC;CACf,EAAE;AACF;CACA,CAAC,MAAM,CAAC,KAAK,EAAE;CACf,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,OAAO;AAGvD;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,iBAAiB,CAAC;CACrC,EAAE,MAAM,aAAa,GAAG,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC;AAC1C;CACA,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACpE;CACA,GAAG,KAAK,GAAG,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;CAC7E,GAAG;CACH,EAAE;AACF;CACA,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE;CAC3B,EAAE,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE;CAC5C;CACA,GAAG,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC;CAChD,GAAG,MAAM,IAAI,KAAK;CAClB,IAAI,CAAC,mDAAmD,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;CACzG,IAAI,CAAC;CACL,GAAG;AACH;CACA,EAAE,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACtC;CACA,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;CAC5B,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC;CACjC,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;AACtC;CACA,EAAE,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;AAC1D;CACA,EAAE,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;CAEjC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,QAAQ,GAAG;CACZ,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;AACvB;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;CAC9B,EAAE,OAAO,KAAK,EAAE;CAChB,GAAG,GAAG,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;CAC3B,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACtB,GAAG;AACH;CACA,EAAE,OAAO,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;CAC1B,EAAE;AACF;CACA,CAAC,OAAO,GAAG;CACX,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;CAC9B,EAAE,GAAG;CACL,GAAG;CACH,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE;CAC7C,KAAK,KAAK,CAAC,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;CAClD,KAAK,KAAK,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;CAC9C;CACA,IAAI,OAAO,KAAK,CAAC;CACjB,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,IAAI,GAAG;CACjC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,MAAM,GAAG;CACV,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;CAC9B,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;CACjB,EAAE,GAAG;CACL,GAAG,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;CAC5E,GAAG,SAAS,KAAK,GAAG,KAAK,CAAC,IAAI,GAAG;CACjC,EAAE,OAAO,MAAM,CAAC;CAChB,EAAE;AACF;CACA,CAAC,SAAS,GAAG;CACb,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;CAC/B,EAAE;AACF;CACA,CAAC,IAAI,CAAC,QAAQ,EAAE;CAChB,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;CACpD,EAAE;AACF;CACA,CAAC,cAAc,CAAC,QAAQ,EAAE;CAC1B,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;CACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;AAC7B;CACA,EAAE,GAAG;CACL,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;CACzB,GAAG,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;AACrC;CACA;CACA,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,EAAE;CAC1B,IAAI,IAAI,IAAI,CAAC,SAAS,KAAK,KAAK,EAAE;CAClC,KAAK,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;CACjC,KAAK;AACL;CACA,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;CAClC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;CAChD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;CAC5C,IAAI;AACJ;CACA,GAAG,IAAI,OAAO,EAAE,OAAO,IAAI,CAAC;CAC5B,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC;CAC1B,GAAG,QAAQ,KAAK,EAAE;AAClB;CACA,EAAE,OAAO,KAAK,CAAC;CACf,EAAE;AACF;CACA,CAAC,OAAO,CAAC,QAAQ,EAAE;CACnB,EAAE,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;CAChC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;CACF,CAAC,gBAAgB,CAAC,QAAQ,EAAE;CAC5B,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AACzD;CACA,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC1C,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC;AACrC;CACA,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;AAC9B;CACA,EAAE,GAAG;CACL,GAAG,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC;CACzB,GAAG,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;AACvC;CACA,GAAG,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG,EAAE;CAC1B;CACA,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC;AAC9D;CACA,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;CAClC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;CAChD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC;CAC5C,IAAI;AACJ;CACA,GAAG,IAAI,OAAO,EAAE,OAAO,IAAI,CAAC;CAC5B,GAAG,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC;CACtB,GAAG,QAAQ,KAAK,EAAE;AAClB;CACA,EAAE,OAAO,KAAK,CAAC;CACf,EAAE;AACF;CACA,CAAC,SAAS,CAAC,QAAQ,EAAE;CACrB,EAAE,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;CAClC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,UAAU,GAAG;CACd,EAAE,OAAO,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE,CAAC;CAC3C,EAAE;AACF;CACA,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,EAAE;CAC1C,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE;CACtC,GAAG,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;CACxC,IAAI,OAAO,WAAW,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK;CAC1D;CACA,KAAK,IAAI,CAAC,KAAK,GAAG,EAAE,OAAO,GAAG,CAAC;CAC/B,KAAK,IAAI,CAAC,KAAK,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;CACpC,KAAK,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC;CACpB,KAAK,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;CAC9C,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;CACpB,KAAK,CAAC,CAAC;CACP,IAAI,MAAM;CACV,IAAI,OAAO,WAAW,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;CACjE,IAAI;CACJ,GAAG;CACH,EAAE,SAAS,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE;CAC7B,GAAG,IAAI,KAAK,CAAC;CACb,GAAG,MAAM,OAAO,GAAG,EAAE,CAAC;CACtB,GAAG,QAAQ,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;CAClC,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;CACxB,IAAI;CACJ,GAAG,OAAO,OAAO,CAAC;CAClB,GAAG;CACH,EAAE,IAAI,WAAW,CAAC,MAAM,EAAE;CAC1B,GAAG,MAAM,OAAO,GAAG,QAAQ,CAAC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;CACxD,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,KAAK;CAC9B,IAAI,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI;CAC3B,KAAK,IAAI,CAAC,SAAS;CACnB,MAAM,KAAK,CAAC,KAAK;CACjB,MAAM,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;CACnC,MAAM,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC;CAC1C,MAAM,CAAC;CACP,IAAI,CAAC,CAAC;CACN,GAAG,MAAM;CACT,GAAG,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;CAClD,GAAG,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,IAAI;CACnC,IAAI,IAAI,CAAC,SAAS;CAClB,KAAK,KAAK,CAAC,KAAK;CAChB,KAAK,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM;CAClC,KAAK,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC;CACzC,KAAK,CAAC;CACN,GAAG;CACH,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE;CACrC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;CAC5B,EAAE,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACzC;CACA,EAAE,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;CACpB,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;CAC7D,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,EAAE;CACnC,EAAE,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;CACvC,GAAG,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;CACxD,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;CACvD,EAAE;AACF;CACA,CAAC,iBAAiB,CAAC,MAAM,EAAE,WAAW,EAAE;CACxC,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;CAC5B,EAAE,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;CACrC,EAAE;CACF,GAAG,IAAI,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC;CACvC,GAAG,KAAK,KAAK,CAAC,CAAC;CACf,GAAG,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,GAAG,YAAY,CAAC;CACzD,IAAI;CACJ,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,YAAY,EAAE,WAAW,CAAC,CAAC;CAC5D,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,UAAU,CAAC,WAAW,EAAE,WAAW,EAAE;CACtC,EAAE,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;CACvC,GAAG,OAAO,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;CAC3D,GAAG;AACH;CACA,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE;CAC3B,GAAG,MAAM,IAAI,SAAS;CACtB,IAAI,2EAA2E;CAC/E,IAAI,CAAC;CACL,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;CACvD,EAAE;CACF;;CCz1BA,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD;CACe,MAAM,MAAM,CAAC;CAC5B,CAAC,WAAW,CAAC,OAAO,GAAG,EAAE,EAAE;CAC3B,EAAE,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC;CACnC,EAAE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;CAC9E,EAAE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;CACpB,EAAE,IAAI,CAAC,aAAa,GAAG,EAAE,CAAC;CAC1B,EAAE,IAAI,CAAC,2BAA2B,GAAG,EAAE,CAAC;CACxC,EAAE;AACF;CACA,CAAC,SAAS,CAAC,MAAM,EAAE;CACnB,EAAE,IAAI,MAAM,YAAY,WAAW,EAAE;CACrC,GAAG,OAAO,IAAI,CAAC,SAAS,CAAC;CACzB,IAAI,OAAO,EAAE,MAAM;CACnB,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ;CAC7B,IAAI,SAAS,EAAE,IAAI,CAAC,SAAS;CAC7B,IAAI,CAAC,CAAC;CACN,GAAG;AACH;CACA,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;CAC5C,GAAG,MAAM,IAAI,KAAK;CAClB,IAAI,sIAAsI;CAC1I,IAAI,CAAC;CACL,GAAG;AACH;CACA,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,uBAAuB,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;CACvF,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;CACjF,GAAG,CAAC,CAAC;AACL;CACA,EAAE,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE;CACtC;CACA,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;CACrC,GAAG;AACH;CACA,EAAE,IAAI,MAAM,CAAC,QAAQ,EAAE;CACvB,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,2BAA2B,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE;CAC5E,IAAI,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;CAClF,IAAI,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;CAC7F,IAAI,MAAM;CACV,IAAI,MAAM,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;CAC/F,IAAI,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,KAAK,YAAY,CAAC,OAAO,EAAE;CAC1D,KAAK,MAAM,IAAI,KAAK,CAAC,CAAC,+BAA+B,EAAE,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC;CAC/F,KAAK;CACL,IAAI;CACJ,GAAG;AACH;CACA,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;CAC5B,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE;CACtB,EAAE,IAAI,CAAC,SAAS,CAAC;CACjB,GAAG,OAAO,EAAE,IAAI,WAAW,CAAC,GAAG,CAAC;CAChC,GAAG,SAAS,EAAE,CAAC,OAAO,IAAI,OAAO,CAAC,SAAS,KAAK,EAAE;CAClD,GAAG,CAAC,CAAC;AACL;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,KAAK,GAAG;CACT,EAAE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC;CAC5B,GAAG,KAAK,EAAE,IAAI,CAAC,KAAK;CACpB,GAAG,SAAS,EAAE,IAAI,CAAC,SAAS;CAC5B,GAAG,CAAC,CAAC;AACL;CACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;CACnC,GAAG,MAAM,CAAC,SAAS,CAAC;CACpB,IAAI,QAAQ,EAAE,MAAM,CAAC,QAAQ;CAC7B,IAAI,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE;CACnC,IAAI,SAAS,EAAE,MAAM,CAAC,SAAS;CAC/B,IAAI,CAAC,CAAC;CACN,GAAG,CAAC,CAAC;AACL;CACA,EAAE,OAAO,MAAM,CAAC;CAChB,EAAE;AACF;CACA,CAAC,kBAAkB,CAAC,OAAO,GAAG,EAAE,EAAE;CAClC,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;CACnB,EAAE,IAAI,mBAAmB,GAAG,SAAS,CAAC;CACtC,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;CACnC,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,KAAK;CAC7D,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;CAChD,IAAI,CAAC,CAAC;CACN,GAAG,CAAC,CAAC;AACL;CACA,EAAE,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/C;CACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;CAClB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;CAChC,GAAG;AACH;CACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;CACtC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE;CACd,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;CACrC,IAAI;AACJ;CACA,GAAG,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;CAChG,GAAG,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC;CACtC,GAAG,MAAM,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACnD;CACA,GAAG,IAAI,WAAW,CAAC,KAAK,EAAE;CAC1B,IAAI,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;CACxC,IAAI;AACJ;CACA,GAAG,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,KAAK;CAC9C,IAAI,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACpC;CACA,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1D;CACA,IAAI,IAAI,MAAM,CAAC,QAAQ,EAAE;CACzB,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;CACvB,MAAM,QAAQ,CAAC,OAAO;CACtB,OAAO,WAAW;CAClB,OAAO,KAAK,CAAC,OAAO;CACpB,OAAO,GAAG;CACV,OAAO,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;CAC3D,OAAO,CAAC;CACR,MAAM,MAAM;CACZ,MAAM,QAAQ,CAAC,gBAAgB;CAC/B,OAAO,WAAW;CAClB,OAAO,KAAK;CACZ,OAAO,WAAW,CAAC,QAAQ;CAC3B,OAAO,GAAG;CACV,OAAO,WAAW,CAAC,kBAAkB;CACrC,OAAO,CAAC;CACR,MAAM;CACN,KAAK,MAAM;CACX,KAAK,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;CACrC,KAAK;AACL;CACA,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;CAC1D,IAAI,CAAC,CAAC;AACN;CACA,GAAG,IAAI,WAAW,CAAC,KAAK,EAAE;CAC1B,IAAI,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;CACxC,IAAI;AACJ;CACA,GAAG,IAAI,MAAM,CAAC,UAAU,IAAI,WAAW,KAAK,CAAC,CAAC,EAAE;CAChD,IAAI,IAAI,mBAAmB,KAAK,SAAS,EAAE;CAC3C,KAAK,mBAAmB,GAAG,EAAE,CAAC;CAC9B,KAAK;CACL,IAAI,mBAAmB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;CAC1C,IAAI;CACJ,GAAG,CAAC,CAAC;AACL;CACA,EAAE,OAAO;CACT,GAAG,IAAI,EAAE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,SAAS;CACrE,GAAG,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK;CAC/C,IAAI,OAAO,OAAO,CAAC,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC;CAC3F,IAAI,CAAC;CACL,GAAG,cAAc,EAAE,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK;CACtD,IAAI,OAAO,OAAO,CAAC,cAAc,GAAG,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;CAC1D,IAAI,CAAC;CACL,GAAG,KAAK;CACR,GAAG,QAAQ,EAAE,QAAQ,CAAC,GAAG;CACzB,GAAG,mBAAmB;CACtB,GAAG,CAAC;CACJ,EAAE;AACF;CACA,CAAC,WAAW,CAAC,OAAO,EAAE;CACtB,EAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;CACzD,EAAE;AACF;CACA,CAAC,eAAe,GAAG;CACnB,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAChC;CACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;CACnC,GAAG,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,mBAAmB,EAAE,CAAC;AAC1D;CACA,GAAG,IAAI,SAAS,KAAK,IAAI,EAAE,OAAO;AAClC;CACA,GAAG,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,kBAAkB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;CACzE,GAAG,kBAAkB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;CACtC,GAAG,CAAC,CAAC;AACL;CACA,EAAE;CACF,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK;CAClD,IAAI,OAAO,kBAAkB,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC,CAAC,CAAC,CAAC;CACzD,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;CAChB,IAAI;CACJ,EAAE;AACF;CACA,CAAC,MAAM,CAAC,SAAS,EAAE;CACnB,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE;CACzB,GAAG,SAAS,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;CACtC,GAAG;AACH;CACA,EAAE,IAAI,SAAS,KAAK,EAAE,EAAE,OAAO,IAAI,CAAC;AACpC;CACA,EAAE,IAAI,eAAe,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;AACrE;CACA,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;CACtC,GAAG,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;CACxF,GAAG,MAAM,WAAW,GAAG,eAAe,KAAK,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9E;CACA,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE;CACpC,IAAI,OAAO,EAAE,MAAM,CAAC,qBAAqB;CACzC,IAAI,WAAW;CACf,IAAI,CAAC,CAAC;AACN;CACA,GAAG,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC;CACxD,GAAG,CAAC,CAAC;AACL;CACA,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE;CAClB,GAAG,IAAI,CAAC,KAAK;CACb,IAAI,SAAS;CACb,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK;CACrD,KAAK,OAAO,KAAK,GAAG,CAAC,GAAG,SAAS,GAAG,KAAK,GAAG,KAAK,CAAC;CAClD,KAAK,CAAC,CAAC;CACP,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,OAAO,CAAC,GAAG,EAAE;CACd,EAAE,IAAI,CAAC,KAAK,GAAG,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC;CAChC,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,QAAQ,GAAG;CACZ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO;CAC3B,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK;CACvB,IAAI,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,SAAS,GAAG,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;CACzF,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,EAAE,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;AACrE;CACA,IAAI,OAAO,GAAG,CAAC;CACf,IAAI,CAAC;CACL,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;AACb;CACA,EAAE,OAAO,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;CAC3B,EAAE;AACF;CACA,CAAC,OAAO,GAAG;CACX,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,KAAK,CAAC;CAC3D,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,OAAO,KAAK,CAAC;CAC7E,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,MAAM,GAAG;CACV,EAAE,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM;CAC5B,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE;CACvD,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM;CACpB,GAAG,CAAC;CACJ,EAAE;AACF;CACA,CAAC,SAAS,GAAG;CACb,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;CAC/B,EAAE;AACF;CACA,CAAC,IAAI,CAAC,QAAQ,EAAE;CAChB,EAAE,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;CACpD,EAAE;AACF;CACA,CAAC,SAAS,CAAC,QAAQ,EAAE;CACrB,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,GAAG,IAAI,QAAQ,IAAI,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;CACzD,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1C;CACA,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;CACnB,GAAG,IAAI,MAAM,CAAC;CACd,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AACb;CACA,GAAG,GAAG;CACN,IAAI,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CAC/B,IAAI,IAAI,CAAC,MAAM,EAAE;CACjB,KAAK,MAAM;CACX,KAAK;CACL,IAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;CACxD,GAAG;AACH;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;AACF;CACA,CAAC,OAAO,CAAC,QAAQ,EAAE;CACnB,EAAE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACpD;CACA,EAAE,IAAI,MAAM,CAAC;CACb,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;AAClC;CACA,EAAE,GAAG;CACL,GAAG,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CAC9B,GAAG,IAAI,CAAC,MAAM,EAAE;CAChB,IAAI,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;CAC5C,IAAI,MAAM;CACV,IAAI;CACJ,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;AACrD;CACA,EAAE,OAAO,IAAI,CAAC;CACd,EAAE;CACF;;CCpSA,WAAW,CAAC,MAAM,GAAG,MAAM,CAAC;CAC5B,WAAW,CAAC,SAAS,GAAG,SAAS,CAAC;CAClC,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC;;;;;;;;","x_google_ignoreList":[2]} \ No newline at end of file diff --git a/web/node_modules/magic-string/package.json b/web/node_modules/magic-string/package.json new file mode 100644 index 0000000000000000000000000000000000000000..95d32038a7ce03ac08323871e2d3828ba8665f57 --- /dev/null +++ b/web/node_modules/magic-string/package.json @@ -0,0 +1,64 @@ +{ + "name": "magic-string", + "version": "0.30.7", + "description": "Modify strings, generate sourcemaps", + "keywords": [ + "string", + "string manipulation", + "sourcemap", + "templating", + "transpilation" + ], + "repository": "https://github.com/rich-harris/magic-string", + "license": "MIT", + "author": "Rich Harris", + "main": "./dist/magic-string.cjs.js", + "module": "./dist/magic-string.es.mjs", + "jsnext:main": "./dist/magic-string.es.mjs", + "types": "./dist/magic-string.cjs.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": "./dist/magic-string.es.mjs", + "require": "./dist/magic-string.cjs.js" + } + }, + "files": [ + "dist/*", + "index.d.ts", + "README.md" + ], + "scripts": { + "build": "rollup -c && cp ./src/index.d.ts ./dist/magic-string.es.d.mts && cp ./src/index.d.ts ./dist/magic-string.cjs.d.ts", + "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", + "format": "prettier --single-quote --print-width 100 --use-tabs --write src/*.js src/**/*.js", + "lint": "eslint src test && publint", + "prepare": "npm run build", + "prepublishOnly": "npm run lint && rm -rf dist && npm test", + "release": "bumpp -x \"npm run changelog\" --all --commit --tag --push && npm publish", + "pretest": "npm run build", + "test": "mocha", + "bench": "npm run build && node benchmark/index.mjs", + "watch": "rollup -cw" + }, + "devDependencies": { + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^5.0.5", + "benchmark": "^2.1.4", + "bumpp": "^9.3.0", + "conventional-changelog-cli": "^3.0.0", + "eslint": "^8.56.0", + "mocha": "^10.2.0", + "prettier": "^3.2.4", + "publint": "^0.2.7", + "rollup": "^3.28.0", + "source-map-js": "^1.0.2", + "source-map-support": "^0.5.21" + }, + "engines": { + "node": ">=12" + }, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + } +} diff --git a/web/node_modules/merge-stream/LICENSE b/web/node_modules/merge-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..94a4c0a0764dd50ca8a7de95d17471ef22b8cedf --- /dev/null +++ b/web/node_modules/merge-stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Stephen Sugden (stephensugden.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/web/node_modules/merge-stream/README.md b/web/node_modules/merge-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0d54841152d2c9422194e7b9930a07945ed97c9c --- /dev/null +++ b/web/node_modules/merge-stream/README.md @@ -0,0 +1,78 @@ +# merge-stream + +Merge (interleave) a bunch of streams. + +[![build status](https://secure.travis-ci.org/grncdr/merge-stream.svg?branch=master)](http://travis-ci.org/grncdr/merge-stream) + +## Synopsis + +```javascript +var stream1 = new Stream(); +var stream2 = new Stream(); + +var merged = mergeStream(stream1, stream2); + +var stream3 = new Stream(); +merged.add(stream3); +merged.isEmpty(); +//=> false +``` + +## Description + +This is adapted from [event-stream](https://github.com/dominictarr/event-stream) separated into a new module, using Streams3. + +## API + +### `mergeStream` + +Type: `function` + +Merges an arbitrary number of streams. Returns a merged stream. + +#### `merged.add` + +A method to dynamically add more sources to the stream. The argument supplied to `add` can be either a source or an array of sources. + +#### `merged.isEmpty` + +A method that tells you if the merged stream is empty. + +When a stream is "empty" (aka. no sources were added), it could not be returned to a gulp task. + +So, we could do something like this: + +```js +stream = require('merge-stream')(); +// Something like a loop to add some streams to the merge stream +// stream.add(streamA); +// stream.add(streamB); +return stream.isEmpty() ? null : stream; +``` + +## Gulp example + +An example use case for **merge-stream** is to combine parts of a task in a project's **gulpfile.js** like this: + +```js +const gulp = require('gulp'); +const htmlValidator = require('gulp-w3c-html-validator'); +const jsHint = require('gulp-jshint'); +const mergeStream = require('merge-stream'); + +function lint() { + return mergeStream( + gulp.src('src/*.html') + .pipe(htmlValidator()) + .pipe(htmlValidator.reporter()), + gulp.src('src/*.js') + .pipe(jsHint()) + .pipe(jsHint.reporter()) + ); +} +gulp.task('lint', lint); +``` + +## License + +MIT diff --git a/web/node_modules/merge-stream/index.js b/web/node_modules/merge-stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b1a9e1a02e202baa4e2e0d5e81e14c5c9fd981b4 --- /dev/null +++ b/web/node_modules/merge-stream/index.js @@ -0,0 +1,41 @@ +'use strict'; + +const { PassThrough } = require('stream'); + +module.exports = function (/*streams...*/) { + var sources = [] + var output = new PassThrough({objectMode: true}) + + output.setMaxListeners(0) + + output.add = add + output.isEmpty = isEmpty + + output.on('unpipe', remove) + + Array.prototype.slice.call(arguments).forEach(add) + + return output + + function add (source) { + if (Array.isArray(source)) { + source.forEach(add) + return this + } + + sources.push(source); + source.once('end', remove.bind(null, source)) + source.once('error', output.emit.bind(output, 'error')) + source.pipe(output, {end: false}) + return this + } + + function isEmpty () { + return sources.length == 0; + } + + function remove (source) { + sources = sources.filter(function (it) { return it !== source }) + if (!sources.length && output.readable) { output.end() } + } +} diff --git a/web/node_modules/merge-stream/package.json b/web/node_modules/merge-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a4c54ca50905aadb1341705310169c222c0c6ac --- /dev/null +++ b/web/node_modules/merge-stream/package.json @@ -0,0 +1,19 @@ +{ + "name": "merge-stream", + "version": "2.0.0", + "description": "Create a stream that emits events from multiple other streams", + "files": [ + "index.js" + ], + "scripts": { + "test": "istanbul cover test.js && istanbul check-cover --statements 100 --branches 100" + }, + "repository": "grncdr/merge-stream", + "author": "Stephen Sugden ", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "from2": "^2.0.3", + "istanbul": "^0.4.5" + } +} diff --git a/web/node_modules/mimic-fn/index.d.ts b/web/node_modules/mimic-fn/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a72e0a565ad36db14dc30fa244d4e18fb4dbf00 --- /dev/null +++ b/web/node_modules/mimic-fn/index.d.ts @@ -0,0 +1,52 @@ +export interface Options { + /** + Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error. + + @default false + */ + readonly ignoreNonConfigurable?: boolean; +} + +/** +Modifies the `to` function to mimic the `from` function. Returns the `to` function. + +`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied. + +`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment. + +@param to - Mimicking function. +@param from - Function to mimic. +@returns The modified `to` function. + +@example +``` +import mimicFunction from 'mimic-fn'; + +function foo() {} +foo.unicorn = '🦄'; + +function wrapper() { + return foo(); +} + +console.log(wrapper.name); +//=> 'wrapper' + +mimicFunction(wrapper, foo); + +console.log(wrapper.name); +//=> 'foo' + +console.log(wrapper.unicorn); +//=> '🦄' +``` +*/ +export default function mimicFunction< + ArgumentsType extends unknown[], + ReturnType, + FunctionType extends (...arguments: ArgumentsType) => ReturnType +>( + to: (...arguments: ArgumentsType) => ReturnType, + from: FunctionType, + options?: Options, +): FunctionType; diff --git a/web/node_modules/mimic-fn/index.js b/web/node_modules/mimic-fn/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bc9ef7d5663807501bef4a754aec7fc50528497b --- /dev/null +++ b/web/node_modules/mimic-fn/index.js @@ -0,0 +1,71 @@ +const copyProperty = (to, from, property, ignoreNonConfigurable) => { + // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. + // `Function#prototype` is non-writable and non-configurable so can never be modified. + if (property === 'length' || property === 'prototype') { + return; + } + + // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here. + if (property === 'arguments' || property === 'caller') { + return; + } + + const toDescriptor = Object.getOwnPropertyDescriptor(to, property); + const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); + + if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { + return; + } + + Object.defineProperty(to, property, fromDescriptor); +}; + +// `Object.defineProperty()` throws if the property exists, is not configurable and either: +// - one its descriptors is changed +// - it is non-writable and its value is changed +const canCopyProperty = function (toDescriptor, fromDescriptor) { + return toDescriptor === undefined || toDescriptor.configurable || ( + toDescriptor.writable === fromDescriptor.writable && + toDescriptor.enumerable === fromDescriptor.enumerable && + toDescriptor.configurable === fromDescriptor.configurable && + (toDescriptor.writable || toDescriptor.value === fromDescriptor.value) + ); +}; + +const changePrototype = (to, from) => { + const fromPrototype = Object.getPrototypeOf(from); + if (fromPrototype === Object.getPrototypeOf(to)) { + return; + } + + Object.setPrototypeOf(to, fromPrototype); +}; + +const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; + +const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); +const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); + +// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. +// We use `bind()` instead of a closure for the same reason. +// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. +const changeToString = (to, from, name) => { + const withName = name === '' ? '' : `with ${name.trim()}() `; + const newToString = wrappedToString.bind(null, withName, from.toString()); + // Ensure `to.toString.toString` is non-enumerable and has the same `same` + Object.defineProperty(newToString, 'name', toStringName); + Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString}); +}; + +export default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) { + const {name} = to; + + for (const property of Reflect.ownKeys(from)) { + copyProperty(to, from, property, ignoreNonConfigurable); + } + + changePrototype(to, from); + changeToString(to, from, name); + + return to; +} diff --git a/web/node_modules/mimic-fn/license b/web/node_modules/mimic-fn/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/mimic-fn/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/web/node_modules/mimic-fn/package.json b/web/node_modules/mimic-fn/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d010cdd4cb298d66856a8b4dee6230b61e96b314 --- /dev/null +++ b/web/node_modules/mimic-fn/package.json @@ -0,0 +1,45 @@ +{ + "name": "mimic-fn", + "version": "4.0.0", + "description": "Make a function mimic another one", + "license": "MIT", + "repository": "sindresorhus/mimic-fn", + "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": [ + "function", + "mimic", + "imitate", + "rename", + "copy", + "inherit", + "properties", + "name", + "func", + "fn", + "set", + "infer", + "change" + ], + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/web/node_modules/mimic-fn/readme.md b/web/node_modules/mimic-fn/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9f571cea2f0b7357bbd62fc2dedcdd88e2c9387b --- /dev/null +++ b/web/node_modules/mimic-fn/readme.md @@ -0,0 +1,90 @@ +mimic-fn +
+ +> Make a function mimic another one + +Useful when you wrap a function in another function and like to preserve the original name and other properties. + +## Install + +``` +$ npm install mimic-fn +``` + +## Usage + +```js +import mimicFunction from 'mimic-fn'; + +function foo() {} +foo.unicorn = '🦄'; + +function wrapper() { + return foo(); +} + +console.log(wrapper.name); +//=> 'wrapper' + +mimicFunction(wrapper, foo); + +console.log(wrapper.name); +//=> 'foo' + +console.log(wrapper.unicorn); +//=> '🦄' + +console.log(String(wrapper)); +//=> '/* Wrapped with wrapper() */\nfunction foo() {}' +``` + + +## API + +### mimicFunction(to, from, options?) + +Modifies the `to` function to mimic the `from` function. Returns the `to` function. + +`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied. + +`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment. + +#### to + +Type: `Function` + +Mimicking function. + +#### from + +Type: `Function` + +Function to mimic. + +#### options + +Type: `object` + +##### ignoreNonConfigurable + +Type: `boolean`\ +Default: `false` + +Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error. + +## Related + +- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function +- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name and other properties + +--- + +
+ + 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/web/node_modules/mlly/LICENSE b/web/node_modules/mlly/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e739abce461d8b2899aaec6529a4af24a417e0fc --- /dev/null +++ b/web/node_modules/mlly/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pooya Parsa + +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/web/node_modules/mlly/README.md b/web/node_modules/mlly/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5000d87d9c153a2603cd9131ab7b25fe53241f5b --- /dev/null +++ b/web/node_modules/mlly/README.md @@ -0,0 +1,561 @@ +# mlly + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![Codecov][codecov-src]][codecov-href] + +> Missing [ECMAScript module](https://nodejs.org/api/esm.html) utils for Node.js + +While ESM Modules are evolving in Node.js ecosystem, there are still +many required features that are still experimental or missing or needed to support ESM. This package tries to fill in the gap. + +## Usage + +Install npm package: + +```sh +# using yarn +yarn add mlly + +# using npm +npm install mlly +``` + +**Note:** Node.js 14+ is recommended. + +Import utils: + +```js +// ESM +import {} from "mlly"; + +// CommonJS +const {} = require("mlly"); +``` + +## Resolving ESM modules + +Several utilities to make ESM resolution easier: + +- Respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm) +- Exposed from Node.js implementation +- Windows paths normalized +- Supporting custom `extensions` and `/index` resolution +- Supporting custom `conditions` +- Support resolving from multiple paths or urls + +### `resolve` / `resolveSync` + +Resolve a module by respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm) +(using [wooorm/import-meta-resolve](https://github.com/wooorm/import-meta-resolve)). + +Additionally supports resolving without extension and `/index` similar to CommonJS. + +```js +import { resolve, resolveSync } from "mlly"; + +// file:///home/user/project/module.mjs +console.log(await resolve("./module.mjs", { url: import.meta.url })); +``` + +**Resolve options:** + +- `url`: URL or string to resolve from (default is `pwd()`) +- `conditions`: Array of conditions used for resolution algorithm (default is `['node', 'import']`) +- `extensions`: Array of additional extensions to check if import failed (default is `['.mjs', '.cjs', '.js', '.json']`) + +### `resolvePath` / `resolvePathSync` + +Similar to `resolve` but returns a path instead of URL using `fileURLToPath`. + +```js +import { resolvePath, resolveSync } from "mlly"; + +// /home/user/project/module.mjs +console.log(await resolvePath("./module.mjs", { url: import.meta.url })); +``` + +### `createResolve` + +Create a `resolve` function with defaults. + +```js +import { createResolve } from "mlly"; + +const _resolve = createResolve({ url: import.meta.url }); + +// file:///home/user/project/module.mjs +console.log(await _resolve("./module.mjs")); +``` + +**Example:** Ponyfill [import.meta.resolve](https://nodejs.org/api/esm.html#esm_import_meta_resolve_specifier_parent): + +```js +import { createResolve } from "mlly"; + +import.meta.resolve = createResolve({ url: import.meta.url }); +``` + +### `resolveImports` + +Resolve all static and dynamic imports with relative paths to full resolved path. + +```js +import { resolveImports } from "mlly"; + +// import foo from 'file:///home/user/project/bar.mjs' +console.log( + await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url }), +); +``` + +## Syntax Analyzes + +### `isValidNodeImport` + +Using various syntax detection and heuristics, this method can determine if import is a valid import or not to be imported using dynamic `import()` before hitting an error! + +When result is `false`, we usually need a to create a CommonJS require context or add specific rules to the bundler to transform dependency. + +```js +import { isValidNodeImport } from "mlly"; + +// If returns true, we are safe to use `import('some-lib')` +await isValidNodeImport("some-lib", {}); +``` + +**Algorithm:** + +- Check import protocol - If is `data:` return `true` (✅ valid) - If is not `node:`, `file:` or `data:`, return `false` ( + ❌ invalid) +- Resolve full path of import using Node.js [Resolution algorithm](https://nodejs.org/api/esm.html#resolution-algorithm) +- Check full path extension + - If is `.mjs`, `.cjs`, `.node` or `.wasm`, return `true` (✅ valid) + - If is not `.js`, return `false` (❌ invalid) + - If is matching known mixed syntax (`.esm.js`, `.es.js`, etc) return `false` ( + ❌ invalid) +- Read closest `package.json` file to resolve path +- If `type: 'module'` field is set, return `true` (✅ valid) +- Read source code of resolved path +- Try to detect CommonJS syntax usage + - If yes, return `true` (✅ valid) +- Try to detect ESM syntax usage + - if yes, return `false` ( + ❌ invalid) + +**Notes:** + +- There might be still edge cases algorithm cannot cover. It is designed with best-efforts. +- This method also allows using dynamic import of CommonJS libraries considering + Node.js has [Interoperability with CommonJS](https://nodejs.org/api/esm.html#interoperability-with-commonjs). + +### `hasESMSyntax` + +Detect if code, has usage of ESM syntax (Static `import`, ESM `export` and `import.meta` usage) + +```js +import { hasESMSyntax } from "mlly"; + +hasESMSyntax("export default foo = 123"); // true +``` + +### `hasCJSSyntax` + +Detect if code, has usage of CommonJS syntax (`exports`, `module.exports`, `require` and `global` usage) + +```js +import { hasCJSSyntax } from "mlly"; + +hasCJSSyntax("export default foo = 123"); // false +``` + +### `detectSyntax` + +Tests code against both CJS and ESM. + +`isMixed` indicates if both are detected! This is a common case with legacy packages exporting semi-compatible ESM syntax meant to be used by bundlers. + +```js +import { detectSyntax } from "mlly"; + +// { hasESM: true, hasCJS: true, isMixed: true } +detectSyntax('export default require("lodash")'); +``` + +## CommonJS Context + +### `createCommonJS` + +This utility creates a compatible CommonJS context that is missing in ECMAScript modules. + +```js +import { createCommonJS } from "mlly"; + +const { __dirname, __filename, require } = createCommonJS(import.meta.url); +``` + +Note: `require` and `require.resolve` implementation are lazy functions. [`createRequire`](https://nodejs.org/api/module.html#module_module_createrequire_filename) will be called on first usage. + +## Import/Export Analyzes + +Tools to quickly analyze ESM syntax and extract static `import`/`export` + +- Super fast Regex based implementation +- Handle most edge cases +- Find all static ESM imports +- Find all dynamic ESM imports +- Parse static import statement +- Find all named, declared and default exports + +### `findStaticImports` + +Find all static ESM imports. + +Example: + +```js +import { findStaticImports } from "mlly"; + +console.log( + findStaticImports(` +// Empty line +import foo, { bar /* foo */ } from 'baz' +`), +); +``` + +Outputs: + +```js +[ + { + type: "static", + imports: "foo, { bar /* foo */ } ", + specifier: "baz", + code: "import foo, { bar /* foo */ } from 'baz'", + start: 15, + end: 55, + }, +]; +``` + +### `parseStaticImport` + +Parse a dynamic ESM import statement previously matched by `findStaticImports`. + +Example: + +```js +import { findStaticImports, parseStaticImport } from "mlly"; + +const [match0] = findStaticImports(`import baz, { x, y as z } from 'baz'`); +console.log(parseStaticImport(match0)); +``` + +Outputs: + +```js +{ + type: 'static', + imports: 'baz, { x, y as z } ', + specifier: 'baz', + code: "import baz, { x, y as z } from 'baz'", + start: 0, + end: 36, + defaultImport: 'baz', + namespacedImport: undefined, + namedImports: { x: 'x', y: 'z' } +} +``` + +### `findDynamicImports` + +Find all dynamic ESM imports. + +Example: + +```js +import { findDynamicImports } from "mlly"; + +console.log( + findDynamicImports(` +const foo = await import('bar') +`), +); +``` + +### `findExports` + +```js +import { findExports } from "mlly"; + +console.log( + findExports(` +export const foo = 'bar' +export { bar, baz } +export default something +`), +); +``` + +Outputs: + +```js +[ + { + type: "declaration", + declaration: "const", + name: "foo", + code: "export const foo", + start: 1, + end: 17, + }, + { + type: "named", + exports: " bar, baz ", + code: "export { bar, baz }", + start: 26, + end: 45, + names: ["bar", "baz"], + }, + { type: "default", code: "export default ", start: 46, end: 61 }, +]; +``` + +### `findExportNames` + +Same as `findExports` but returns array of export names. + +```js +import { findExportNames } from "mlly"; + +// [ "foo", "bar", "baz", "default" ] +console.log( + findExportNames(` +export const foo = 'bar' +export { bar, baz } +export default something +`), +); +``` + +## `resolveModuleExportNames` + +Resolves module and reads its contents to extract possible export names using static analyzes. + +```js +import { resolveModuleExportNames } from "mlly"; + +// ["basename", "dirname", ... ] +console.log(await resolveModuleExportNames("mlly")); +``` + +## Evaluating Modules + +Set of utilities to evaluate ESM modules using `data:` imports + +- Automatic import rewrite to resolved path using static analyzes +- Allow bypass ESM Cache +- Stack-trace support +- `.json` loader + +### `evalModule` + +Transform and evaluates module code using dynamic imports. + +```js +import { evalModule } from "mlly"; + +await evalModule(`console.log("Hello World!")`); + +await evalModule( + ` + import { reverse } from './utils.mjs' + console.log(reverse('!emosewa si sj')) +`, + { url: import.meta.url }, +); +``` + +**Options:** + +- all `resolve` options +- `url`: File URL + +### `loadModule` + +Dynamically loads a module by evaluating source code. + +```js +import { loadModule } from "mlly"; + +await loadModule("./hello.mjs", { url: import.meta.url }); +``` + +Options are same as `evalModule`. + +### `transformModule` + +- Resolves all relative imports will be resolved +- All usages of `import.meta.url` will be replaced with `url` or `from` option + +```js +import { transformModule } from "mlly"; +console.log(transformModule(`console.log(import.meta.url)`), { + url: "test.mjs", +}); +``` + +Options are same as `evalModule`. + +## Other Utils + +### `fileURLToPath` + +Similar to [url.fileURLToPath](https://nodejs.org/api/url.html#url_url_fileurltopath_url) but also converts windows backslash `\` to unix slash `/` and handles if input is already a path. + +```js +import { fileURLToPath } from "mlly"; + +// /foo/bar.js +console.log(fileURLToPath("file:///foo/bar.js")); + +// C:/path +console.log(fileURLToPath("file:///C:/path/")); +``` + +### `pathToFileURL` + +Similar to [url.pathToFileURL](https://nodejs.org/api/url.html#urlpathtofileurlpath) but also handles `URL` input and returns a **string** with `file://` protocol. + +```js +import { pathToFileURL } from "mlly"; + +// /foo/bar.js +console.log(pathToFileURL("foo/bar.js")); + +// C:/path +console.log(pathToFileURL("C:\\path")); +``` + +### `normalizeid` + +Ensures id has either of `node:`, `data:`, `http:`, `https:` or `file:` protocols. + +```js +import { ensureProtocol } from "mlly"; + +// file:///foo/bar.js +console.log(normalizeid("/foo/bar.js")); +``` + +### `loadURL` + +Read source contents of a URL. (currently only file protocol supported) + +```js +import { resolve, loadURL } from "mlly"; + +const url = await resolve("./index.mjs", { url: import.meta.url }); +console.log(await loadURL(url)); +``` + +### `toDataURL` + +Convert code to [`data:`](https://nodejs.org/api/esm.html#esm_data_imports) URL using base64 encoding. + +```js +import { toDataURL } from "mlly"; + +console.log( + toDataURL(` + // This is an example + console.log('Hello world') +`), +); +``` + +### `interopDefault` + +Return the default export of a module at the top-level, alongside any other named exports. + +```js +// Assuming the shape { default: { foo: 'bar' }, baz: 'qux' } +import myModule from "my-module"; + +// Returns { foo: 'bar', baz: 'qux' } +console.log(interopDefault(myModule)); +``` + +**Options:** + +- `preferNamespace`: In case that `default` value exists but is not extendable (when is string for example), return input as-is (default is `false`, meaning `default`'s value is prefered even if cannot be extended) + +### `sanitizeURIComponent` + +Replace reserved characters from a segment of URI to make it compatible with [rfc2396](https://datatracker.ietf.org/doc/html/rfc2396). + +```js +import { sanitizeURIComponent } from "mlly"; + +// foo_bar +console.log(sanitizeURIComponent(`foo:bar`)); +``` + +### `sanitizeFilePath` + +Sanitize each path of a file name or path with `sanitizeURIComponent` for URI compatibility. + +```js +import { sanitizeFilePath } from "mlly"; + +// C:/te_st/_...slug_.jsx' +console.log(sanitizeFilePath("C:\\te#st\\[...slug].jsx")); +``` + +### `parseNodeModulePath` + +Parses an absolute file path in `node_modules` to three segments: + +- `dir`: Path to main directory of package +- `name`: Package name +- `subpath`: The optional package subpath + +It returns an empty object (with partial keys) if parsing fails. + +```js +import { parseNodeModulePath } from "mlly"; + +// dir: "/src/a/node_modules/" +// name: "lib" +// subpath: "./dist/index.mjs" +const { dir, name, subpath } = parseNodeModulePath( + "/src/a/node_modules/lib/dist/index.mjs", +); +``` + +### `lookupNodeModuleSubpath` + +Parses an absolute file path in `node_modules` and tries to reverse lookup (or guess) the original package exports subpath for it. + +```js +import { lookupNodeModuleSubpath } from "mlly"; + +// subpath: "./utils" +const subpath = lookupNodeModuleSubpath( + "/src/a/node_modules/lib/dist/utils.mjs", +); +``` + +## License + +[MIT](./LICENSE) - Made with 💛 + + + +[npm-version-src]: https://img.shields.io/npm/v/mlly?style=flat&colorA=18181B&colorB=F0DB4F +[npm-version-href]: https://npmjs.com/package/mlly +[npm-downloads-src]: https://img.shields.io/npm/dm/mlly?style=flat&colorA=18181B&colorB=F0DB4F +[npm-downloads-href]: https://npmjs.com/package/mlly +[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/mlly/main?style=flat&colorA=18181B&colorB=F0DB4F +[codecov-href]: https://codecov.io/gh/unjs/mlly diff --git a/web/node_modules/mlly/dist/index.cjs b/web/node_modules/mlly/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..33673f7bedd5d68f056ce6d2ad2fe7f4fa792378 --- /dev/null +++ b/web/node_modules/mlly/dist/index.cjs @@ -0,0 +1,2671 @@ +'use strict'; + +const acorn = require('acorn'); +const node_module = require('node:module'); +const fs = require('node:fs'); +const ufo = require('ufo'); +const pathe = require('pathe'); +const pkgTypes = require('pkg-types'); +const node_url = require('node:url'); +const assert = require('node:assert'); +const process$1 = require('node:process'); +const path = require('node:path'); +const v8 = require('node:v8'); +const node_util = require('node:util'); + +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } + +const fs__default = /*#__PURE__*/_interopDefaultCompat(fs); +const assert__default = /*#__PURE__*/_interopDefaultCompat(assert); +const process__default = /*#__PURE__*/_interopDefaultCompat(process$1); +const path__default = /*#__PURE__*/_interopDefaultCompat(path); +const v8__default = /*#__PURE__*/_interopDefaultCompat(v8); + +const BUILTIN_MODULES = new Set(node_module.builtinModules); +function normalizeSlash(path) { + return path.replace(/\\/g, "/"); +} +function isObject(value) { + return value !== null && typeof value === "object"; +} +function matchAll(regex, string, addition) { + const matches = []; + for (const match of string.matchAll(regex)) { + matches.push({ + ...addition, + ...match.groups, + code: match[0], + start: match.index, + end: (match.index || 0) + match[0].length + }); + } + return matches; +} +function clearImports(imports) { + return (imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " "); +} +function getImportNames(cleanedImports) { + const topLevelImports = cleanedImports.replace(/{([^}]*)}/, ""); + const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1]; + const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0; + return { + namespacedImport, + defaultImport + }; +} + +/** + * @typedef ErrnoExceptionFields + * @property {number | undefined} [errnode] + * @property {string | undefined} [code] + * @property {string | undefined} [path] + * @property {string | undefined} [syscall] + * @property {string | undefined} [url] + * + * @typedef {Error & ErrnoExceptionFields} ErrnoException + */ + + +const own$1 = {}.hasOwnProperty; + +const classRegExp = /^([A-Z][a-z\d]*)+$/; +// Sorted by a rough estimate on most frequently used entries. +const kTypes = new Set([ + 'string', + 'function', + 'number', + 'object', + // Accept 'Function' and 'Object' as alternative to the lower cased version. + 'Function', + 'Object', + 'boolean', + 'bigint', + 'symbol' +]); + +const codes = {}; + +/** + * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'. + * We cannot use Intl.ListFormat because it's not available in + * --without-intl builds. + * + * @param {Array} array + * An array of strings. + * @param {string} [type] + * The list type to be inserted before the last element. + * @returns {string} + */ +function formatList(array, type = 'and') { + return array.length < 3 + ? array.join(` ${type} `) + : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}` +} + +/** @type {Map} */ +const messages = new Map(); +const nodeInternalPrefix = '__node_internal_'; +/** @type {number} */ +let userStackTraceLimit; + +codes.ERR_INVALID_ARG_TYPE = createError( + 'ERR_INVALID_ARG_TYPE', + /** + * @param {string} name + * @param {Array | string} expected + * @param {unknown} actual + */ + (name, expected, actual) => { + assert__default(typeof name === 'string', "'name' must be a string"); + if (!Array.isArray(expected)) { + expected = [expected]; + } + + let message = 'The '; + if (name.endsWith(' argument')) { + // For cases like 'first argument' + message += `${name} `; + } else { + const type = name.includes('.') ? 'property' : 'argument'; + message += `"${name}" ${type} `; + } + + message += 'must be '; + + /** @type {Array} */ + const types = []; + /** @type {Array} */ + const instances = []; + /** @type {Array} */ + const other = []; + + for (const value of expected) { + assert__default( + typeof value === 'string', + 'All expected entries have to be of type string' + ); + + if (kTypes.has(value)) { + types.push(value.toLowerCase()); + } else if (classRegExp.exec(value) === null) { + assert__default( + value !== 'object', + 'The value "object" should be written as "Object"' + ); + other.push(value); + } else { + instances.push(value); + } + } + + // Special handle `object` in case other instances are allowed to outline + // the differences between each other. + if (instances.length > 0) { + const pos = types.indexOf('object'); + if (pos !== -1) { + types.slice(pos, 1); + instances.push('Object'); + } + } + + if (types.length > 0) { + message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList( + types, + 'or' + )}`; + if (instances.length > 0 || other.length > 0) message += ' or '; + } + + if (instances.length > 0) { + message += `an instance of ${formatList(instances, 'or')}`; + if (other.length > 0) message += ' or '; + } + + if (other.length > 0) { + if (other.length > 1) { + message += `one of ${formatList(other, 'or')}`; + } else { + if (other[0].toLowerCase() !== other[0]) message += 'an '; + message += `${other[0]}`; + } + } + + message += `. Received ${determineSpecificType(actual)}`; + + return message + }, + TypeError +); + +codes.ERR_INVALID_MODULE_SPECIFIER = createError( + 'ERR_INVALID_MODULE_SPECIFIER', + /** + * @param {string} request + * @param {string} reason + * @param {string} [base] + */ + (request, reason, base = undefined) => { + return `Invalid module "${request}" ${reason}${ + base ? ` imported from ${base}` : '' + }` + }, + TypeError +); + +codes.ERR_INVALID_PACKAGE_CONFIG = createError( + 'ERR_INVALID_PACKAGE_CONFIG', + /** + * @param {string} path + * @param {string} [base] + * @param {string} [message] + */ + (path, base, message) => { + return `Invalid package config ${path}${ + base ? ` while importing ${base}` : '' + }${message ? `. ${message}` : ''}` + }, + Error +); + +codes.ERR_INVALID_PACKAGE_TARGET = createError( + 'ERR_INVALID_PACKAGE_TARGET', + /** + * @param {string} pkgPath + * @param {string} key + * @param {unknown} target + * @param {boolean} [isImport=false] + * @param {string} [base] + */ + (pkgPath, key, target, isImport = false, base = undefined) => { + const relError = + typeof target === 'string' && + !isImport && + target.length > 0 && + !target.startsWith('./'); + if (key === '.') { + assert__default(isImport === false); + return ( + `Invalid "exports" main target ${JSON.stringify(target)} defined ` + + `in the package config ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }${relError ? '; targets must start with "./"' : ''}` + ) + } + + return `Invalid "${ + isImport ? 'imports' : 'exports' + }" target ${JSON.stringify( + target + )} defined for '${key}' in the package config ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }${relError ? '; targets must start with "./"' : ''}` + }, + Error +); + +codes.ERR_MODULE_NOT_FOUND = createError( + 'ERR_MODULE_NOT_FOUND', + /** + * @param {string} path + * @param {string} base + * @param {boolean} [exactUrl] + */ + (path, base, exactUrl = false) => { + return `Cannot find ${ + exactUrl ? 'module' : 'package' + } '${path}' imported from ${base}` + }, + Error +); + +codes.ERR_NETWORK_IMPORT_DISALLOWED = createError( + 'ERR_NETWORK_IMPORT_DISALLOWED', + "import of '%s' by %s is not supported: %s", + Error +); + +codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError( + 'ERR_PACKAGE_IMPORT_NOT_DEFINED', + /** + * @param {string} specifier + * @param {string} packagePath + * @param {string} base + */ + (specifier, packagePath, base) => { + return `Package import specifier "${specifier}" is not defined${ + packagePath ? ` in package ${packagePath}package.json` : '' + } imported from ${base}` + }, + TypeError +); + +codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + /** + * @param {string} pkgPath + * @param {string} subpath + * @param {string} [base] + */ + (pkgPath, subpath, base = undefined) => { + if (subpath === '.') + return `No "exports" main defined in ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }` + return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }` + }, + Error +); + +codes.ERR_UNSUPPORTED_DIR_IMPORT = createError( + 'ERR_UNSUPPORTED_DIR_IMPORT', + "Directory import '%s' is not supported " + + 'resolving ES modules imported from %s', + Error +); + +codes.ERR_UNKNOWN_FILE_EXTENSION = createError( + 'ERR_UNKNOWN_FILE_EXTENSION', + /** + * @param {string} ext + * @param {string} path + */ + (ext, path) => { + return `Unknown file extension "${ext}" for ${path}` + }, + TypeError +); + +codes.ERR_INVALID_ARG_VALUE = createError( + 'ERR_INVALID_ARG_VALUE', + /** + * @param {string} name + * @param {unknown} value + * @param {string} [reason='is invalid'] + */ + (name, value, reason = 'is invalid') => { + let inspected = node_util.inspect(value); + + if (inspected.length > 128) { + inspected = `${inspected.slice(0, 128)}...`; + } + + const type = name.includes('.') ? 'property' : 'argument'; + + return `The ${type} '${name}' ${reason}. Received ${inspected}` + }, + TypeError + // Note: extra classes have been shaken out. + // , RangeError +); + +/** + * Utility function for registering the error codes. Only used here. Exported + * *only* to allow for testing. + * @param {string} sym + * @param {MessageFunction | string} value + * @param {ErrorConstructor} def + * @returns {new (...args: Array) => Error} + */ +function createError(sym, value, def) { + // Special case for SystemError that formats the error message differently + // The SystemErrors only have SystemError as their base classes. + messages.set(sym, value); + + return makeNodeErrorWithCode(def, sym) +} + +/** + * @param {ErrorConstructor} Base + * @param {string} key + * @returns {ErrorConstructor} + */ +function makeNodeErrorWithCode(Base, key) { + // @ts-expect-error It’s a Node error. + return NodeError + /** + * @param {Array} args + */ + function NodeError(...args) { + const limit = Error.stackTraceLimit; + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; + const error = new Base(); + // Reset the limit and setting the name property. + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; + const message = getMessage(key, args, error); + Object.defineProperties(error, { + // Note: no need to implement `kIsNodeError` symbol, would be hard, + // probably. + message: { + value: message, + enumerable: false, + writable: true, + configurable: true + }, + toString: { + /** @this {Error} */ + value() { + return `${this.name} [${key}]: ${this.message}` + }, + enumerable: false, + writable: true, + configurable: true + } + }); + + captureLargerStackTrace(error); + // @ts-expect-error It’s a Node error. + error.code = key; + return error + } +} + +/** + * @returns {boolean} + */ +function isErrorStackTraceLimitWritable() { + // Do no touch Error.stackTraceLimit as V8 would attempt to install + // it again during deserialization. + try { + // @ts-expect-error: not in types? + if (v8__default.startupSnapshot.isBuildingSnapshot()) { + return false + } + } catch {} + + const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); + if (desc === undefined) { + return Object.isExtensible(Error) + } + + return own$1.call(desc, 'writable') && desc.writable !== undefined + ? desc.writable + : desc.set !== undefined +} + +/** + * This function removes unnecessary frames from Node.js core errors. + * @template {(...args: unknown[]) => unknown} T + * @param {T} fn + * @returns {T} + */ +function hideStackFrames(fn) { + // We rename the functions that will be hidden to cut off the stacktrace + // at the outermost one + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, 'name', {value: hidden}); + return fn +} + +const captureLargerStackTrace = hideStackFrames( + /** + * @param {Error} error + * @returns {Error} + */ + // @ts-expect-error: fine + function (error) { + const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); + if (stackTraceLimitIsWritable) { + userStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Number.POSITIVE_INFINITY; + } + + Error.captureStackTrace(error); + + // Reset the limit + if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; + + return error + } +); + +/** + * @param {string} key + * @param {Array} args + * @param {Error} self + * @returns {string} + */ +function getMessage(key, args, self) { + const message = messages.get(key); + assert__default(message !== undefined, 'expected `message` to be found'); + + if (typeof message === 'function') { + assert__default( + message.length <= args.length, // Default options do not count. + `Code: ${key}; The provided arguments length (${args.length}) does not ` + + `match the required ones (${message.length}).` + ); + return Reflect.apply(message, self, args) + } + + const regex = /%[dfijoOs]/g; + let expectedLength = 0; + while (regex.exec(message) !== null) expectedLength++; + assert__default( + expectedLength === args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not ` + + `match the required ones (${expectedLength}).` + ); + if (args.length === 0) return message + + args.unshift(message); + return Reflect.apply(node_util.format, null, args) +} + +/** + * Determine the specific type of a value for type-mismatch errors. + * @param {unknown} value + * @returns {string} + */ +function determineSpecificType(value) { + if (value === null || value === undefined) { + return String(value) + } + + if (typeof value === 'function' && value.name) { + return `function ${value.name}` + } + + if (typeof value === 'object') { + if (value.constructor && value.constructor.name) { + return `an instance of ${value.constructor.name}` + } + + return `${node_util.inspect(value, {depth: -1})}` + } + + let inspected = node_util.inspect(value, {colors: false}); + + if (inspected.length > 28) { + inspected = `${inspected.slice(0, 25)}...`; + } + + return `type ${typeof value} (${inspected})` +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. +// Removed the native dependency. +// Also: no need to cache, we do that in resolve already. + + +const hasOwnProperty$1 = {}.hasOwnProperty; + +const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes; + +/** @type {Map} */ +const cache = new Map(); + +const reader = {read}; +const packageJsonReader = reader; + +/** + * @param {string} jsonPath + * @param {{specifier: URL | string, base?: URL}} options + * @returns {PackageConfig} + */ +function read(jsonPath, {base, specifier}) { + const existing = cache.get(jsonPath); + + if (existing) { + return existing + } + + /** @type {string | undefined} */ + let string; + + try { + string = fs__default.readFileSync(path__default.toNamespacedPath(jsonPath), 'utf8'); + } catch (error) { + const exception = /** @type {ErrnoException} */ (error); + + if (exception.code !== 'ENOENT') { + throw exception + } + } + + /** @type {PackageConfig} */ + const result = { + exists: false, + pjsonPath: jsonPath, + main: undefined, + name: undefined, + type: 'none', // Ignore unknown types for forwards compatibility + exports: undefined, + imports: undefined + }; + + if (string !== undefined) { + /** @type {Record} */ + let parsed; + + try { + parsed = JSON.parse(string); + } catch (error_) { + const cause = /** @type {ErrnoException} */ (error_); + const error = new ERR_INVALID_PACKAGE_CONFIG$1( + jsonPath, + (base ? `"${specifier}" from ` : '') + node_url.fileURLToPath(base || specifier), + cause.message + ); + // @ts-expect-error: fine. + error.cause = cause; + throw error + } + + result.exists = true; + + if ( + hasOwnProperty$1.call(parsed, 'name') && + typeof parsed.name === 'string' + ) { + result.name = parsed.name; + } + + if ( + hasOwnProperty$1.call(parsed, 'main') && + typeof parsed.main === 'string' + ) { + result.main = parsed.main; + } + + if (hasOwnProperty$1.call(parsed, 'exports')) { + // @ts-expect-error: assume valid. + result.exports = parsed.exports; + } + + if (hasOwnProperty$1.call(parsed, 'imports')) { + // @ts-expect-error: assume valid. + result.imports = parsed.imports; + } + + // Ignore unknown types for forwards compatibility + if ( + hasOwnProperty$1.call(parsed, 'type') && + (parsed.type === 'commonjs' || parsed.type === 'module') + ) { + result.type = parsed.type; + } + } + + cache.set(jsonPath, result); + + return result +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. + + +/** + * @param {URL | string} resolved + * @returns {PackageConfig} + */ +function getPackageScopeConfig(resolved) { + let packageJSONUrl = new node_url.URL('package.json', resolved); + + while (true) { + const packageJSONPath = packageJSONUrl.pathname; + if (packageJSONPath.endsWith('node_modules/package.json')) { + break + } + + const packageConfig = packageJsonReader.read( + node_url.fileURLToPath(packageJSONUrl), + {specifier: resolved} + ); + + if (packageConfig.exists) { + return packageConfig + } + + const lastPackageJSONUrl = packageJSONUrl; + packageJSONUrl = new node_url.URL('../package.json', packageJSONUrl); + + // Terminates at root where ../package.json equals ../../package.json + // (can't just check "/package.json" for Windows support). + if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) { + break + } + } + + const packageJSONPath = node_url.fileURLToPath(packageJSONUrl); + + return { + pjsonPath: packageJSONPath, + exists: false, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + } +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. +// +// This file solves a circular dependency. +// In Node.js, `getPackageType` is in `resolve.js`. +// `resolve.js` imports `get-format.js`, which needs `getPackageType`. +// We split that up so that bundlers don’t fail. + + +/** + * @param {URL} url + * @returns {PackageType} + */ +function getPackageType(url) { + const packageConfig = getPackageScopeConfig(url); + return packageConfig.type +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. + + +const {ERR_UNKNOWN_FILE_EXTENSION} = codes; + +const hasOwnProperty = {}.hasOwnProperty; + +/** @type {Record} */ +const extensionFormatMap = { + // @ts-expect-error: hush. + __proto__: null, + '.cjs': 'commonjs', + '.js': 'module', + '.json': 'json', + '.mjs': 'module' +}; + +/** + * @param {string | null} mime + * @returns {string | null} + */ +function mimeToFormat(mime) { + if ( + mime && + /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime) + ) + return 'module' + if (mime === 'application/json') return 'json' + return null +} + +/** + * @callback ProtocolHandler + * @param {URL} parsed + * @param {{parentURL: string, source?: Buffer}} context + * @param {boolean} ignoreErrors + * @returns {string | null | void} + */ + +/** + * @type {Record} + */ +const protocolHandlers = { + // @ts-expect-error: hush. + __proto__: null, + 'data:': getDataProtocolModuleFormat, + 'file:': getFileProtocolModuleFormat, + 'http:': getHttpProtocolModuleFormat, + 'https:': getHttpProtocolModuleFormat, + 'node:'() { + return 'builtin' + } +}; + +/** + * @param {URL} parsed + */ +function getDataProtocolModuleFormat(parsed) { + const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec( + parsed.pathname + ) || [null, null, null]; + return mimeToFormat(mime) +} + +/** + * Returns the file extension from a URL. + * + * Should give similar result to + * `require('node:path').extname(require('node:url').fileURLToPath(url))` + * when used with a `file:` URL. + * + * @param {URL} url + * @returns {string} + */ +function extname(url) { + const pathname = url.pathname; + let index = pathname.length; + + while (index--) { + const code = pathname.codePointAt(index); + + if (code === 47 /* `/` */) { + return '' + } + + if (code === 46 /* `.` */) { + return pathname.codePointAt(index - 1) === 47 /* `/` */ + ? '' + : pathname.slice(index) + } + } + + return '' +} + +/** + * @type {ProtocolHandler} + */ +function getFileProtocolModuleFormat(url, _context, ignoreErrors) { + const ext = extname(url); + + if (ext === '.js') { + const packageType = getPackageType(url); + + if (packageType !== 'none') { + return packageType + } + + return 'commonjs' + } + + if (ext === '') { + const packageType = getPackageType(url); + + // Legacy behavior + if (packageType === 'none' || packageType === 'commonjs') { + return 'commonjs' + } + + // Note: we don’t implement WASM, so we don’t need + // `getFormatOfExtensionlessFile` from `formats`. + return 'module' + } + + const format = extensionFormatMap[ext]; + if (format) return format + + // Explicit undefined return indicates load hook should rerun format check + if (ignoreErrors) { + return undefined + } + + const filepath = node_url.fileURLToPath(url); + throw new ERR_UNKNOWN_FILE_EXTENSION(ext, filepath) +} + +function getHttpProtocolModuleFormat() { + // To do: HTTPS imports. +} + +/** + * @param {URL} url + * @param {{parentURL: string}} context + * @returns {string | null} + */ +function defaultGetFormatWithoutErrors(url, context) { + const protocol = url.protocol; + + if (!hasOwnProperty.call(protocolHandlers, protocol)) { + return null + } + + return protocolHandlers[protocol](url, context, true) || null +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. + + +const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace]; + +const { + ERR_NETWORK_IMPORT_DISALLOWED, + ERR_INVALID_MODULE_SPECIFIER, + ERR_INVALID_PACKAGE_CONFIG, + ERR_INVALID_PACKAGE_TARGET, + ERR_MODULE_NOT_FOUND, + ERR_PACKAGE_IMPORT_NOT_DEFINED, + ERR_PACKAGE_PATH_NOT_EXPORTED, + ERR_UNSUPPORTED_DIR_IMPORT +} = codes; + +const own = {}.hasOwnProperty; + +const invalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; +const deprecatedInvalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; +const invalidPackageNameRegEx = /^\.|%|\\/; +const patternRegEx = /\*/g; +const encodedSepRegEx = /%2f|%5c/i; +/** @type {Set} */ +const emittedPackageWarnings = new Set(); + +const doubleSlashRegEx = /[/\\]{2}/; + +/** + * + * @param {string} target + * @param {string} request + * @param {string} match + * @param {URL} packageJsonUrl + * @param {boolean} internal + * @param {URL} base + * @param {boolean} isTarget + */ +function emitInvalidSegmentDeprecation( + target, + request, + match, + packageJsonUrl, + internal, + base, + isTarget +) { + // @ts-expect-error: apparently it does exist, TS. + if (process__default.noDeprecation) { + return + } + + const pjsonPath = node_url.fileURLToPath(packageJsonUrl); + const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null; + process__default.emitWarning( + `Use of deprecated ${ + double ? 'double slash' : 'leading or trailing slash matching' + } resolving "${target}" for module ` + + `request "${request}" ${ + request === match ? '' : `matched to "${match}" ` + }in the "${ + internal ? 'imports' : 'exports' + }" field module resolution of the package at ${pjsonPath}${ + base ? ` imported from ${node_url.fileURLToPath(base)}` : '' + }.`, + 'DeprecationWarning', + 'DEP0166' + ); +} + +/** + * @param {URL} url + * @param {URL} packageJsonUrl + * @param {URL} base + * @param {string} [main] + * @returns {void} + */ +function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { + // @ts-expect-error: apparently it does exist, TS. + if (process__default.noDeprecation) { + return + } + + const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href}); + if (format !== 'module') return + const urlPath = node_url.fileURLToPath(url.href); + const pkgPath = node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)); + const basePath = node_url.fileURLToPath(base); + if (!main) { + process__default.emitWarning( + `No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${urlPath.slice( + pkgPath.length + )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, + 'DeprecationWarning', + 'DEP0151' + ); + } else if (path__default.resolve(pkgPath, main) !== urlPath) { + process__default.emitWarning( + `Package ${pkgPath} has a "main" field set to "${main}", ` + + `excluding the full filename and extension to the resolved file at "${urlPath.slice( + pkgPath.length + )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` + + 'deprecated for ES modules.', + 'DeprecationWarning', + 'DEP0151' + ); + } +} + +/** + * @param {string} path + * @returns {Stats} + */ +function tryStatSync(path) { + // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead. + try { + return fs.statSync(path) + } catch { + return new fs.Stats() + } +} + +/** + * Legacy CommonJS main resolution: + * 1. let M = pkg_url + (json main field) + * 2. TRY(M, M.js, M.json, M.node) + * 3. TRY(M/index.js, M/index.json, M/index.node) + * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) + * 5. NOT_FOUND + * + * @param {URL} url + * @returns {boolean} + */ +function fileExists(url) { + const stats = fs.statSync(url, {throwIfNoEntry: false}); + const isFile = stats ? stats.isFile() : undefined; + return isFile === null || isFile === undefined ? false : isFile +} + +/** + * @param {URL} packageJsonUrl + * @param {PackageConfig} packageConfig + * @param {URL} base + * @returns {URL} + */ +function legacyMainResolve(packageJsonUrl, packageConfig, base) { + /** @type {URL | undefined} */ + let guess; + if (packageConfig.main !== undefined) { + guess = new node_url.URL(packageConfig.main, packageJsonUrl); + // Note: fs check redundances will be handled by Descriptor cache here. + if (fileExists(guess)) return guess + + const tries = [ + `./${packageConfig.main}.js`, + `./${packageConfig.main}.json`, + `./${packageConfig.main}.node`, + `./${packageConfig.main}/index.js`, + `./${packageConfig.main}/index.json`, + `./${packageConfig.main}/index.node` + ]; + let i = -1; + + while (++i < tries.length) { + guess = new node_url.URL(tries[i], packageJsonUrl); + if (fileExists(guess)) break + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation( + guess, + packageJsonUrl, + base, + packageConfig.main + ); + return guess + } + // Fallthrough. + } + + const tries = ['./index.js', './index.json', './index.node']; + let i = -1; + + while (++i < tries.length) { + guess = new node_url.URL(tries[i], packageJsonUrl); + if (fileExists(guess)) break + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess + } + + // Not found. + throw new ERR_MODULE_NOT_FOUND( + node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)), + node_url.fileURLToPath(base) + ) +} + +/** + * @param {URL} resolved + * @param {URL} base + * @param {boolean} [preserveSymlinks] + * @returns {URL} + */ +function finalizeResolution(resolved, base, preserveSymlinks) { + if (encodedSepRegEx.exec(resolved.pathname) !== null) { + throw new ERR_INVALID_MODULE_SPECIFIER( + resolved.pathname, + 'must not include encoded "/" or "\\" characters', + node_url.fileURLToPath(base) + ) + } + + /** @type {string} */ + let filePath; + + try { + filePath = node_url.fileURLToPath(resolved); + } catch (error) { + const cause = /** @type {ErrnoException} */ (error); + Object.defineProperty(cause, 'input', {value: String(resolved)}); + Object.defineProperty(cause, 'module', {value: String(base)}); + throw cause + } + + const stats = tryStatSync( + filePath.endsWith('/') ? filePath.slice(-1) : filePath + ); + + if (stats.isDirectory()) { + const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, node_url.fileURLToPath(base)); + // @ts-expect-error Add this for `import.meta.resolve`. + error.url = String(resolved); + throw error + } + + if (!stats.isFile()) { + const error = new ERR_MODULE_NOT_FOUND( + filePath || resolved.pathname, + base && node_url.fileURLToPath(base), + true + ); + // @ts-expect-error Add this for `import.meta.resolve`. + error.url = String(resolved); + throw error + } + + if (!preserveSymlinks) { + const real = fs.realpathSync(filePath); + const {search, hash} = resolved; + resolved = node_url.pathToFileURL(real + (filePath.endsWith(path__default.sep) ? '/' : '')); + resolved.search = search; + resolved.hash = hash; + } + + return resolved +} + +/** + * @param {string} specifier + * @param {URL | undefined} packageJsonUrl + * @param {URL} base + * @returns {Error} + */ +function importNotDefined(specifier, packageJsonUrl, base) { + return new ERR_PACKAGE_IMPORT_NOT_DEFINED( + specifier, + packageJsonUrl && node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)), + node_url.fileURLToPath(base) + ) +} + +/** + * @param {string} subpath + * @param {URL} packageJsonUrl + * @param {URL} base + * @returns {Error} + */ +function exportsNotFound(subpath, packageJsonUrl, base) { + return new ERR_PACKAGE_PATH_NOT_EXPORTED( + node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)), + subpath, + base && node_url.fileURLToPath(base) + ) +} + +/** + * @param {string} request + * @param {string} match + * @param {URL} packageJsonUrl + * @param {boolean} internal + * @param {URL} [base] + * @returns {never} + */ +function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) { + const reason = `request is not a valid match in pattern "${match}" for the "${ + internal ? 'imports' : 'exports' + }" resolution of ${node_url.fileURLToPath(packageJsonUrl)}`; + throw new ERR_INVALID_MODULE_SPECIFIER( + request, + reason, + base && node_url.fileURLToPath(base) + ) +} + +/** + * @param {string} subpath + * @param {unknown} target + * @param {URL} packageJsonUrl + * @param {boolean} internal + * @param {URL} [base] + * @returns {Error} + */ +function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { + target = + typeof target === 'object' && target !== null + ? JSON.stringify(target, null, '') + : `${target}`; + + return new ERR_INVALID_PACKAGE_TARGET( + node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)), + subpath, + target, + internal, + base && node_url.fileURLToPath(base) + ) +} + +/** + * @param {string} target + * @param {string} subpath + * @param {string} match + * @param {URL} packageJsonUrl + * @param {URL} base + * @param {boolean} pattern + * @param {boolean} internal + * @param {boolean} isPathMap + * @param {Set | undefined} conditions + * @returns {URL} + */ +function resolvePackageTargetString( + target, + subpath, + match, + packageJsonUrl, + base, + pattern, + internal, + isPathMap, + conditions +) { + if (subpath !== '' && !pattern && target[target.length - 1] !== '/') + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + + if (!target.startsWith('./')) { + if (internal && !target.startsWith('../') && !target.startsWith('/')) { + let isURL = false; + + try { + new node_url.URL(target); + isURL = true; + } catch { + // Continue regardless of error. + } + + if (!isURL) { + const exportTarget = pattern + ? RegExpPrototypeSymbolReplace.call( + patternRegEx, + target, + () => subpath + ) + : target + subpath; + + return packageResolve(exportTarget, packageJsonUrl, conditions) + } + } + + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + } + + if (invalidSegmentRegEx.exec(target.slice(2)) !== null) { + if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) { + if (!isPathMap) { + const request = pattern + ? match.replace('*', () => subpath) + : match + subpath; + const resolvedTarget = pattern + ? RegExpPrototypeSymbolReplace.call( + patternRegEx, + target, + () => subpath + ) + : target; + emitInvalidSegmentDeprecation( + resolvedTarget, + request, + match, + packageJsonUrl, + internal, + base, + true + ); + } + } else { + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + } + } + + const resolved = new node_url.URL(target, packageJsonUrl); + const resolvedPath = resolved.pathname; + const packagePath = new node_url.URL('.', packageJsonUrl).pathname; + + if (!resolvedPath.startsWith(packagePath)) + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + + if (subpath === '') return resolved + + if (invalidSegmentRegEx.exec(subpath) !== null) { + const request = pattern + ? match.replace('*', () => subpath) + : match + subpath; + if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) { + if (!isPathMap) { + const resolvedTarget = pattern + ? RegExpPrototypeSymbolReplace.call( + patternRegEx, + target, + () => subpath + ) + : target; + emitInvalidSegmentDeprecation( + resolvedTarget, + request, + match, + packageJsonUrl, + internal, + base, + false + ); + } + } else { + throwInvalidSubpath(request, match, packageJsonUrl, internal, base); + } + } + + if (pattern) { + return new node_url.URL( + RegExpPrototypeSymbolReplace.call( + patternRegEx, + resolved.href, + () => subpath + ) + ) + } + + return new node_url.URL(subpath, resolved) +} + +/** + * @param {string} key + * @returns {boolean} + */ +function isArrayIndex(key) { + const keyNumber = Number(key); + if (`${keyNumber}` !== key) return false + return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff +} + +/** + * @param {URL} packageJsonUrl + * @param {unknown} target + * @param {string} subpath + * @param {string} packageSubpath + * @param {URL} base + * @param {boolean} pattern + * @param {boolean} internal + * @param {boolean} isPathMap + * @param {Set | undefined} conditions + * @returns {URL | null} + */ +function resolvePackageTarget( + packageJsonUrl, + target, + subpath, + packageSubpath, + base, + pattern, + internal, + isPathMap, + conditions +) { + if (typeof target === 'string') { + return resolvePackageTargetString( + target, + subpath, + packageSubpath, + packageJsonUrl, + base, + pattern, + internal, + isPathMap, + conditions + ) + } + + if (Array.isArray(target)) { + /** @type {Array} */ + const targetList = target; + if (targetList.length === 0) return null + + /** @type {ErrnoException | null | undefined} */ + let lastException; + let i = -1; + + while (++i < targetList.length) { + const targetItem = targetList[i]; + /** @type {URL | null} */ + let resolveResult; + try { + resolveResult = resolvePackageTarget( + packageJsonUrl, + targetItem, + subpath, + packageSubpath, + base, + pattern, + internal, + isPathMap, + conditions + ); + } catch (error) { + const exception = /** @type {ErrnoException} */ (error); + lastException = exception; + if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue + throw error + } + + if (resolveResult === undefined) continue + + if (resolveResult === null) { + lastException = null; + continue + } + + return resolveResult + } + + if (lastException === undefined || lastException === null) { + return null + } + + throw lastException + } + + if (typeof target === 'object' && target !== null) { + const keys = Object.getOwnPropertyNames(target); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + if (isArrayIndex(key)) { + throw new ERR_INVALID_PACKAGE_CONFIG( + node_url.fileURLToPath(packageJsonUrl), + base, + '"exports" cannot contain numeric property keys.' + ) + } + } + + i = -1; + + while (++i < keys.length) { + const key = keys[i]; + if (key === 'default' || (conditions && conditions.has(key))) { + // @ts-expect-error: indexable. + const conditionalTarget = /** @type {unknown} */ (target[key]); + const resolveResult = resolvePackageTarget( + packageJsonUrl, + conditionalTarget, + subpath, + packageSubpath, + base, + pattern, + internal, + isPathMap, + conditions + ); + if (resolveResult === undefined) continue + return resolveResult + } + } + + return null + } + + if (target === null) { + return null + } + + throw invalidPackageTarget( + packageSubpath, + target, + packageJsonUrl, + internal, + base + ) +} + +/** + * @param {unknown} exports + * @param {URL} packageJsonUrl + * @param {URL} base + * @returns {boolean} + */ +function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { + if (typeof exports === 'string' || Array.isArray(exports)) return true + if (typeof exports !== 'object' || exports === null) return false + + const keys = Object.getOwnPropertyNames(exports); + let isConditionalSugar = false; + let i = 0; + let j = -1; + while (++j < keys.length) { + const key = keys[j]; + const curIsConditionalSugar = key === '' || key[0] !== '.'; + if (i++ === 0) { + isConditionalSugar = curIsConditionalSugar; + } else if (isConditionalSugar !== curIsConditionalSugar) { + throw new ERR_INVALID_PACKAGE_CONFIG( + node_url.fileURLToPath(packageJsonUrl), + base, + '"exports" cannot contain some keys starting with \'.\' and some not.' + + ' The exports object must either be an object of package subpath keys' + + ' or an object of main entry condition name keys only.' + ) + } + } + + return isConditionalSugar +} + +/** + * @param {string} match + * @param {URL} pjsonUrl + * @param {URL} base + */ +function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { + // @ts-expect-error: apparently it does exist, TS. + if (process__default.noDeprecation) { + return + } + + const pjsonPath = node_url.fileURLToPath(pjsonUrl); + if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return + emittedPackageWarnings.add(pjsonPath + '|' + match); + process__default.emitWarning( + `Use of deprecated trailing slash pattern mapping "${match}" in the ` + + `"exports" field module resolution of the package at ${pjsonPath}${ + base ? ` imported from ${node_url.fileURLToPath(base)}` : '' + }. Mapping specifiers ending in "/" is no longer supported.`, + 'DeprecationWarning', + 'DEP0155' + ); +} + +/** + * @param {URL} packageJsonUrl + * @param {string} packageSubpath + * @param {Record} packageConfig + * @param {URL} base + * @param {Set | undefined} conditions + * @returns {URL} + */ +function packageExportsResolve( + packageJsonUrl, + packageSubpath, + packageConfig, + base, + conditions +) { + let exports = packageConfig.exports; + + if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) { + exports = {'.': exports}; + } + + if ( + own.call(exports, packageSubpath) && + !packageSubpath.includes('*') && + !packageSubpath.endsWith('/') + ) { + // @ts-expect-error: indexable. + const target = exports[packageSubpath]; + const resolveResult = resolvePackageTarget( + packageJsonUrl, + target, + '', + packageSubpath, + base, + false, + false, + false, + conditions + ); + if (resolveResult === null || resolveResult === undefined) { + throw exportsNotFound(packageSubpath, packageJsonUrl, base) + } + + return resolveResult + } + + let bestMatch = ''; + let bestMatchSubpath = ''; + const keys = Object.getOwnPropertyNames(exports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + const patternIndex = key.indexOf('*'); + + if ( + patternIndex !== -1 && + packageSubpath.startsWith(key.slice(0, patternIndex)) + ) { + // When this reaches EOL, this can throw at the top of the whole function: + // + // if (StringPrototypeEndsWith(packageSubpath, '/')) + // throwInvalidSubpath(packageSubpath) + // + // To match "imports" and the spec. + if (packageSubpath.endsWith('/')) { + emitTrailingSlashPatternDeprecation( + packageSubpath, + packageJsonUrl, + base + ); + } + + const patternTrailer = key.slice(patternIndex + 1); + + if ( + packageSubpath.length >= key.length && + packageSubpath.endsWith(patternTrailer) && + patternKeyCompare(bestMatch, key) === 1 && + key.lastIndexOf('*') === patternIndex + ) { + bestMatch = key; + bestMatchSubpath = packageSubpath.slice( + patternIndex, + packageSubpath.length - patternTrailer.length + ); + } + } + } + + if (bestMatch) { + // @ts-expect-error: indexable. + const target = /** @type {unknown} */ (exports[bestMatch]); + const resolveResult = resolvePackageTarget( + packageJsonUrl, + target, + bestMatchSubpath, + bestMatch, + base, + true, + false, + packageSubpath.endsWith('/'), + conditions + ); + + if (resolveResult === null || resolveResult === undefined) { + throw exportsNotFound(packageSubpath, packageJsonUrl, base) + } + + return resolveResult + } + + throw exportsNotFound(packageSubpath, packageJsonUrl, base) +} + +/** + * @param {string} a + * @param {string} b + */ +function patternKeyCompare(a, b) { + const aPatternIndex = a.indexOf('*'); + const bPatternIndex = b.indexOf('*'); + const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLengthA > baseLengthB) return -1 + if (baseLengthB > baseLengthA) return 1 + if (aPatternIndex === -1) return 1 + if (bPatternIndex === -1) return -1 + if (a.length > b.length) return -1 + if (b.length > a.length) return 1 + return 0 +} + +/** + * @param {string} name + * @param {URL} base + * @param {Set} [conditions] + * @returns {URL} + */ +function packageImportsResolve(name, base, conditions) { + if (name === '#' || name.startsWith('#/') || name.endsWith('/')) { + const reason = 'is not a valid internal imports specifier name'; + throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, node_url.fileURLToPath(base)) + } + + /** @type {URL | undefined} */ + let packageJsonUrl; + + const packageConfig = getPackageScopeConfig(base); + + if (packageConfig.exists) { + packageJsonUrl = node_url.pathToFileURL(packageConfig.pjsonPath); + const imports = packageConfig.imports; + if (imports) { + if (own.call(imports, name) && !name.includes('*')) { + const resolveResult = resolvePackageTarget( + packageJsonUrl, + imports[name], + '', + name, + base, + false, + true, + false, + conditions + ); + if (resolveResult !== null && resolveResult !== undefined) { + return resolveResult + } + } else { + let bestMatch = ''; + let bestMatchSubpath = ''; + const keys = Object.getOwnPropertyNames(imports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + const patternIndex = key.indexOf('*'); + + if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) { + const patternTrailer = key.slice(patternIndex + 1); + if ( + name.length >= key.length && + name.endsWith(patternTrailer) && + patternKeyCompare(bestMatch, key) === 1 && + key.lastIndexOf('*') === patternIndex + ) { + bestMatch = key; + bestMatchSubpath = name.slice( + patternIndex, + name.length - patternTrailer.length + ); + } + } + } + + if (bestMatch) { + const target = imports[bestMatch]; + const resolveResult = resolvePackageTarget( + packageJsonUrl, + target, + bestMatchSubpath, + bestMatch, + base, + true, + true, + false, + conditions + ); + + if (resolveResult !== null && resolveResult !== undefined) { + return resolveResult + } + } + } + } + } + + throw importNotDefined(name, packageJsonUrl, base) +} + +// Note: In Node.js, `getPackageType` is here. +// To prevent a circular dependency, we move it to +// `resolve-get-package-type.js`. + +/** + * @param {string} specifier + * @param {URL} base + */ +function parsePackageName(specifier, base) { + let separatorIndex = specifier.indexOf('/'); + let validPackageName = true; + let isScoped = false; + if (specifier[0] === '@') { + isScoped = true; + if (separatorIndex === -1 || specifier.length === 0) { + validPackageName = false; + } else { + separatorIndex = specifier.indexOf('/', separatorIndex + 1); + } + } + + const packageName = + separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); + + // Package name cannot have leading . and cannot have percent-encoding or + // \\ separators. + if (invalidPackageNameRegEx.exec(packageName) !== null) { + validPackageName = false; + } + + if (!validPackageName) { + throw new ERR_INVALID_MODULE_SPECIFIER( + specifier, + 'is not a valid package name', + node_url.fileURLToPath(base) + ) + } + + const packageSubpath = + '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex)); + + return {packageName, packageSubpath, isScoped} +} + +/** + * @param {string} specifier + * @param {URL} base + * @param {Set | undefined} conditions + * @returns {URL} + */ +function packageResolve(specifier, base, conditions) { + if (node_module.builtinModules.includes(specifier)) { + return new node_url.URL('node:' + specifier) + } + + const {packageName, packageSubpath, isScoped} = parsePackageName( + specifier, + base + ); + + // ResolveSelf + const packageConfig = getPackageScopeConfig(base); + + // Can’t test. + /* c8 ignore next 16 */ + if (packageConfig.exists) { + const packageJsonUrl = node_url.pathToFileURL(packageConfig.pjsonPath); + if ( + packageConfig.name === packageName && + packageConfig.exports !== undefined && + packageConfig.exports !== null + ) { + return packageExportsResolve( + packageJsonUrl, + packageSubpath, + packageConfig, + base, + conditions + ) + } + } + + let packageJsonUrl = new node_url.URL( + './node_modules/' + packageName + '/package.json', + base + ); + let packageJsonPath = node_url.fileURLToPath(packageJsonUrl); + /** @type {string} */ + let lastPath; + do { + const stat = tryStatSync(packageJsonPath.slice(0, -13)); + if (!stat.isDirectory()) { + lastPath = packageJsonPath; + packageJsonUrl = new node_url.URL( + (isScoped ? '../../../../node_modules/' : '../../../node_modules/') + + packageName + + '/package.json', + packageJsonUrl + ); + packageJsonPath = node_url.fileURLToPath(packageJsonUrl); + continue + } + + // Package match. + const packageConfig = packageJsonReader.read(packageJsonPath, { + base, + specifier + }); + if (packageConfig.exports !== undefined && packageConfig.exports !== null) { + return packageExportsResolve( + packageJsonUrl, + packageSubpath, + packageConfig, + base, + conditions + ) + } + + if (packageSubpath === '.') { + return legacyMainResolve(packageJsonUrl, packageConfig, base) + } + + return new node_url.URL(packageSubpath, packageJsonUrl) + // Cross-platform root check. + } while (packageJsonPath.length !== lastPath.length) + + throw new ERR_MODULE_NOT_FOUND(packageName, node_url.fileURLToPath(base), false) +} + +/** + * @param {string} specifier + * @returns {boolean} + */ +function isRelativeSpecifier(specifier) { + if (specifier[0] === '.') { + if (specifier.length === 1 || specifier[1] === '/') return true + if ( + specifier[1] === '.' && + (specifier.length === 2 || specifier[2] === '/') + ) { + return true + } + } + + return false +} + +/** + * @param {string} specifier + * @returns {boolean} + */ +function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { + if (specifier === '') return false + if (specifier[0] === '/') return true + return isRelativeSpecifier(specifier) +} + +/** + * The “Resolver Algorithm Specification” as detailed in the Node docs (which is + * sync and slightly lower-level than `resolve`). + * + * @param {string} specifier + * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc. + * @param {URL} base + * Full URL (to a file) that `specifier` is resolved relative from. + * @param {Set} [conditions] + * Conditions. + * @param {boolean} [preserveSymlinks] + * Keep symlinks instead of resolving them. + * @returns {URL} + * A URL object to the found thing. + */ +function moduleResolve(specifier, base, conditions, preserveSymlinks) { + const protocol = base.protocol; + const isRemote = protocol === 'http:' || protocol === 'https:'; + // Order swapped from spec for minor perf gain. + // Ok since relative URLs cannot parse as URLs. + /** @type {URL | undefined} */ + let resolved; + + if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { + resolved = new node_url.URL(specifier, base); + } else if (!isRemote && specifier[0] === '#') { + resolved = packageImportsResolve(specifier, base, conditions); + } else { + try { + resolved = new node_url.URL(specifier); + } catch { + if (!isRemote) { + resolved = packageResolve(specifier, base, conditions); + } + } + } + + assert__default(resolved !== undefined, 'expected to be defined'); + + if (resolved.protocol !== 'file:') { + return resolved + } + + return finalizeResolution(resolved, base, preserveSymlinks) +} + +function fileURLToPath(id) { + if (typeof id === "string" && !id.startsWith("file://")) { + return normalizeSlash(id); + } + return normalizeSlash(node_url.fileURLToPath(id)); +} +function pathToFileURL(id) { + return node_url.pathToFileURL(fileURLToPath(id)).toString(); +} +const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g; +function sanitizeURIComponent(name = "", replacement = "_") { + return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement); +} +function sanitizeFilePath(filePath = "") { + return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/"); +} +function normalizeid(id) { + if (typeof id !== "string") { + id = id.toString(); + } + if (/(node|data|http|https|file):/.test(id)) { + return id; + } + if (BUILTIN_MODULES.has(id)) { + return "node:" + id; + } + return "file://" + encodeURI(normalizeSlash(id)); +} +async function loadURL(url) { + const code = await fs.promises.readFile(fileURLToPath(url), "utf8"); + return code; +} +function toDataURL(code) { + const base64 = Buffer.from(code).toString("base64"); + return `data:text/javascript;base64,${base64}`; +} +function isNodeBuiltin(id = "") { + id = id.replace(/^node:/, "").split("/")[0]; + return BUILTIN_MODULES.has(id); +} +const ProtocolRegex = /^(?.{2,}?):.+$/; +function getProtocol(id) { + const proto = id.match(ProtocolRegex); + return proto ? proto.groups?.proto : void 0; +} + +const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]); +const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"]; +const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([ + "ERR_MODULE_NOT_FOUND", + "ERR_UNSUPPORTED_DIR_IMPORT", + "MODULE_NOT_FOUND", + "ERR_PACKAGE_PATH_NOT_EXPORTED" +]); +function _tryModuleResolve(id, url, conditions) { + try { + return moduleResolve(id, url, conditions); + } catch (error) { + if (!NOT_FOUND_ERRORS.has(error?.code)) { + throw error; + } + } +} +function _resolve(id, options = {}) { + if (typeof id !== "string") { + if (id instanceof URL) { + id = fileURLToPath(id); + } else { + throw new TypeError("input must be a `string` or `URL`"); + } + } + if (/(node|data|http|https):/.test(id)) { + return id; + } + if (BUILTIN_MODULES.has(id)) { + return "node:" + id; + } + if (id.startsWith("file://")) { + id = fileURLToPath(id); + } + if (pathe.isAbsolute(id)) { + try { + const stat = fs.statSync(id); + if (stat.isFile()) { + return pathToFileURL(id); + } + } catch (error) { + if (error?.code !== "ENOENT") { + throw error; + } + } + } + const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET; + const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString()))); + if (_urls.length === 0) { + _urls.push(new URL(pathToFileURL(process.cwd()))); + } + const urls = [..._urls]; + for (const url of _urls) { + if (url.protocol === "file:") { + urls.push( + new URL("./", url), + // If url is directory + new URL(ufo.joinURL(url.pathname, "_index.js"), url), + // TODO: Remove in next major version? + new URL("node_modules", url) + ); + } + } + let resolved; + for (const url of urls) { + resolved = _tryModuleResolve(id, url, conditionsSet); + if (resolved) { + break; + } + for (const prefix of ["", "/index"]) { + for (const extension of options.extensions || DEFAULT_EXTENSIONS) { + resolved = _tryModuleResolve( + id + prefix + extension, + url, + conditionsSet + ); + if (resolved) { + break; + } + } + if (resolved) { + break; + } + } + if (resolved) { + break; + } + } + if (!resolved) { + const error = new Error( + `Cannot find module ${id} imported from ${urls.join(", ")}` + ); + error.code = "ERR_MODULE_NOT_FOUND"; + throw error; + } + return pathToFileURL(resolved); +} +function resolveSync(id, options) { + return _resolve(id, options); +} +function resolve(id, options) { + try { + return Promise.resolve(resolveSync(id, options)); + } catch (error) { + return Promise.reject(error); + } +} +function resolvePathSync(id, options) { + return fileURLToPath(resolveSync(id, options)); +} +function resolvePath(id, options) { + try { + return Promise.resolve(resolvePathSync(id, options)); + } catch (error) { + return Promise.reject(error); + } +} +function createResolve(defaults) { + return (id, url) => { + return resolve(id, { url, ...defaults }); + }; +} +const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/; +function parseNodeModulePath(path) { + if (!path) { + return {}; + } + path = pathe.normalize(fileURLToPath(path)); + const match = NODE_MODULES_RE.exec(path); + if (!match) { + return {}; + } + const [, dir, name, subpath] = match; + return { + dir, + name, + subpath: subpath ? `.${subpath}` : void 0 + }; +} +async function lookupNodeModuleSubpath(path) { + path = pathe.normalize(fileURLToPath(path)); + const { name, subpath } = parseNodeModulePath(path); + if (!name || !subpath) { + return subpath; + } + const { exports } = await pkgTypes.readPackageJSON(path).catch(() => { + }) || {}; + if (exports) { + const resolvedSubpath = _findSubpath(subpath, exports); + if (resolvedSubpath) { + return resolvedSubpath; + } + } + return subpath; +} +function _findSubpath(subpath, exports) { + if (typeof exports === "string") { + exports = { ".": exports }; + } + if (!subpath.startsWith(".")) { + subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`; + } + if (subpath in (exports || {})) { + return subpath; + } + return _flattenExports(exports).find((p) => p.fsPath === subpath)?.subpath; +} +function _flattenExports(exports = {}, parentSubpath = "./") { + return Object.entries(exports).flatMap(([key, value]) => { + const [subpath, condition] = key.startsWith(".") ? [key.slice(1), void 0] : ["", key]; + const _subPath = ufo.joinURL(parentSubpath, subpath); + if (typeof value === "string") { + return [{ subpath: _subPath, fsPath: value, condition }]; + } else { + return _flattenExports(value, _subPath); + } + }); +} + +const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*([\s"']*(?[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu; +const DYNAMIC_IMPORT_RE = /import\s*\((?(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm; +const IMPORT_NAMED_TYPE_RE = /(?<=\s|^|;|})import\s*type\s+([\s"']*(?[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm; +const EXPORT_DECAL_RE = /\bexport\s+(?(async function\s*\*?|function\s*\*?|let|const enum|const|enum|var|class))\s+\*?(?[\w$]+)(?.*,\s*[\w$]+)*/g; +const EXPORT_DECAL_TYPE_RE = /\bexport\s+(?(interface|type|declare (async function|function|let|const enum|const|enum|var|class)))\s+(?[\w$]+)/g; +const EXPORT_NAMED_RE = /\bexport\s+{(?[^}]+?)[\s,]*}(\s*from\s*["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; +const EXPORT_NAMED_TYPE_RE = /\bexport\s+type\s+{(?[^}]+?)[\s,]*}(\s*from\s*["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; +const EXPORT_NAMED_DESTRUCT = /\bexport\s+(let|var|const)\s+(?:{(?[^}]+?)[\s,]*}|\[(?[^\]]+?)[\s,]*])\s+=/gm; +const EXPORT_STAR_RE = /\bexport\s*(\*)(\s*as\s+(?[\w$]+)\s+)?\s*(\s*from\s*["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; +const EXPORT_DEFAULT_RE = /\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?.*)/g; +const TYPE_RE = /^\s*?type\s/; +function findStaticImports(code) { + return _filterStatement( + _tryGetLocations(code, "import"), + matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }) + ); +} +function findDynamicImports(code) { + return _filterStatement( + _tryGetLocations(code, "import"), + matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" }) + ); +} +function findTypeImports(code) { + return [ + ...matchAll(IMPORT_NAMED_TYPE_RE, code, { type: "type" }), + ...matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }).filter( + (match) => /[^A-Za-z]type\s/.test(match.imports) + ) + ]; +} +function parseStaticImport(matched) { + const cleanedImports = clearImports(matched.imports); + const namedImports = {}; + const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; + for (const namedImport of _matches) { + const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/); + const source = _match?.[1] || namedImport.trim(); + const importName = _match?.[2] || source; + if (source && !TYPE_RE.test(source)) { + namedImports[source] = importName; + } + } + const { namespacedImport, defaultImport } = getImportNames(cleanedImports); + return { + ...matched, + defaultImport, + namespacedImport, + namedImports + }; +} +function parseTypeImport(matched) { + if (matched.type === "type") { + return parseStaticImport(matched); + } + const cleanedImports = clearImports(matched.imports); + const namedImports = {}; + const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; + for (const namedImport of _matches) { + const _match = /\s+as\s+/.test(namedImport) ? namedImport.match(/^\s*type\s+(\S*) as (\S*)\s*$/) : namedImport.match(/^\s*type\s+(\S*)\s*$/); + const source = _match?.[1] || namedImport.trim(); + const importName = _match?.[2] || source; + if (source && TYPE_RE.test(namedImport)) { + namedImports[source] = importName; + } + } + const { namespacedImport, defaultImport } = getImportNames(cleanedImports); + return { + ...matched, + defaultImport, + namespacedImport, + namedImports + }; +} +function findExports(code) { + const declaredExports = matchAll(EXPORT_DECAL_RE, code, { + type: "declaration" + }); + for (const declaredExport of declaredExports) { + const extraNamesStr = declaredExport.extraNames; + if (extraNamesStr) { + const extraNames = matchAll(/,\s*(?\w+)/g, extraNamesStr, {}).map( + (m) => m.name + ); + declaredExport.names = [declaredExport.name, ...extraNames]; + } + delete declaredExport.extraNames; + } + const namedExports = normalizeNamedExports( + matchAll(EXPORT_NAMED_RE, code, { + type: "named" + }) + ); + const destructuredExports = matchAll( + EXPORT_NAMED_DESTRUCT, + code, + { type: "named" } + ); + for (const namedExport of destructuredExports) { + namedExport.exports = namedExport.exports1 || namedExport.exports2; + namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map( + (name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim() + ); + } + const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, { + type: "default", + name: "default" + }); + const starExports = matchAll(EXPORT_STAR_RE, code, { + type: "star" + }); + const exports = normalizeExports([ + ...declaredExports, + ...namedExports, + ...destructuredExports, + ...defaultExport, + ...starExports + ]); + if (exports.length === 0) { + return []; + } + const exportLocations = _tryGetLocations(code, "export"); + if (exportLocations && exportLocations.length === 0) { + return []; + } + return ( + // Filter false positive export matches + _filterStatement(exportLocations, exports).filter((exp, index, exports2) => { + const nextExport = exports2[index + 1]; + return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name; + }) + ); +} +function findTypeExports(code) { + const declaredExports = matchAll( + EXPORT_DECAL_TYPE_RE, + code, + { type: "declaration" } + ); + const namedExports = normalizeNamedExports( + matchAll(EXPORT_NAMED_TYPE_RE, code, { + type: "named" + }) + ); + const exports = normalizeExports([ + ...declaredExports, + ...namedExports + ]); + if (exports.length === 0) { + return []; + } + const exportLocations = _tryGetLocations(code, "export"); + if (exportLocations && exportLocations.length === 0) { + return []; + } + return ( + // Filter false positive export matches + _filterStatement(exportLocations, exports).filter((exp, index, exports2) => { + const nextExport = exports2[index + 1]; + return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name; + }) + ); +} +function normalizeExports(exports) { + for (const exp of exports) { + if (!exp.name && exp.names && exp.names.length === 1) { + exp.name = exp.names[0]; + } + if (exp.name === "default" && exp.type !== "default") { + exp._type = exp.type; + exp.type = "default"; + } + if (!exp.names && exp.name) { + exp.names = [exp.name]; + } + if (exp.type === "declaration" && exp.declaration) { + exp.declarationType = exp.declaration.replace( + /^declare\s*/, + "" + ); + } + } + return exports; +} +function normalizeNamedExports(namedExports) { + for (const namedExport of namedExports) { + namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim()); + } + return namedExports; +} +function findExportNames(code) { + return findExports(code).flatMap((exp) => exp.names).filter(Boolean); +} +async function resolveModuleExportNames(id, options) { + const url = await resolvePath(id, options); + const code = await loadURL(url); + const exports = findExports(code); + const exportNames = new Set( + exports.flatMap((exp) => exp.names).filter(Boolean) + ); + for (const exp of exports) { + if (exp.type !== "star" || !exp.specifier) { + continue; + } + const subExports = await resolveModuleExportNames(exp.specifier, { + ...options, + url + }); + for (const subExport of subExports) { + exportNames.add(subExport); + } + } + return [...exportNames]; +} +function _filterStatement(locations, statements) { + return statements.filter((exp) => { + return !locations || locations.some((location) => { + return exp.start <= location.start && exp.end >= location.end; + }); + }); +} +function _tryGetLocations(code, label) { + try { + return _getLocations(code, label); + } catch { + } +} +function _getLocations(code, label) { + const tokens = acorn.tokenizer(code, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true + }); + const locations = []; + for (const token of tokens) { + if (token.type.label === label) { + locations.push({ + start: token.start, + end: token.end + }); + } + } + return locations; +} + +function createCommonJS(url) { + const __filename = fileURLToPath(url); + const __dirname = path.dirname(__filename); + let _nativeRequire; + const getNativeRequire = () => { + if (!_nativeRequire) { + _nativeRequire = node_module.createRequire(url); + } + return _nativeRequire; + }; + function require(id) { + return getNativeRequire()(id); + } + require.resolve = function requireResolve(id, options) { + return getNativeRequire().resolve(id, options); + }; + return { + __filename, + __dirname, + require + }; +} +function interopDefault(sourceModule, opts = {}) { + if (!isObject(sourceModule) || !("default" in sourceModule)) { + return sourceModule; + } + const defaultValue = sourceModule.default; + if (defaultValue === void 0 || defaultValue === null) { + return sourceModule; + } + if (typeof defaultValue !== "object") { + return opts.preferNamespace ? sourceModule : defaultValue; + } + for (const key in sourceModule) { + if (key === "default") { + try { + if (!(key in defaultValue)) { + Object.defineProperty(defaultValue, key, { + enumerable: false, + configurable: false, + get() { + return defaultValue; + } + }); + } + } catch { + } + } else { + try { + if (!(key in defaultValue)) { + Object.defineProperty(defaultValue, key, { + enumerable: true, + configurable: true, + get() { + return sourceModule[key]; + } + }); + } + } catch { + } + } + } + return defaultValue; +} + +const EVAL_ESM_IMPORT_RE = /(?<=import .* from ["'])([^"']+)(?=["'])|(?<=export .* from ["'])([^"']+)(?=["'])|(?<=import\s*["'])([^"']+)(?=["'])|(?<=import\s*\(["'])([^"']+)(?=["']\))/g; +async function loadModule(id, options = {}) { + const url = await resolve(id, options); + const code = await loadURL(url); + return evalModule(code, { ...options, url }); +} +async function evalModule(code, options = {}) { + const transformed = await transformModule(code, options); + const dataURL = toDataURL(transformed); + return import(dataURL).catch((error) => { + error.stack = error.stack.replace( + new RegExp(dataURL, "g"), + options.url || "_mlly_eval_" + ); + throw error; + }); +} +function transformModule(code, options = {}) { + if (options.url && options.url.endsWith(".json")) { + return Promise.resolve("export default " + code); + } + if (options.url) { + code = code.replace(/import\.meta\.url/g, `'${options.url}'`); + } + return Promise.resolve(code); +} +async function resolveImports(code, options) { + const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]); + if (imports.length === 0) { + return code; + } + const uniqueImports = [...new Set(imports)]; + const resolved = /* @__PURE__ */ new Map(); + await Promise.all( + uniqueImports.map(async (id) => { + let url = await resolve(id, options); + if (url.endsWith(".json")) { + const code2 = await loadURL(url); + url = toDataURL(await transformModule(code2, { url })); + } + resolved.set(id, url); + }) + ); + const re = new RegExp( + uniqueImports.map((index) => `(${index})`).join("|"), + "g" + ); + return code.replace(re, (id) => resolved.get(id)); +} + +const ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; +const CJS_RE = /([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m; +const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g; +const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]); +function hasESMSyntax(code, opts = {}) { + if (opts.stripComments) { + code = code.replace(COMMENT_RE, ""); + } + return ESM_RE.test(code); +} +function hasCJSSyntax(code, opts = {}) { + if (opts.stripComments) { + code = code.replace(COMMENT_RE, ""); + } + return CJS_RE.test(code); +} +function detectSyntax(code, opts = {}) { + if (opts.stripComments) { + code = code.replace(COMMENT_RE, ""); + } + const hasESM = hasESMSyntax(code, {}); + const hasCJS = hasCJSSyntax(code, {}); + return { + hasESM, + hasCJS, + isMixed: hasESM && hasCJS + }; +} +const validNodeImportDefaults = { + allowedProtocols: ["node", "file", "data"] +}; +async function isValidNodeImport(id, _options = {}) { + if (isNodeBuiltin(id)) { + return true; + } + const options = { ...validNodeImportDefaults, ..._options }; + const proto = getProtocol(id); + if (proto && !options.allowedProtocols?.includes(proto)) { + return false; + } + if (proto === "data") { + return true; + } + const resolvedPath = await resolvePath(id, options); + const extension = pathe.extname(resolvedPath); + if (BUILTIN_EXTENSIONS.has(extension)) { + return true; + } + if (extension !== ".js") { + return false; + } + const package_ = await pkgTypes.readPackageJSON(resolvedPath).catch(() => { + }); + if (package_?.type === "module") { + return true; + } + if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(resolvedPath)) { + return false; + } + const code = options.code || await fs.promises.readFile(resolvedPath, "utf8").catch(() => { + }) || ""; + return !hasESMSyntax(code); +} + +exports.DYNAMIC_IMPORT_RE = DYNAMIC_IMPORT_RE; +exports.ESM_STATIC_IMPORT_RE = ESM_STATIC_IMPORT_RE; +exports.EXPORT_DECAL_RE = EXPORT_DECAL_RE; +exports.EXPORT_DECAL_TYPE_RE = EXPORT_DECAL_TYPE_RE; +exports.createCommonJS = createCommonJS; +exports.createResolve = createResolve; +exports.detectSyntax = detectSyntax; +exports.evalModule = evalModule; +exports.fileURLToPath = fileURLToPath; +exports.findDynamicImports = findDynamicImports; +exports.findExportNames = findExportNames; +exports.findExports = findExports; +exports.findStaticImports = findStaticImports; +exports.findTypeExports = findTypeExports; +exports.findTypeImports = findTypeImports; +exports.getProtocol = getProtocol; +exports.hasCJSSyntax = hasCJSSyntax; +exports.hasESMSyntax = hasESMSyntax; +exports.interopDefault = interopDefault; +exports.isNodeBuiltin = isNodeBuiltin; +exports.isValidNodeImport = isValidNodeImport; +exports.loadModule = loadModule; +exports.loadURL = loadURL; +exports.lookupNodeModuleSubpath = lookupNodeModuleSubpath; +exports.normalizeid = normalizeid; +exports.parseNodeModulePath = parseNodeModulePath; +exports.parseStaticImport = parseStaticImport; +exports.parseTypeImport = parseTypeImport; +exports.pathToFileURL = pathToFileURL; +exports.resolve = resolve; +exports.resolveImports = resolveImports; +exports.resolveModuleExportNames = resolveModuleExportNames; +exports.resolvePath = resolvePath; +exports.resolvePathSync = resolvePathSync; +exports.resolveSync = resolveSync; +exports.sanitizeFilePath = sanitizeFilePath; +exports.sanitizeURIComponent = sanitizeURIComponent; +exports.toDataURL = toDataURL; +exports.transformModule = transformModule; diff --git a/web/node_modules/mlly/dist/index.d.cts b/web/node_modules/mlly/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..e6dbc09ca1e263bcd4490ddf79a63237c51265ae --- /dev/null +++ b/web/node_modules/mlly/dist/index.d.cts @@ -0,0 +1,143 @@ +interface ResolveOptions { + url?: string | URL | (string | URL)[]; + extensions?: string[]; + conditions?: string[]; +} +declare function resolveSync(id: string, options?: ResolveOptions): string; +declare function resolve(id: string, options?: ResolveOptions): Promise; +declare function resolvePathSync(id: string, options?: ResolveOptions): string; +declare function resolvePath(id: string, options?: ResolveOptions): Promise; +declare function createResolve(defaults?: ResolveOptions): (id: string, url?: ResolveOptions["url"]) => Promise; +declare function parseNodeModulePath(path: string): { + dir?: undefined; + name?: undefined; + subpath?: undefined; +} | { + dir: string; + name: string; + subpath: string | undefined; +}; +/** Reverse engineer a subpath export if possible */ +declare function lookupNodeModuleSubpath(path: string): Promise; + +interface ESMImport { + type: "static" | "dynamic"; + code: string; + start: number; + end: number; +} +interface StaticImport extends ESMImport { + type: "static"; + imports: string; + specifier: string; +} +interface ParsedStaticImport extends StaticImport { + defaultImport?: string; + namespacedImport?: string; + namedImports?: { + [name: string]: string; + }; +} +interface DynamicImport extends ESMImport { + type: "dynamic"; + expression: string; +} +interface TypeImport extends Omit { + type: "type"; + imports: string; + specifier: string; +} +interface ESMExport { + _type?: "declaration" | "named" | "default" | "star"; + type: "declaration" | "named" | "default" | "star"; + declarationType?: "let" | "var" | "const" | "enum" | "const enum" | "class" | "function" | "async function"; + code: string; + start: number; + end: number; + name?: string; + defaultName?: string; + names: string[]; + specifier?: string; +} +interface DeclarationExport extends ESMExport { + type: "declaration"; + declaration: string; + name: string; +} +interface NamedExport extends ESMExport { + type: "named"; + exports: string; + names: string[]; + specifier?: string; +} +interface DefaultExport extends ESMExport { + type: "default"; +} +declare const ESM_STATIC_IMPORT_RE: RegExp; +declare const DYNAMIC_IMPORT_RE: RegExp; +declare const EXPORT_DECAL_RE: RegExp; +declare const EXPORT_DECAL_TYPE_RE: RegExp; +declare function findStaticImports(code: string): StaticImport[]; +declare function findDynamicImports(code: string): DynamicImport[]; +declare function findTypeImports(code: string): TypeImport[]; +declare function parseStaticImport(matched: StaticImport | TypeImport): ParsedStaticImport; +declare function parseTypeImport(matched: TypeImport | StaticImport): ParsedStaticImport; +declare function findExports(code: string): ESMExport[]; +declare function findTypeExports(code: string): ESMExport[]; +declare function findExportNames(code: string): string[]; +declare function resolveModuleExportNames(id: string, options?: ResolveOptions): Promise; + +interface CommonjsContext { + __filename: string; + __dirname: string; + require: NodeRequire; +} +declare function createCommonJS(url: string): CommonjsContext; +declare function interopDefault(sourceModule: any, opts?: { + preferNamespace?: boolean; +}): any; + +interface EvaluateOptions extends ResolveOptions { + url?: string; +} +declare function loadModule(id: string, options?: EvaluateOptions): Promise; +declare function evalModule(code: string, options?: EvaluateOptions): Promise; +declare function transformModule(code: string, options?: EvaluateOptions): Promise; +declare function resolveImports(code: string, options?: EvaluateOptions): Promise; + +type DetectSyntaxOptions = { + stripComments?: boolean; +}; +declare function hasESMSyntax(code: string, opts?: DetectSyntaxOptions): boolean; +declare function hasCJSSyntax(code: string, opts?: DetectSyntaxOptions): boolean; +declare function detectSyntax(code: string, opts?: DetectSyntaxOptions): { + hasESM: boolean; + hasCJS: boolean; + isMixed: boolean; +}; +interface ValidNodeImportOptions extends ResolveOptions { + /** + * The contents of the import, which may be analyzed to see if it contains + * CJS or ESM syntax as a last step in checking whether it is a valid import. + */ + code?: string; + /** + * Protocols that are allowed as valid node imports. + * + * Default: ['node', 'file', 'data'] + */ + allowedProtocols?: Array; +} +declare function isValidNodeImport(id: string, _options?: ValidNodeImportOptions): Promise; + +declare function fileURLToPath(id: string | URL): string; +declare function pathToFileURL(id: string | URL): string; +declare function sanitizeURIComponent(name?: string, replacement?: string): string; +declare function sanitizeFilePath(filePath?: string): string; +declare function normalizeid(id: string): string; +declare function loadURL(url: string): Promise; +declare function toDataURL(code: string): string; +declare function isNodeBuiltin(id?: string): boolean; +declare function getProtocol(id: string): string | undefined; + +export { type CommonjsContext, DYNAMIC_IMPORT_RE, type DeclarationExport, type DefaultExport, type DetectSyntaxOptions, type DynamicImport, type ESMExport, type ESMImport, ESM_STATIC_IMPORT_RE, EXPORT_DECAL_RE, EXPORT_DECAL_TYPE_RE, type EvaluateOptions, type NamedExport, type ParsedStaticImport, type ResolveOptions, type StaticImport, type TypeImport, type ValidNodeImportOptions, createCommonJS, createResolve, detectSyntax, evalModule, fileURLToPath, findDynamicImports, findExportNames, findExports, findStaticImports, findTypeExports, findTypeImports, getProtocol, hasCJSSyntax, hasESMSyntax, interopDefault, isNodeBuiltin, isValidNodeImport, loadModule, loadURL, lookupNodeModuleSubpath, normalizeid, parseNodeModulePath, parseStaticImport, parseTypeImport, pathToFileURL, resolve, resolveImports, resolveModuleExportNames, resolvePath, resolvePathSync, resolveSync, sanitizeFilePath, sanitizeURIComponent, toDataURL, transformModule }; diff --git a/web/node_modules/mlly/dist/index.d.mts b/web/node_modules/mlly/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e6dbc09ca1e263bcd4490ddf79a63237c51265ae --- /dev/null +++ b/web/node_modules/mlly/dist/index.d.mts @@ -0,0 +1,143 @@ +interface ResolveOptions { + url?: string | URL | (string | URL)[]; + extensions?: string[]; + conditions?: string[]; +} +declare function resolveSync(id: string, options?: ResolveOptions): string; +declare function resolve(id: string, options?: ResolveOptions): Promise; +declare function resolvePathSync(id: string, options?: ResolveOptions): string; +declare function resolvePath(id: string, options?: ResolveOptions): Promise; +declare function createResolve(defaults?: ResolveOptions): (id: string, url?: ResolveOptions["url"]) => Promise; +declare function parseNodeModulePath(path: string): { + dir?: undefined; + name?: undefined; + subpath?: undefined; +} | { + dir: string; + name: string; + subpath: string | undefined; +}; +/** Reverse engineer a subpath export if possible */ +declare function lookupNodeModuleSubpath(path: string): Promise; + +interface ESMImport { + type: "static" | "dynamic"; + code: string; + start: number; + end: number; +} +interface StaticImport extends ESMImport { + type: "static"; + imports: string; + specifier: string; +} +interface ParsedStaticImport extends StaticImport { + defaultImport?: string; + namespacedImport?: string; + namedImports?: { + [name: string]: string; + }; +} +interface DynamicImport extends ESMImport { + type: "dynamic"; + expression: string; +} +interface TypeImport extends Omit { + type: "type"; + imports: string; + specifier: string; +} +interface ESMExport { + _type?: "declaration" | "named" | "default" | "star"; + type: "declaration" | "named" | "default" | "star"; + declarationType?: "let" | "var" | "const" | "enum" | "const enum" | "class" | "function" | "async function"; + code: string; + start: number; + end: number; + name?: string; + defaultName?: string; + names: string[]; + specifier?: string; +} +interface DeclarationExport extends ESMExport { + type: "declaration"; + declaration: string; + name: string; +} +interface NamedExport extends ESMExport { + type: "named"; + exports: string; + names: string[]; + specifier?: string; +} +interface DefaultExport extends ESMExport { + type: "default"; +} +declare const ESM_STATIC_IMPORT_RE: RegExp; +declare const DYNAMIC_IMPORT_RE: RegExp; +declare const EXPORT_DECAL_RE: RegExp; +declare const EXPORT_DECAL_TYPE_RE: RegExp; +declare function findStaticImports(code: string): StaticImport[]; +declare function findDynamicImports(code: string): DynamicImport[]; +declare function findTypeImports(code: string): TypeImport[]; +declare function parseStaticImport(matched: StaticImport | TypeImport): ParsedStaticImport; +declare function parseTypeImport(matched: TypeImport | StaticImport): ParsedStaticImport; +declare function findExports(code: string): ESMExport[]; +declare function findTypeExports(code: string): ESMExport[]; +declare function findExportNames(code: string): string[]; +declare function resolveModuleExportNames(id: string, options?: ResolveOptions): Promise; + +interface CommonjsContext { + __filename: string; + __dirname: string; + require: NodeRequire; +} +declare function createCommonJS(url: string): CommonjsContext; +declare function interopDefault(sourceModule: any, opts?: { + preferNamespace?: boolean; +}): any; + +interface EvaluateOptions extends ResolveOptions { + url?: string; +} +declare function loadModule(id: string, options?: EvaluateOptions): Promise; +declare function evalModule(code: string, options?: EvaluateOptions): Promise; +declare function transformModule(code: string, options?: EvaluateOptions): Promise; +declare function resolveImports(code: string, options?: EvaluateOptions): Promise; + +type DetectSyntaxOptions = { + stripComments?: boolean; +}; +declare function hasESMSyntax(code: string, opts?: DetectSyntaxOptions): boolean; +declare function hasCJSSyntax(code: string, opts?: DetectSyntaxOptions): boolean; +declare function detectSyntax(code: string, opts?: DetectSyntaxOptions): { + hasESM: boolean; + hasCJS: boolean; + isMixed: boolean; +}; +interface ValidNodeImportOptions extends ResolveOptions { + /** + * The contents of the import, which may be analyzed to see if it contains + * CJS or ESM syntax as a last step in checking whether it is a valid import. + */ + code?: string; + /** + * Protocols that are allowed as valid node imports. + * + * Default: ['node', 'file', 'data'] + */ + allowedProtocols?: Array; +} +declare function isValidNodeImport(id: string, _options?: ValidNodeImportOptions): Promise; + +declare function fileURLToPath(id: string | URL): string; +declare function pathToFileURL(id: string | URL): string; +declare function sanitizeURIComponent(name?: string, replacement?: string): string; +declare function sanitizeFilePath(filePath?: string): string; +declare function normalizeid(id: string): string; +declare function loadURL(url: string): Promise; +declare function toDataURL(code: string): string; +declare function isNodeBuiltin(id?: string): boolean; +declare function getProtocol(id: string): string | undefined; + +export { type CommonjsContext, DYNAMIC_IMPORT_RE, type DeclarationExport, type DefaultExport, type DetectSyntaxOptions, type DynamicImport, type ESMExport, type ESMImport, ESM_STATIC_IMPORT_RE, EXPORT_DECAL_RE, EXPORT_DECAL_TYPE_RE, type EvaluateOptions, type NamedExport, type ParsedStaticImport, type ResolveOptions, type StaticImport, type TypeImport, type ValidNodeImportOptions, createCommonJS, createResolve, detectSyntax, evalModule, fileURLToPath, findDynamicImports, findExportNames, findExports, findStaticImports, findTypeExports, findTypeImports, getProtocol, hasCJSSyntax, hasESMSyntax, interopDefault, isNodeBuiltin, isValidNodeImport, loadModule, loadURL, lookupNodeModuleSubpath, normalizeid, parseNodeModulePath, parseStaticImport, parseTypeImport, pathToFileURL, resolve, resolveImports, resolveModuleExportNames, resolvePath, resolvePathSync, resolveSync, sanitizeFilePath, sanitizeURIComponent, toDataURL, transformModule }; diff --git a/web/node_modules/mlly/dist/index.d.ts b/web/node_modules/mlly/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6dbc09ca1e263bcd4490ddf79a63237c51265ae --- /dev/null +++ b/web/node_modules/mlly/dist/index.d.ts @@ -0,0 +1,143 @@ +interface ResolveOptions { + url?: string | URL | (string | URL)[]; + extensions?: string[]; + conditions?: string[]; +} +declare function resolveSync(id: string, options?: ResolveOptions): string; +declare function resolve(id: string, options?: ResolveOptions): Promise; +declare function resolvePathSync(id: string, options?: ResolveOptions): string; +declare function resolvePath(id: string, options?: ResolveOptions): Promise; +declare function createResolve(defaults?: ResolveOptions): (id: string, url?: ResolveOptions["url"]) => Promise; +declare function parseNodeModulePath(path: string): { + dir?: undefined; + name?: undefined; + subpath?: undefined; +} | { + dir: string; + name: string; + subpath: string | undefined; +}; +/** Reverse engineer a subpath export if possible */ +declare function lookupNodeModuleSubpath(path: string): Promise; + +interface ESMImport { + type: "static" | "dynamic"; + code: string; + start: number; + end: number; +} +interface StaticImport extends ESMImport { + type: "static"; + imports: string; + specifier: string; +} +interface ParsedStaticImport extends StaticImport { + defaultImport?: string; + namespacedImport?: string; + namedImports?: { + [name: string]: string; + }; +} +interface DynamicImport extends ESMImport { + type: "dynamic"; + expression: string; +} +interface TypeImport extends Omit { + type: "type"; + imports: string; + specifier: string; +} +interface ESMExport { + _type?: "declaration" | "named" | "default" | "star"; + type: "declaration" | "named" | "default" | "star"; + declarationType?: "let" | "var" | "const" | "enum" | "const enum" | "class" | "function" | "async function"; + code: string; + start: number; + end: number; + name?: string; + defaultName?: string; + names: string[]; + specifier?: string; +} +interface DeclarationExport extends ESMExport { + type: "declaration"; + declaration: string; + name: string; +} +interface NamedExport extends ESMExport { + type: "named"; + exports: string; + names: string[]; + specifier?: string; +} +interface DefaultExport extends ESMExport { + type: "default"; +} +declare const ESM_STATIC_IMPORT_RE: RegExp; +declare const DYNAMIC_IMPORT_RE: RegExp; +declare const EXPORT_DECAL_RE: RegExp; +declare const EXPORT_DECAL_TYPE_RE: RegExp; +declare function findStaticImports(code: string): StaticImport[]; +declare function findDynamicImports(code: string): DynamicImport[]; +declare function findTypeImports(code: string): TypeImport[]; +declare function parseStaticImport(matched: StaticImport | TypeImport): ParsedStaticImport; +declare function parseTypeImport(matched: TypeImport | StaticImport): ParsedStaticImport; +declare function findExports(code: string): ESMExport[]; +declare function findTypeExports(code: string): ESMExport[]; +declare function findExportNames(code: string): string[]; +declare function resolveModuleExportNames(id: string, options?: ResolveOptions): Promise; + +interface CommonjsContext { + __filename: string; + __dirname: string; + require: NodeRequire; +} +declare function createCommonJS(url: string): CommonjsContext; +declare function interopDefault(sourceModule: any, opts?: { + preferNamespace?: boolean; +}): any; + +interface EvaluateOptions extends ResolveOptions { + url?: string; +} +declare function loadModule(id: string, options?: EvaluateOptions): Promise; +declare function evalModule(code: string, options?: EvaluateOptions): Promise; +declare function transformModule(code: string, options?: EvaluateOptions): Promise; +declare function resolveImports(code: string, options?: EvaluateOptions): Promise; + +type DetectSyntaxOptions = { + stripComments?: boolean; +}; +declare function hasESMSyntax(code: string, opts?: DetectSyntaxOptions): boolean; +declare function hasCJSSyntax(code: string, opts?: DetectSyntaxOptions): boolean; +declare function detectSyntax(code: string, opts?: DetectSyntaxOptions): { + hasESM: boolean; + hasCJS: boolean; + isMixed: boolean; +}; +interface ValidNodeImportOptions extends ResolveOptions { + /** + * The contents of the import, which may be analyzed to see if it contains + * CJS or ESM syntax as a last step in checking whether it is a valid import. + */ + code?: string; + /** + * Protocols that are allowed as valid node imports. + * + * Default: ['node', 'file', 'data'] + */ + allowedProtocols?: Array; +} +declare function isValidNodeImport(id: string, _options?: ValidNodeImportOptions): Promise; + +declare function fileURLToPath(id: string | URL): string; +declare function pathToFileURL(id: string | URL): string; +declare function sanitizeURIComponent(name?: string, replacement?: string): string; +declare function sanitizeFilePath(filePath?: string): string; +declare function normalizeid(id: string): string; +declare function loadURL(url: string): Promise; +declare function toDataURL(code: string): string; +declare function isNodeBuiltin(id?: string): boolean; +declare function getProtocol(id: string): string | undefined; + +export { type CommonjsContext, DYNAMIC_IMPORT_RE, type DeclarationExport, type DefaultExport, type DetectSyntaxOptions, type DynamicImport, type ESMExport, type ESMImport, ESM_STATIC_IMPORT_RE, EXPORT_DECAL_RE, EXPORT_DECAL_TYPE_RE, type EvaluateOptions, type NamedExport, type ParsedStaticImport, type ResolveOptions, type StaticImport, type TypeImport, type ValidNodeImportOptions, createCommonJS, createResolve, detectSyntax, evalModule, fileURLToPath, findDynamicImports, findExportNames, findExports, findStaticImports, findTypeExports, findTypeImports, getProtocol, hasCJSSyntax, hasESMSyntax, interopDefault, isNodeBuiltin, isValidNodeImport, loadModule, loadURL, lookupNodeModuleSubpath, normalizeid, parseNodeModulePath, parseStaticImport, parseTypeImport, pathToFileURL, resolve, resolveImports, resolveModuleExportNames, resolvePath, resolvePathSync, resolveSync, sanitizeFilePath, sanitizeURIComponent, toDataURL, transformModule }; diff --git a/web/node_modules/mlly/dist/index.mjs b/web/node_modules/mlly/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a9541e0f283ee7d12a82962d76916cfd09b95d16 --- /dev/null +++ b/web/node_modules/mlly/dist/index.mjs @@ -0,0 +1,2623 @@ +import { tokenizer } from 'acorn'; +import { builtinModules, createRequire } from 'node:module'; +import fs, { realpathSync, statSync, Stats, promises } from 'node:fs'; +import { joinURL } from 'ufo'; +import { normalize, isAbsolute, extname as extname$1 } from 'pathe'; +import { readPackageJSON } from 'pkg-types'; +import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from 'node:url'; +import assert from 'node:assert'; +import process$1 from 'node:process'; +import path, { dirname } from 'node:path'; +import v8 from 'node:v8'; +import { format, inspect } from 'node:util'; + +const BUILTIN_MODULES = new Set(builtinModules); +function normalizeSlash(path) { + return path.replace(/\\/g, "/"); +} +function isObject(value) { + return value !== null && typeof value === "object"; +} +function matchAll(regex, string, addition) { + const matches = []; + for (const match of string.matchAll(regex)) { + matches.push({ + ...addition, + ...match.groups, + code: match[0], + start: match.index, + end: (match.index || 0) + match[0].length + }); + } + return matches; +} +function clearImports(imports) { + return (imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " "); +} +function getImportNames(cleanedImports) { + const topLevelImports = cleanedImports.replace(/{([^}]*)}/, ""); + const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1]; + const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0; + return { + namespacedImport, + defaultImport + }; +} + +/** + * @typedef ErrnoExceptionFields + * @property {number | undefined} [errnode] + * @property {string | undefined} [code] + * @property {string | undefined} [path] + * @property {string | undefined} [syscall] + * @property {string | undefined} [url] + * + * @typedef {Error & ErrnoExceptionFields} ErrnoException + */ + + +const own$1 = {}.hasOwnProperty; + +const classRegExp = /^([A-Z][a-z\d]*)+$/; +// Sorted by a rough estimate on most frequently used entries. +const kTypes = new Set([ + 'string', + 'function', + 'number', + 'object', + // Accept 'Function' and 'Object' as alternative to the lower cased version. + 'Function', + 'Object', + 'boolean', + 'bigint', + 'symbol' +]); + +const codes = {}; + +/** + * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'. + * We cannot use Intl.ListFormat because it's not available in + * --without-intl builds. + * + * @param {Array} array + * An array of strings. + * @param {string} [type] + * The list type to be inserted before the last element. + * @returns {string} + */ +function formatList(array, type = 'and') { + return array.length < 3 + ? array.join(` ${type} `) + : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}` +} + +/** @type {Map} */ +const messages = new Map(); +const nodeInternalPrefix = '__node_internal_'; +/** @type {number} */ +let userStackTraceLimit; + +codes.ERR_INVALID_ARG_TYPE = createError( + 'ERR_INVALID_ARG_TYPE', + /** + * @param {string} name + * @param {Array | string} expected + * @param {unknown} actual + */ + (name, expected, actual) => { + assert(typeof name === 'string', "'name' must be a string"); + if (!Array.isArray(expected)) { + expected = [expected]; + } + + let message = 'The '; + if (name.endsWith(' argument')) { + // For cases like 'first argument' + message += `${name} `; + } else { + const type = name.includes('.') ? 'property' : 'argument'; + message += `"${name}" ${type} `; + } + + message += 'must be '; + + /** @type {Array} */ + const types = []; + /** @type {Array} */ + const instances = []; + /** @type {Array} */ + const other = []; + + for (const value of expected) { + assert( + typeof value === 'string', + 'All expected entries have to be of type string' + ); + + if (kTypes.has(value)) { + types.push(value.toLowerCase()); + } else if (classRegExp.exec(value) === null) { + assert( + value !== 'object', + 'The value "object" should be written as "Object"' + ); + other.push(value); + } else { + instances.push(value); + } + } + + // Special handle `object` in case other instances are allowed to outline + // the differences between each other. + if (instances.length > 0) { + const pos = types.indexOf('object'); + if (pos !== -1) { + types.slice(pos, 1); + instances.push('Object'); + } + } + + if (types.length > 0) { + message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList( + types, + 'or' + )}`; + if (instances.length > 0 || other.length > 0) message += ' or '; + } + + if (instances.length > 0) { + message += `an instance of ${formatList(instances, 'or')}`; + if (other.length > 0) message += ' or '; + } + + if (other.length > 0) { + if (other.length > 1) { + message += `one of ${formatList(other, 'or')}`; + } else { + if (other[0].toLowerCase() !== other[0]) message += 'an '; + message += `${other[0]}`; + } + } + + message += `. Received ${determineSpecificType(actual)}`; + + return message + }, + TypeError +); + +codes.ERR_INVALID_MODULE_SPECIFIER = createError( + 'ERR_INVALID_MODULE_SPECIFIER', + /** + * @param {string} request + * @param {string} reason + * @param {string} [base] + */ + (request, reason, base = undefined) => { + return `Invalid module "${request}" ${reason}${ + base ? ` imported from ${base}` : '' + }` + }, + TypeError +); + +codes.ERR_INVALID_PACKAGE_CONFIG = createError( + 'ERR_INVALID_PACKAGE_CONFIG', + /** + * @param {string} path + * @param {string} [base] + * @param {string} [message] + */ + (path, base, message) => { + return `Invalid package config ${path}${ + base ? ` while importing ${base}` : '' + }${message ? `. ${message}` : ''}` + }, + Error +); + +codes.ERR_INVALID_PACKAGE_TARGET = createError( + 'ERR_INVALID_PACKAGE_TARGET', + /** + * @param {string} pkgPath + * @param {string} key + * @param {unknown} target + * @param {boolean} [isImport=false] + * @param {string} [base] + */ + (pkgPath, key, target, isImport = false, base = undefined) => { + const relError = + typeof target === 'string' && + !isImport && + target.length > 0 && + !target.startsWith('./'); + if (key === '.') { + assert(isImport === false); + return ( + `Invalid "exports" main target ${JSON.stringify(target)} defined ` + + `in the package config ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }${relError ? '; targets must start with "./"' : ''}` + ) + } + + return `Invalid "${ + isImport ? 'imports' : 'exports' + }" target ${JSON.stringify( + target + )} defined for '${key}' in the package config ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }${relError ? '; targets must start with "./"' : ''}` + }, + Error +); + +codes.ERR_MODULE_NOT_FOUND = createError( + 'ERR_MODULE_NOT_FOUND', + /** + * @param {string} path + * @param {string} base + * @param {boolean} [exactUrl] + */ + (path, base, exactUrl = false) => { + return `Cannot find ${ + exactUrl ? 'module' : 'package' + } '${path}' imported from ${base}` + }, + Error +); + +codes.ERR_NETWORK_IMPORT_DISALLOWED = createError( + 'ERR_NETWORK_IMPORT_DISALLOWED', + "import of '%s' by %s is not supported: %s", + Error +); + +codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError( + 'ERR_PACKAGE_IMPORT_NOT_DEFINED', + /** + * @param {string} specifier + * @param {string} packagePath + * @param {string} base + */ + (specifier, packagePath, base) => { + return `Package import specifier "${specifier}" is not defined${ + packagePath ? ` in package ${packagePath}package.json` : '' + } imported from ${base}` + }, + TypeError +); + +codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError( + 'ERR_PACKAGE_PATH_NOT_EXPORTED', + /** + * @param {string} pkgPath + * @param {string} subpath + * @param {string} [base] + */ + (pkgPath, subpath, base = undefined) => { + if (subpath === '.') + return `No "exports" main defined in ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }` + return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${ + base ? ` imported from ${base}` : '' + }` + }, + Error +); + +codes.ERR_UNSUPPORTED_DIR_IMPORT = createError( + 'ERR_UNSUPPORTED_DIR_IMPORT', + "Directory import '%s' is not supported " + + 'resolving ES modules imported from %s', + Error +); + +codes.ERR_UNKNOWN_FILE_EXTENSION = createError( + 'ERR_UNKNOWN_FILE_EXTENSION', + /** + * @param {string} ext + * @param {string} path + */ + (ext, path) => { + return `Unknown file extension "${ext}" for ${path}` + }, + TypeError +); + +codes.ERR_INVALID_ARG_VALUE = createError( + 'ERR_INVALID_ARG_VALUE', + /** + * @param {string} name + * @param {unknown} value + * @param {string} [reason='is invalid'] + */ + (name, value, reason = 'is invalid') => { + let inspected = inspect(value); + + if (inspected.length > 128) { + inspected = `${inspected.slice(0, 128)}...`; + } + + const type = name.includes('.') ? 'property' : 'argument'; + + return `The ${type} '${name}' ${reason}. Received ${inspected}` + }, + TypeError + // Note: extra classes have been shaken out. + // , RangeError +); + +/** + * Utility function for registering the error codes. Only used here. Exported + * *only* to allow for testing. + * @param {string} sym + * @param {MessageFunction | string} value + * @param {ErrorConstructor} def + * @returns {new (...args: Array) => Error} + */ +function createError(sym, value, def) { + // Special case for SystemError that formats the error message differently + // The SystemErrors only have SystemError as their base classes. + messages.set(sym, value); + + return makeNodeErrorWithCode(def, sym) +} + +/** + * @param {ErrorConstructor} Base + * @param {string} key + * @returns {ErrorConstructor} + */ +function makeNodeErrorWithCode(Base, key) { + // @ts-expect-error It’s a Node error. + return NodeError + /** + * @param {Array} args + */ + function NodeError(...args) { + const limit = Error.stackTraceLimit; + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; + const error = new Base(); + // Reset the limit and setting the name property. + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; + const message = getMessage(key, args, error); + Object.defineProperties(error, { + // Note: no need to implement `kIsNodeError` symbol, would be hard, + // probably. + message: { + value: message, + enumerable: false, + writable: true, + configurable: true + }, + toString: { + /** @this {Error} */ + value() { + return `${this.name} [${key}]: ${this.message}` + }, + enumerable: false, + writable: true, + configurable: true + } + }); + + captureLargerStackTrace(error); + // @ts-expect-error It’s a Node error. + error.code = key; + return error + } +} + +/** + * @returns {boolean} + */ +function isErrorStackTraceLimitWritable() { + // Do no touch Error.stackTraceLimit as V8 would attempt to install + // it again during deserialization. + try { + // @ts-expect-error: not in types? + if (v8.startupSnapshot.isBuildingSnapshot()) { + return false + } + } catch {} + + const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); + if (desc === undefined) { + return Object.isExtensible(Error) + } + + return own$1.call(desc, 'writable') && desc.writable !== undefined + ? desc.writable + : desc.set !== undefined +} + +/** + * This function removes unnecessary frames from Node.js core errors. + * @template {(...args: unknown[]) => unknown} T + * @param {T} fn + * @returns {T} + */ +function hideStackFrames(fn) { + // We rename the functions that will be hidden to cut off the stacktrace + // at the outermost one + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, 'name', {value: hidden}); + return fn +} + +const captureLargerStackTrace = hideStackFrames( + /** + * @param {Error} error + * @returns {Error} + */ + // @ts-expect-error: fine + function (error) { + const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); + if (stackTraceLimitIsWritable) { + userStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Number.POSITIVE_INFINITY; + } + + Error.captureStackTrace(error); + + // Reset the limit + if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; + + return error + } +); + +/** + * @param {string} key + * @param {Array} args + * @param {Error} self + * @returns {string} + */ +function getMessage(key, args, self) { + const message = messages.get(key); + assert(message !== undefined, 'expected `message` to be found'); + + if (typeof message === 'function') { + assert( + message.length <= args.length, // Default options do not count. + `Code: ${key}; The provided arguments length (${args.length}) does not ` + + `match the required ones (${message.length}).` + ); + return Reflect.apply(message, self, args) + } + + const regex = /%[dfijoOs]/g; + let expectedLength = 0; + while (regex.exec(message) !== null) expectedLength++; + assert( + expectedLength === args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not ` + + `match the required ones (${expectedLength}).` + ); + if (args.length === 0) return message + + args.unshift(message); + return Reflect.apply(format, null, args) +} + +/** + * Determine the specific type of a value for type-mismatch errors. + * @param {unknown} value + * @returns {string} + */ +function determineSpecificType(value) { + if (value === null || value === undefined) { + return String(value) + } + + if (typeof value === 'function' && value.name) { + return `function ${value.name}` + } + + if (typeof value === 'object') { + if (value.constructor && value.constructor.name) { + return `an instance of ${value.constructor.name}` + } + + return `${inspect(value, {depth: -1})}` + } + + let inspected = inspect(value, {colors: false}); + + if (inspected.length > 28) { + inspected = `${inspected.slice(0, 25)}...`; + } + + return `type ${typeof value} (${inspected})` +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. +// Removed the native dependency. +// Also: no need to cache, we do that in resolve already. + + +const hasOwnProperty$1 = {}.hasOwnProperty; + +const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes; + +/** @type {Map} */ +const cache = new Map(); + +const reader = {read}; +const packageJsonReader = reader; + +/** + * @param {string} jsonPath + * @param {{specifier: URL | string, base?: URL}} options + * @returns {PackageConfig} + */ +function read(jsonPath, {base, specifier}) { + const existing = cache.get(jsonPath); + + if (existing) { + return existing + } + + /** @type {string | undefined} */ + let string; + + try { + string = fs.readFileSync(path.toNamespacedPath(jsonPath), 'utf8'); + } catch (error) { + const exception = /** @type {ErrnoException} */ (error); + + if (exception.code !== 'ENOENT') { + throw exception + } + } + + /** @type {PackageConfig} */ + const result = { + exists: false, + pjsonPath: jsonPath, + main: undefined, + name: undefined, + type: 'none', // Ignore unknown types for forwards compatibility + exports: undefined, + imports: undefined + }; + + if (string !== undefined) { + /** @type {Record} */ + let parsed; + + try { + parsed = JSON.parse(string); + } catch (error_) { + const cause = /** @type {ErrnoException} */ (error_); + const error = new ERR_INVALID_PACKAGE_CONFIG$1( + jsonPath, + (base ? `"${specifier}" from ` : '') + fileURLToPath$1(base || specifier), + cause.message + ); + // @ts-expect-error: fine. + error.cause = cause; + throw error + } + + result.exists = true; + + if ( + hasOwnProperty$1.call(parsed, 'name') && + typeof parsed.name === 'string' + ) { + result.name = parsed.name; + } + + if ( + hasOwnProperty$1.call(parsed, 'main') && + typeof parsed.main === 'string' + ) { + result.main = parsed.main; + } + + if (hasOwnProperty$1.call(parsed, 'exports')) { + // @ts-expect-error: assume valid. + result.exports = parsed.exports; + } + + if (hasOwnProperty$1.call(parsed, 'imports')) { + // @ts-expect-error: assume valid. + result.imports = parsed.imports; + } + + // Ignore unknown types for forwards compatibility + if ( + hasOwnProperty$1.call(parsed, 'type') && + (parsed.type === 'commonjs' || parsed.type === 'module') + ) { + result.type = parsed.type; + } + } + + cache.set(jsonPath, result); + + return result +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. + + +/** + * @param {URL | string} resolved + * @returns {PackageConfig} + */ +function getPackageScopeConfig(resolved) { + let packageJSONUrl = new URL$1('package.json', resolved); + + while (true) { + const packageJSONPath = packageJSONUrl.pathname; + if (packageJSONPath.endsWith('node_modules/package.json')) { + break + } + + const packageConfig = packageJsonReader.read( + fileURLToPath$1(packageJSONUrl), + {specifier: resolved} + ); + + if (packageConfig.exists) { + return packageConfig + } + + const lastPackageJSONUrl = packageJSONUrl; + packageJSONUrl = new URL$1('../package.json', packageJSONUrl); + + // Terminates at root where ../package.json equals ../../package.json + // (can't just check "/package.json" for Windows support). + if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) { + break + } + } + + const packageJSONPath = fileURLToPath$1(packageJSONUrl); + + return { + pjsonPath: packageJSONPath, + exists: false, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + } +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. +// +// This file solves a circular dependency. +// In Node.js, `getPackageType` is in `resolve.js`. +// `resolve.js` imports `get-format.js`, which needs `getPackageType`. +// We split that up so that bundlers don’t fail. + + +/** + * @param {URL} url + * @returns {PackageType} + */ +function getPackageType(url) { + const packageConfig = getPackageScopeConfig(url); + return packageConfig.type +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. + + +const {ERR_UNKNOWN_FILE_EXTENSION} = codes; + +const hasOwnProperty = {}.hasOwnProperty; + +/** @type {Record} */ +const extensionFormatMap = { + // @ts-expect-error: hush. + __proto__: null, + '.cjs': 'commonjs', + '.js': 'module', + '.json': 'json', + '.mjs': 'module' +}; + +/** + * @param {string | null} mime + * @returns {string | null} + */ +function mimeToFormat(mime) { + if ( + mime && + /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime) + ) + return 'module' + if (mime === 'application/json') return 'json' + return null +} + +/** + * @callback ProtocolHandler + * @param {URL} parsed + * @param {{parentURL: string, source?: Buffer}} context + * @param {boolean} ignoreErrors + * @returns {string | null | void} + */ + +/** + * @type {Record} + */ +const protocolHandlers = { + // @ts-expect-error: hush. + __proto__: null, + 'data:': getDataProtocolModuleFormat, + 'file:': getFileProtocolModuleFormat, + 'http:': getHttpProtocolModuleFormat, + 'https:': getHttpProtocolModuleFormat, + 'node:'() { + return 'builtin' + } +}; + +/** + * @param {URL} parsed + */ +function getDataProtocolModuleFormat(parsed) { + const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec( + parsed.pathname + ) || [null, null, null]; + return mimeToFormat(mime) +} + +/** + * Returns the file extension from a URL. + * + * Should give similar result to + * `require('node:path').extname(require('node:url').fileURLToPath(url))` + * when used with a `file:` URL. + * + * @param {URL} url + * @returns {string} + */ +function extname(url) { + const pathname = url.pathname; + let index = pathname.length; + + while (index--) { + const code = pathname.codePointAt(index); + + if (code === 47 /* `/` */) { + return '' + } + + if (code === 46 /* `.` */) { + return pathname.codePointAt(index - 1) === 47 /* `/` */ + ? '' + : pathname.slice(index) + } + } + + return '' +} + +/** + * @type {ProtocolHandler} + */ +function getFileProtocolModuleFormat(url, _context, ignoreErrors) { + const ext = extname(url); + + if (ext === '.js') { + const packageType = getPackageType(url); + + if (packageType !== 'none') { + return packageType + } + + return 'commonjs' + } + + if (ext === '') { + const packageType = getPackageType(url); + + // Legacy behavior + if (packageType === 'none' || packageType === 'commonjs') { + return 'commonjs' + } + + // Note: we don’t implement WASM, so we don’t need + // `getFormatOfExtensionlessFile` from `formats`. + return 'module' + } + + const format = extensionFormatMap[ext]; + if (format) return format + + // Explicit undefined return indicates load hook should rerun format check + if (ignoreErrors) { + return undefined + } + + const filepath = fileURLToPath$1(url); + throw new ERR_UNKNOWN_FILE_EXTENSION(ext, filepath) +} + +function getHttpProtocolModuleFormat() { + // To do: HTTPS imports. +} + +/** + * @param {URL} url + * @param {{parentURL: string}} context + * @returns {string | null} + */ +function defaultGetFormatWithoutErrors(url, context) { + const protocol = url.protocol; + + if (!hasOwnProperty.call(protocolHandlers, protocol)) { + return null + } + + return protocolHandlers[protocol](url, context, true) || null +} + +// Manually “tree shaken” from: +// +// Last checked on: Nov 2, 2023. + + +const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace]; + +const { + ERR_NETWORK_IMPORT_DISALLOWED, + ERR_INVALID_MODULE_SPECIFIER, + ERR_INVALID_PACKAGE_CONFIG, + ERR_INVALID_PACKAGE_TARGET, + ERR_MODULE_NOT_FOUND, + ERR_PACKAGE_IMPORT_NOT_DEFINED, + ERR_PACKAGE_PATH_NOT_EXPORTED, + ERR_UNSUPPORTED_DIR_IMPORT +} = codes; + +const own = {}.hasOwnProperty; + +const invalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; +const deprecatedInvalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; +const invalidPackageNameRegEx = /^\.|%|\\/; +const patternRegEx = /\*/g; +const encodedSepRegEx = /%2f|%5c/i; +/** @type {Set} */ +const emittedPackageWarnings = new Set(); + +const doubleSlashRegEx = /[/\\]{2}/; + +/** + * + * @param {string} target + * @param {string} request + * @param {string} match + * @param {URL} packageJsonUrl + * @param {boolean} internal + * @param {URL} base + * @param {boolean} isTarget + */ +function emitInvalidSegmentDeprecation( + target, + request, + match, + packageJsonUrl, + internal, + base, + isTarget +) { + // @ts-expect-error: apparently it does exist, TS. + if (process$1.noDeprecation) { + return + } + + const pjsonPath = fileURLToPath$1(packageJsonUrl); + const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null; + process$1.emitWarning( + `Use of deprecated ${ + double ? 'double slash' : 'leading or trailing slash matching' + } resolving "${target}" for module ` + + `request "${request}" ${ + request === match ? '' : `matched to "${match}" ` + }in the "${ + internal ? 'imports' : 'exports' + }" field module resolution of the package at ${pjsonPath}${ + base ? ` imported from ${fileURLToPath$1(base)}` : '' + }.`, + 'DeprecationWarning', + 'DEP0166' + ); +} + +/** + * @param {URL} url + * @param {URL} packageJsonUrl + * @param {URL} base + * @param {string} [main] + * @returns {void} + */ +function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { + // @ts-expect-error: apparently it does exist, TS. + if (process$1.noDeprecation) { + return + } + + const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href}); + if (format !== 'module') return + const urlPath = fileURLToPath$1(url.href); + const pkgPath = fileURLToPath$1(new URL$1('.', packageJsonUrl)); + const basePath = fileURLToPath$1(base); + if (!main) { + process$1.emitWarning( + `No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${urlPath.slice( + pkgPath.length + )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, + 'DeprecationWarning', + 'DEP0151' + ); + } else if (path.resolve(pkgPath, main) !== urlPath) { + process$1.emitWarning( + `Package ${pkgPath} has a "main" field set to "${main}", ` + + `excluding the full filename and extension to the resolved file at "${urlPath.slice( + pkgPath.length + )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` + + 'deprecated for ES modules.', + 'DeprecationWarning', + 'DEP0151' + ); + } +} + +/** + * @param {string} path + * @returns {Stats} + */ +function tryStatSync(path) { + // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead. + try { + return statSync(path) + } catch { + return new Stats() + } +} + +/** + * Legacy CommonJS main resolution: + * 1. let M = pkg_url + (json main field) + * 2. TRY(M, M.js, M.json, M.node) + * 3. TRY(M/index.js, M/index.json, M/index.node) + * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) + * 5. NOT_FOUND + * + * @param {URL} url + * @returns {boolean} + */ +function fileExists(url) { + const stats = statSync(url, {throwIfNoEntry: false}); + const isFile = stats ? stats.isFile() : undefined; + return isFile === null || isFile === undefined ? false : isFile +} + +/** + * @param {URL} packageJsonUrl + * @param {PackageConfig} packageConfig + * @param {URL} base + * @returns {URL} + */ +function legacyMainResolve(packageJsonUrl, packageConfig, base) { + /** @type {URL | undefined} */ + let guess; + if (packageConfig.main !== undefined) { + guess = new URL$1(packageConfig.main, packageJsonUrl); + // Note: fs check redundances will be handled by Descriptor cache here. + if (fileExists(guess)) return guess + + const tries = [ + `./${packageConfig.main}.js`, + `./${packageConfig.main}.json`, + `./${packageConfig.main}.node`, + `./${packageConfig.main}/index.js`, + `./${packageConfig.main}/index.json`, + `./${packageConfig.main}/index.node` + ]; + let i = -1; + + while (++i < tries.length) { + guess = new URL$1(tries[i], packageJsonUrl); + if (fileExists(guess)) break + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation( + guess, + packageJsonUrl, + base, + packageConfig.main + ); + return guess + } + // Fallthrough. + } + + const tries = ['./index.js', './index.json', './index.node']; + let i = -1; + + while (++i < tries.length) { + guess = new URL$1(tries[i], packageJsonUrl); + if (fileExists(guess)) break + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess + } + + // Not found. + throw new ERR_MODULE_NOT_FOUND( + fileURLToPath$1(new URL$1('.', packageJsonUrl)), + fileURLToPath$1(base) + ) +} + +/** + * @param {URL} resolved + * @param {URL} base + * @param {boolean} [preserveSymlinks] + * @returns {URL} + */ +function finalizeResolution(resolved, base, preserveSymlinks) { + if (encodedSepRegEx.exec(resolved.pathname) !== null) { + throw new ERR_INVALID_MODULE_SPECIFIER( + resolved.pathname, + 'must not include encoded "/" or "\\" characters', + fileURLToPath$1(base) + ) + } + + /** @type {string} */ + let filePath; + + try { + filePath = fileURLToPath$1(resolved); + } catch (error) { + const cause = /** @type {ErrnoException} */ (error); + Object.defineProperty(cause, 'input', {value: String(resolved)}); + Object.defineProperty(cause, 'module', {value: String(base)}); + throw cause + } + + const stats = tryStatSync( + filePath.endsWith('/') ? filePath.slice(-1) : filePath + ); + + if (stats.isDirectory()) { + const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base)); + // @ts-expect-error Add this for `import.meta.resolve`. + error.url = String(resolved); + throw error + } + + if (!stats.isFile()) { + const error = new ERR_MODULE_NOT_FOUND( + filePath || resolved.pathname, + base && fileURLToPath$1(base), + true + ); + // @ts-expect-error Add this for `import.meta.resolve`. + error.url = String(resolved); + throw error + } + + if (!preserveSymlinks) { + const real = realpathSync(filePath); + const {search, hash} = resolved; + resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? '/' : '')); + resolved.search = search; + resolved.hash = hash; + } + + return resolved +} + +/** + * @param {string} specifier + * @param {URL | undefined} packageJsonUrl + * @param {URL} base + * @returns {Error} + */ +function importNotDefined(specifier, packageJsonUrl, base) { + return new ERR_PACKAGE_IMPORT_NOT_DEFINED( + specifier, + packageJsonUrl && fileURLToPath$1(new URL$1('.', packageJsonUrl)), + fileURLToPath$1(base) + ) +} + +/** + * @param {string} subpath + * @param {URL} packageJsonUrl + * @param {URL} base + * @returns {Error} + */ +function exportsNotFound(subpath, packageJsonUrl, base) { + return new ERR_PACKAGE_PATH_NOT_EXPORTED( + fileURLToPath$1(new URL$1('.', packageJsonUrl)), + subpath, + base && fileURLToPath$1(base) + ) +} + +/** + * @param {string} request + * @param {string} match + * @param {URL} packageJsonUrl + * @param {boolean} internal + * @param {URL} [base] + * @returns {never} + */ +function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) { + const reason = `request is not a valid match in pattern "${match}" for the "${ + internal ? 'imports' : 'exports' + }" resolution of ${fileURLToPath$1(packageJsonUrl)}`; + throw new ERR_INVALID_MODULE_SPECIFIER( + request, + reason, + base && fileURLToPath$1(base) + ) +} + +/** + * @param {string} subpath + * @param {unknown} target + * @param {URL} packageJsonUrl + * @param {boolean} internal + * @param {URL} [base] + * @returns {Error} + */ +function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { + target = + typeof target === 'object' && target !== null + ? JSON.stringify(target, null, '') + : `${target}`; + + return new ERR_INVALID_PACKAGE_TARGET( + fileURLToPath$1(new URL$1('.', packageJsonUrl)), + subpath, + target, + internal, + base && fileURLToPath$1(base) + ) +} + +/** + * @param {string} target + * @param {string} subpath + * @param {string} match + * @param {URL} packageJsonUrl + * @param {URL} base + * @param {boolean} pattern + * @param {boolean} internal + * @param {boolean} isPathMap + * @param {Set | undefined} conditions + * @returns {URL} + */ +function resolvePackageTargetString( + target, + subpath, + match, + packageJsonUrl, + base, + pattern, + internal, + isPathMap, + conditions +) { + if (subpath !== '' && !pattern && target[target.length - 1] !== '/') + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + + if (!target.startsWith('./')) { + if (internal && !target.startsWith('../') && !target.startsWith('/')) { + let isURL = false; + + try { + new URL$1(target); + isURL = true; + } catch { + // Continue regardless of error. + } + + if (!isURL) { + const exportTarget = pattern + ? RegExpPrototypeSymbolReplace.call( + patternRegEx, + target, + () => subpath + ) + : target + subpath; + + return packageResolve(exportTarget, packageJsonUrl, conditions) + } + } + + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + } + + if (invalidSegmentRegEx.exec(target.slice(2)) !== null) { + if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) { + if (!isPathMap) { + const request = pattern + ? match.replace('*', () => subpath) + : match + subpath; + const resolvedTarget = pattern + ? RegExpPrototypeSymbolReplace.call( + patternRegEx, + target, + () => subpath + ) + : target; + emitInvalidSegmentDeprecation( + resolvedTarget, + request, + match, + packageJsonUrl, + internal, + base, + true + ); + } + } else { + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + } + } + + const resolved = new URL$1(target, packageJsonUrl); + const resolvedPath = resolved.pathname; + const packagePath = new URL$1('.', packageJsonUrl).pathname; + + if (!resolvedPath.startsWith(packagePath)) + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base) + + if (subpath === '') return resolved + + if (invalidSegmentRegEx.exec(subpath) !== null) { + const request = pattern + ? match.replace('*', () => subpath) + : match + subpath; + if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) { + if (!isPathMap) { + const resolvedTarget = pattern + ? RegExpPrototypeSymbolReplace.call( + patternRegEx, + target, + () => subpath + ) + : target; + emitInvalidSegmentDeprecation( + resolvedTarget, + request, + match, + packageJsonUrl, + internal, + base, + false + ); + } + } else { + throwInvalidSubpath(request, match, packageJsonUrl, internal, base); + } + } + + if (pattern) { + return new URL$1( + RegExpPrototypeSymbolReplace.call( + patternRegEx, + resolved.href, + () => subpath + ) + ) + } + + return new URL$1(subpath, resolved) +} + +/** + * @param {string} key + * @returns {boolean} + */ +function isArrayIndex(key) { + const keyNumber = Number(key); + if (`${keyNumber}` !== key) return false + return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff +} + +/** + * @param {URL} packageJsonUrl + * @param {unknown} target + * @param {string} subpath + * @param {string} packageSubpath + * @param {URL} base + * @param {boolean} pattern + * @param {boolean} internal + * @param {boolean} isPathMap + * @param {Set | undefined} conditions + * @returns {URL | null} + */ +function resolvePackageTarget( + packageJsonUrl, + target, + subpath, + packageSubpath, + base, + pattern, + internal, + isPathMap, + conditions +) { + if (typeof target === 'string') { + return resolvePackageTargetString( + target, + subpath, + packageSubpath, + packageJsonUrl, + base, + pattern, + internal, + isPathMap, + conditions + ) + } + + if (Array.isArray(target)) { + /** @type {Array} */ + const targetList = target; + if (targetList.length === 0) return null + + /** @type {ErrnoException | null | undefined} */ + let lastException; + let i = -1; + + while (++i < targetList.length) { + const targetItem = targetList[i]; + /** @type {URL | null} */ + let resolveResult; + try { + resolveResult = resolvePackageTarget( + packageJsonUrl, + targetItem, + subpath, + packageSubpath, + base, + pattern, + internal, + isPathMap, + conditions + ); + } catch (error) { + const exception = /** @type {ErrnoException} */ (error); + lastException = exception; + if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue + throw error + } + + if (resolveResult === undefined) continue + + if (resolveResult === null) { + lastException = null; + continue + } + + return resolveResult + } + + if (lastException === undefined || lastException === null) { + return null + } + + throw lastException + } + + if (typeof target === 'object' && target !== null) { + const keys = Object.getOwnPropertyNames(target); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + if (isArrayIndex(key)) { + throw new ERR_INVALID_PACKAGE_CONFIG( + fileURLToPath$1(packageJsonUrl), + base, + '"exports" cannot contain numeric property keys.' + ) + } + } + + i = -1; + + while (++i < keys.length) { + const key = keys[i]; + if (key === 'default' || (conditions && conditions.has(key))) { + // @ts-expect-error: indexable. + const conditionalTarget = /** @type {unknown} */ (target[key]); + const resolveResult = resolvePackageTarget( + packageJsonUrl, + conditionalTarget, + subpath, + packageSubpath, + base, + pattern, + internal, + isPathMap, + conditions + ); + if (resolveResult === undefined) continue + return resolveResult + } + } + + return null + } + + if (target === null) { + return null + } + + throw invalidPackageTarget( + packageSubpath, + target, + packageJsonUrl, + internal, + base + ) +} + +/** + * @param {unknown} exports + * @param {URL} packageJsonUrl + * @param {URL} base + * @returns {boolean} + */ +function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { + if (typeof exports === 'string' || Array.isArray(exports)) return true + if (typeof exports !== 'object' || exports === null) return false + + const keys = Object.getOwnPropertyNames(exports); + let isConditionalSugar = false; + let i = 0; + let j = -1; + while (++j < keys.length) { + const key = keys[j]; + const curIsConditionalSugar = key === '' || key[0] !== '.'; + if (i++ === 0) { + isConditionalSugar = curIsConditionalSugar; + } else if (isConditionalSugar !== curIsConditionalSugar) { + throw new ERR_INVALID_PACKAGE_CONFIG( + fileURLToPath$1(packageJsonUrl), + base, + '"exports" cannot contain some keys starting with \'.\' and some not.' + + ' The exports object must either be an object of package subpath keys' + + ' or an object of main entry condition name keys only.' + ) + } + } + + return isConditionalSugar +} + +/** + * @param {string} match + * @param {URL} pjsonUrl + * @param {URL} base + */ +function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { + // @ts-expect-error: apparently it does exist, TS. + if (process$1.noDeprecation) { + return + } + + const pjsonPath = fileURLToPath$1(pjsonUrl); + if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return + emittedPackageWarnings.add(pjsonPath + '|' + match); + process$1.emitWarning( + `Use of deprecated trailing slash pattern mapping "${match}" in the ` + + `"exports" field module resolution of the package at ${pjsonPath}${ + base ? ` imported from ${fileURLToPath$1(base)}` : '' + }. Mapping specifiers ending in "/" is no longer supported.`, + 'DeprecationWarning', + 'DEP0155' + ); +} + +/** + * @param {URL} packageJsonUrl + * @param {string} packageSubpath + * @param {Record} packageConfig + * @param {URL} base + * @param {Set | undefined} conditions + * @returns {URL} + */ +function packageExportsResolve( + packageJsonUrl, + packageSubpath, + packageConfig, + base, + conditions +) { + let exports = packageConfig.exports; + + if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) { + exports = {'.': exports}; + } + + if ( + own.call(exports, packageSubpath) && + !packageSubpath.includes('*') && + !packageSubpath.endsWith('/') + ) { + // @ts-expect-error: indexable. + const target = exports[packageSubpath]; + const resolveResult = resolvePackageTarget( + packageJsonUrl, + target, + '', + packageSubpath, + base, + false, + false, + false, + conditions + ); + if (resolveResult === null || resolveResult === undefined) { + throw exportsNotFound(packageSubpath, packageJsonUrl, base) + } + + return resolveResult + } + + let bestMatch = ''; + let bestMatchSubpath = ''; + const keys = Object.getOwnPropertyNames(exports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + const patternIndex = key.indexOf('*'); + + if ( + patternIndex !== -1 && + packageSubpath.startsWith(key.slice(0, patternIndex)) + ) { + // When this reaches EOL, this can throw at the top of the whole function: + // + // if (StringPrototypeEndsWith(packageSubpath, '/')) + // throwInvalidSubpath(packageSubpath) + // + // To match "imports" and the spec. + if (packageSubpath.endsWith('/')) { + emitTrailingSlashPatternDeprecation( + packageSubpath, + packageJsonUrl, + base + ); + } + + const patternTrailer = key.slice(patternIndex + 1); + + if ( + packageSubpath.length >= key.length && + packageSubpath.endsWith(patternTrailer) && + patternKeyCompare(bestMatch, key) === 1 && + key.lastIndexOf('*') === patternIndex + ) { + bestMatch = key; + bestMatchSubpath = packageSubpath.slice( + patternIndex, + packageSubpath.length - patternTrailer.length + ); + } + } + } + + if (bestMatch) { + // @ts-expect-error: indexable. + const target = /** @type {unknown} */ (exports[bestMatch]); + const resolveResult = resolvePackageTarget( + packageJsonUrl, + target, + bestMatchSubpath, + bestMatch, + base, + true, + false, + packageSubpath.endsWith('/'), + conditions + ); + + if (resolveResult === null || resolveResult === undefined) { + throw exportsNotFound(packageSubpath, packageJsonUrl, base) + } + + return resolveResult + } + + throw exportsNotFound(packageSubpath, packageJsonUrl, base) +} + +/** + * @param {string} a + * @param {string} b + */ +function patternKeyCompare(a, b) { + const aPatternIndex = a.indexOf('*'); + const bPatternIndex = b.indexOf('*'); + const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLengthA > baseLengthB) return -1 + if (baseLengthB > baseLengthA) return 1 + if (aPatternIndex === -1) return 1 + if (bPatternIndex === -1) return -1 + if (a.length > b.length) return -1 + if (b.length > a.length) return 1 + return 0 +} + +/** + * @param {string} name + * @param {URL} base + * @param {Set} [conditions] + * @returns {URL} + */ +function packageImportsResolve(name, base, conditions) { + if (name === '#' || name.startsWith('#/') || name.endsWith('/')) { + const reason = 'is not a valid internal imports specifier name'; + throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base)) + } + + /** @type {URL | undefined} */ + let packageJsonUrl; + + const packageConfig = getPackageScopeConfig(base); + + if (packageConfig.exists) { + packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath); + const imports = packageConfig.imports; + if (imports) { + if (own.call(imports, name) && !name.includes('*')) { + const resolveResult = resolvePackageTarget( + packageJsonUrl, + imports[name], + '', + name, + base, + false, + true, + false, + conditions + ); + if (resolveResult !== null && resolveResult !== undefined) { + return resolveResult + } + } else { + let bestMatch = ''; + let bestMatchSubpath = ''; + const keys = Object.getOwnPropertyNames(imports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + const patternIndex = key.indexOf('*'); + + if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) { + const patternTrailer = key.slice(patternIndex + 1); + if ( + name.length >= key.length && + name.endsWith(patternTrailer) && + patternKeyCompare(bestMatch, key) === 1 && + key.lastIndexOf('*') === patternIndex + ) { + bestMatch = key; + bestMatchSubpath = name.slice( + patternIndex, + name.length - patternTrailer.length + ); + } + } + } + + if (bestMatch) { + const target = imports[bestMatch]; + const resolveResult = resolvePackageTarget( + packageJsonUrl, + target, + bestMatchSubpath, + bestMatch, + base, + true, + true, + false, + conditions + ); + + if (resolveResult !== null && resolveResult !== undefined) { + return resolveResult + } + } + } + } + } + + throw importNotDefined(name, packageJsonUrl, base) +} + +// Note: In Node.js, `getPackageType` is here. +// To prevent a circular dependency, we move it to +// `resolve-get-package-type.js`. + +/** + * @param {string} specifier + * @param {URL} base + */ +function parsePackageName(specifier, base) { + let separatorIndex = specifier.indexOf('/'); + let validPackageName = true; + let isScoped = false; + if (specifier[0] === '@') { + isScoped = true; + if (separatorIndex === -1 || specifier.length === 0) { + validPackageName = false; + } else { + separatorIndex = specifier.indexOf('/', separatorIndex + 1); + } + } + + const packageName = + separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); + + // Package name cannot have leading . and cannot have percent-encoding or + // \\ separators. + if (invalidPackageNameRegEx.exec(packageName) !== null) { + validPackageName = false; + } + + if (!validPackageName) { + throw new ERR_INVALID_MODULE_SPECIFIER( + specifier, + 'is not a valid package name', + fileURLToPath$1(base) + ) + } + + const packageSubpath = + '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex)); + + return {packageName, packageSubpath, isScoped} +} + +/** + * @param {string} specifier + * @param {URL} base + * @param {Set | undefined} conditions + * @returns {URL} + */ +function packageResolve(specifier, base, conditions) { + if (builtinModules.includes(specifier)) { + return new URL$1('node:' + specifier) + } + + const {packageName, packageSubpath, isScoped} = parsePackageName( + specifier, + base + ); + + // ResolveSelf + const packageConfig = getPackageScopeConfig(base); + + // Can’t test. + /* c8 ignore next 16 */ + if (packageConfig.exists) { + const packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath); + if ( + packageConfig.name === packageName && + packageConfig.exports !== undefined && + packageConfig.exports !== null + ) { + return packageExportsResolve( + packageJsonUrl, + packageSubpath, + packageConfig, + base, + conditions + ) + } + } + + let packageJsonUrl = new URL$1( + './node_modules/' + packageName + '/package.json', + base + ); + let packageJsonPath = fileURLToPath$1(packageJsonUrl); + /** @type {string} */ + let lastPath; + do { + const stat = tryStatSync(packageJsonPath.slice(0, -13)); + if (!stat.isDirectory()) { + lastPath = packageJsonPath; + packageJsonUrl = new URL$1( + (isScoped ? '../../../../node_modules/' : '../../../node_modules/') + + packageName + + '/package.json', + packageJsonUrl + ); + packageJsonPath = fileURLToPath$1(packageJsonUrl); + continue + } + + // Package match. + const packageConfig = packageJsonReader.read(packageJsonPath, { + base, + specifier + }); + if (packageConfig.exports !== undefined && packageConfig.exports !== null) { + return packageExportsResolve( + packageJsonUrl, + packageSubpath, + packageConfig, + base, + conditions + ) + } + + if (packageSubpath === '.') { + return legacyMainResolve(packageJsonUrl, packageConfig, base) + } + + return new URL$1(packageSubpath, packageJsonUrl) + // Cross-platform root check. + } while (packageJsonPath.length !== lastPath.length) + + throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false) +} + +/** + * @param {string} specifier + * @returns {boolean} + */ +function isRelativeSpecifier(specifier) { + if (specifier[0] === '.') { + if (specifier.length === 1 || specifier[1] === '/') return true + if ( + specifier[1] === '.' && + (specifier.length === 2 || specifier[2] === '/') + ) { + return true + } + } + + return false +} + +/** + * @param {string} specifier + * @returns {boolean} + */ +function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { + if (specifier === '') return false + if (specifier[0] === '/') return true + return isRelativeSpecifier(specifier) +} + +/** + * The “Resolver Algorithm Specification” as detailed in the Node docs (which is + * sync and slightly lower-level than `resolve`). + * + * @param {string} specifier + * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc. + * @param {URL} base + * Full URL (to a file) that `specifier` is resolved relative from. + * @param {Set} [conditions] + * Conditions. + * @param {boolean} [preserveSymlinks] + * Keep symlinks instead of resolving them. + * @returns {URL} + * A URL object to the found thing. + */ +function moduleResolve(specifier, base, conditions, preserveSymlinks) { + const protocol = base.protocol; + const isRemote = protocol === 'http:' || protocol === 'https:'; + // Order swapped from spec for minor perf gain. + // Ok since relative URLs cannot parse as URLs. + /** @type {URL | undefined} */ + let resolved; + + if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { + resolved = new URL$1(specifier, base); + } else if (!isRemote && specifier[0] === '#') { + resolved = packageImportsResolve(specifier, base, conditions); + } else { + try { + resolved = new URL$1(specifier); + } catch { + if (!isRemote) { + resolved = packageResolve(specifier, base, conditions); + } + } + } + + assert(resolved !== undefined, 'expected to be defined'); + + if (resolved.protocol !== 'file:') { + return resolved + } + + return finalizeResolution(resolved, base, preserveSymlinks) +} + +function fileURLToPath(id) { + if (typeof id === "string" && !id.startsWith("file://")) { + return normalizeSlash(id); + } + return normalizeSlash(fileURLToPath$1(id)); +} +function pathToFileURL(id) { + return pathToFileURL$1(fileURLToPath(id)).toString(); +} +const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g; +function sanitizeURIComponent(name = "", replacement = "_") { + return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement); +} +function sanitizeFilePath(filePath = "") { + return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/"); +} +function normalizeid(id) { + if (typeof id !== "string") { + id = id.toString(); + } + if (/(node|data|http|https|file):/.test(id)) { + return id; + } + if (BUILTIN_MODULES.has(id)) { + return "node:" + id; + } + return "file://" + encodeURI(normalizeSlash(id)); +} +async function loadURL(url) { + const code = await promises.readFile(fileURLToPath(url), "utf8"); + return code; +} +function toDataURL(code) { + const base64 = Buffer.from(code).toString("base64"); + return `data:text/javascript;base64,${base64}`; +} +function isNodeBuiltin(id = "") { + id = id.replace(/^node:/, "").split("/")[0]; + return BUILTIN_MODULES.has(id); +} +const ProtocolRegex = /^(?.{2,}?):.+$/; +function getProtocol(id) { + const proto = id.match(ProtocolRegex); + return proto ? proto.groups?.proto : void 0; +} + +const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]); +const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"]; +const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([ + "ERR_MODULE_NOT_FOUND", + "ERR_UNSUPPORTED_DIR_IMPORT", + "MODULE_NOT_FOUND", + "ERR_PACKAGE_PATH_NOT_EXPORTED" +]); +function _tryModuleResolve(id, url, conditions) { + try { + return moduleResolve(id, url, conditions); + } catch (error) { + if (!NOT_FOUND_ERRORS.has(error?.code)) { + throw error; + } + } +} +function _resolve(id, options = {}) { + if (typeof id !== "string") { + if (id instanceof URL) { + id = fileURLToPath(id); + } else { + throw new TypeError("input must be a `string` or `URL`"); + } + } + if (/(node|data|http|https):/.test(id)) { + return id; + } + if (BUILTIN_MODULES.has(id)) { + return "node:" + id; + } + if (id.startsWith("file://")) { + id = fileURLToPath(id); + } + if (isAbsolute(id)) { + try { + const stat = statSync(id); + if (stat.isFile()) { + return pathToFileURL(id); + } + } catch (error) { + if (error?.code !== "ENOENT") { + throw error; + } + } + } + const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET; + const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString()))); + if (_urls.length === 0) { + _urls.push(new URL(pathToFileURL(process.cwd()))); + } + const urls = [..._urls]; + for (const url of _urls) { + if (url.protocol === "file:") { + urls.push( + new URL("./", url), + // If url is directory + new URL(joinURL(url.pathname, "_index.js"), url), + // TODO: Remove in next major version? + new URL("node_modules", url) + ); + } + } + let resolved; + for (const url of urls) { + resolved = _tryModuleResolve(id, url, conditionsSet); + if (resolved) { + break; + } + for (const prefix of ["", "/index"]) { + for (const extension of options.extensions || DEFAULT_EXTENSIONS) { + resolved = _tryModuleResolve( + id + prefix + extension, + url, + conditionsSet + ); + if (resolved) { + break; + } + } + if (resolved) { + break; + } + } + if (resolved) { + break; + } + } + if (!resolved) { + const error = new Error( + `Cannot find module ${id} imported from ${urls.join(", ")}` + ); + error.code = "ERR_MODULE_NOT_FOUND"; + throw error; + } + return pathToFileURL(resolved); +} +function resolveSync(id, options) { + return _resolve(id, options); +} +function resolve(id, options) { + try { + return Promise.resolve(resolveSync(id, options)); + } catch (error) { + return Promise.reject(error); + } +} +function resolvePathSync(id, options) { + return fileURLToPath(resolveSync(id, options)); +} +function resolvePath(id, options) { + try { + return Promise.resolve(resolvePathSync(id, options)); + } catch (error) { + return Promise.reject(error); + } +} +function createResolve(defaults) { + return (id, url) => { + return resolve(id, { url, ...defaults }); + }; +} +const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/; +function parseNodeModulePath(path) { + if (!path) { + return {}; + } + path = normalize(fileURLToPath(path)); + const match = NODE_MODULES_RE.exec(path); + if (!match) { + return {}; + } + const [, dir, name, subpath] = match; + return { + dir, + name, + subpath: subpath ? `.${subpath}` : void 0 + }; +} +async function lookupNodeModuleSubpath(path) { + path = normalize(fileURLToPath(path)); + const { name, subpath } = parseNodeModulePath(path); + if (!name || !subpath) { + return subpath; + } + const { exports } = await readPackageJSON(path).catch(() => { + }) || {}; + if (exports) { + const resolvedSubpath = _findSubpath(subpath, exports); + if (resolvedSubpath) { + return resolvedSubpath; + } + } + return subpath; +} +function _findSubpath(subpath, exports) { + if (typeof exports === "string") { + exports = { ".": exports }; + } + if (!subpath.startsWith(".")) { + subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`; + } + if (subpath in (exports || {})) { + return subpath; + } + return _flattenExports(exports).find((p) => p.fsPath === subpath)?.subpath; +} +function _flattenExports(exports = {}, parentSubpath = "./") { + return Object.entries(exports).flatMap(([key, value]) => { + const [subpath, condition] = key.startsWith(".") ? [key.slice(1), void 0] : ["", key]; + const _subPath = joinURL(parentSubpath, subpath); + if (typeof value === "string") { + return [{ subpath: _subPath, fsPath: value, condition }]; + } else { + return _flattenExports(value, _subPath); + } + }); +} + +const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*([\s"']*(?[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu; +const DYNAMIC_IMPORT_RE = /import\s*\((?(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm; +const IMPORT_NAMED_TYPE_RE = /(?<=\s|^|;|})import\s*type\s+([\s"']*(?[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm; +const EXPORT_DECAL_RE = /\bexport\s+(?(async function\s*\*?|function\s*\*?|let|const enum|const|enum|var|class))\s+\*?(?[\w$]+)(?.*,\s*[\w$]+)*/g; +const EXPORT_DECAL_TYPE_RE = /\bexport\s+(?(interface|type|declare (async function|function|let|const enum|const|enum|var|class)))\s+(?[\w$]+)/g; +const EXPORT_NAMED_RE = /\bexport\s+{(?[^}]+?)[\s,]*}(\s*from\s*["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; +const EXPORT_NAMED_TYPE_RE = /\bexport\s+type\s+{(?[^}]+?)[\s,]*}(\s*from\s*["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; +const EXPORT_NAMED_DESTRUCT = /\bexport\s+(let|var|const)\s+(?:{(?[^}]+?)[\s,]*}|\[(?[^\]]+?)[\s,]*])\s+=/gm; +const EXPORT_STAR_RE = /\bexport\s*(\*)(\s*as\s+(?[\w$]+)\s+)?\s*(\s*from\s*["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; +const EXPORT_DEFAULT_RE = /\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?.*)/g; +const TYPE_RE = /^\s*?type\s/; +function findStaticImports(code) { + return _filterStatement( + _tryGetLocations(code, "import"), + matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }) + ); +} +function findDynamicImports(code) { + return _filterStatement( + _tryGetLocations(code, "import"), + matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" }) + ); +} +function findTypeImports(code) { + return [ + ...matchAll(IMPORT_NAMED_TYPE_RE, code, { type: "type" }), + ...matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }).filter( + (match) => /[^A-Za-z]type\s/.test(match.imports) + ) + ]; +} +function parseStaticImport(matched) { + const cleanedImports = clearImports(matched.imports); + const namedImports = {}; + const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; + for (const namedImport of _matches) { + const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/); + const source = _match?.[1] || namedImport.trim(); + const importName = _match?.[2] || source; + if (source && !TYPE_RE.test(source)) { + namedImports[source] = importName; + } + } + const { namespacedImport, defaultImport } = getImportNames(cleanedImports); + return { + ...matched, + defaultImport, + namespacedImport, + namedImports + }; +} +function parseTypeImport(matched) { + if (matched.type === "type") { + return parseStaticImport(matched); + } + const cleanedImports = clearImports(matched.imports); + const namedImports = {}; + const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; + for (const namedImport of _matches) { + const _match = /\s+as\s+/.test(namedImport) ? namedImport.match(/^\s*type\s+(\S*) as (\S*)\s*$/) : namedImport.match(/^\s*type\s+(\S*)\s*$/); + const source = _match?.[1] || namedImport.trim(); + const importName = _match?.[2] || source; + if (source && TYPE_RE.test(namedImport)) { + namedImports[source] = importName; + } + } + const { namespacedImport, defaultImport } = getImportNames(cleanedImports); + return { + ...matched, + defaultImport, + namespacedImport, + namedImports + }; +} +function findExports(code) { + const declaredExports = matchAll(EXPORT_DECAL_RE, code, { + type: "declaration" + }); + for (const declaredExport of declaredExports) { + const extraNamesStr = declaredExport.extraNames; + if (extraNamesStr) { + const extraNames = matchAll(/,\s*(?\w+)/g, extraNamesStr, {}).map( + (m) => m.name + ); + declaredExport.names = [declaredExport.name, ...extraNames]; + } + delete declaredExport.extraNames; + } + const namedExports = normalizeNamedExports( + matchAll(EXPORT_NAMED_RE, code, { + type: "named" + }) + ); + const destructuredExports = matchAll( + EXPORT_NAMED_DESTRUCT, + code, + { type: "named" } + ); + for (const namedExport of destructuredExports) { + namedExport.exports = namedExport.exports1 || namedExport.exports2; + namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map( + (name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim() + ); + } + const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, { + type: "default", + name: "default" + }); + const starExports = matchAll(EXPORT_STAR_RE, code, { + type: "star" + }); + const exports = normalizeExports([ + ...declaredExports, + ...namedExports, + ...destructuredExports, + ...defaultExport, + ...starExports + ]); + if (exports.length === 0) { + return []; + } + const exportLocations = _tryGetLocations(code, "export"); + if (exportLocations && exportLocations.length === 0) { + return []; + } + return ( + // Filter false positive export matches + _filterStatement(exportLocations, exports).filter((exp, index, exports2) => { + const nextExport = exports2[index + 1]; + return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name; + }) + ); +} +function findTypeExports(code) { + const declaredExports = matchAll( + EXPORT_DECAL_TYPE_RE, + code, + { type: "declaration" } + ); + const namedExports = normalizeNamedExports( + matchAll(EXPORT_NAMED_TYPE_RE, code, { + type: "named" + }) + ); + const exports = normalizeExports([ + ...declaredExports, + ...namedExports + ]); + if (exports.length === 0) { + return []; + } + const exportLocations = _tryGetLocations(code, "export"); + if (exportLocations && exportLocations.length === 0) { + return []; + } + return ( + // Filter false positive export matches + _filterStatement(exportLocations, exports).filter((exp, index, exports2) => { + const nextExport = exports2[index + 1]; + return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name; + }) + ); +} +function normalizeExports(exports) { + for (const exp of exports) { + if (!exp.name && exp.names && exp.names.length === 1) { + exp.name = exp.names[0]; + } + if (exp.name === "default" && exp.type !== "default") { + exp._type = exp.type; + exp.type = "default"; + } + if (!exp.names && exp.name) { + exp.names = [exp.name]; + } + if (exp.type === "declaration" && exp.declaration) { + exp.declarationType = exp.declaration.replace( + /^declare\s*/, + "" + ); + } + } + return exports; +} +function normalizeNamedExports(namedExports) { + for (const namedExport of namedExports) { + namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim()); + } + return namedExports; +} +function findExportNames(code) { + return findExports(code).flatMap((exp) => exp.names).filter(Boolean); +} +async function resolveModuleExportNames(id, options) { + const url = await resolvePath(id, options); + const code = await loadURL(url); + const exports = findExports(code); + const exportNames = new Set( + exports.flatMap((exp) => exp.names).filter(Boolean) + ); + for (const exp of exports) { + if (exp.type !== "star" || !exp.specifier) { + continue; + } + const subExports = await resolveModuleExportNames(exp.specifier, { + ...options, + url + }); + for (const subExport of subExports) { + exportNames.add(subExport); + } + } + return [...exportNames]; +} +function _filterStatement(locations, statements) { + return statements.filter((exp) => { + return !locations || locations.some((location) => { + return exp.start <= location.start && exp.end >= location.end; + }); + }); +} +function _tryGetLocations(code, label) { + try { + return _getLocations(code, label); + } catch { + } +} +function _getLocations(code, label) { + const tokens = tokenizer(code, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true + }); + const locations = []; + for (const token of tokens) { + if (token.type.label === label) { + locations.push({ + start: token.start, + end: token.end + }); + } + } + return locations; +} + +function createCommonJS(url) { + const __filename = fileURLToPath(url); + const __dirname = dirname(__filename); + let _nativeRequire; + const getNativeRequire = () => { + if (!_nativeRequire) { + _nativeRequire = createRequire(url); + } + return _nativeRequire; + }; + function require(id) { + return getNativeRequire()(id); + } + require.resolve = function requireResolve(id, options) { + return getNativeRequire().resolve(id, options); + }; + return { + __filename, + __dirname, + require + }; +} +function interopDefault(sourceModule, opts = {}) { + if (!isObject(sourceModule) || !("default" in sourceModule)) { + return sourceModule; + } + const defaultValue = sourceModule.default; + if (defaultValue === void 0 || defaultValue === null) { + return sourceModule; + } + if (typeof defaultValue !== "object") { + return opts.preferNamespace ? sourceModule : defaultValue; + } + for (const key in sourceModule) { + if (key === "default") { + try { + if (!(key in defaultValue)) { + Object.defineProperty(defaultValue, key, { + enumerable: false, + configurable: false, + get() { + return defaultValue; + } + }); + } + } catch { + } + } else { + try { + if (!(key in defaultValue)) { + Object.defineProperty(defaultValue, key, { + enumerable: true, + configurable: true, + get() { + return sourceModule[key]; + } + }); + } + } catch { + } + } + } + return defaultValue; +} + +const EVAL_ESM_IMPORT_RE = /(?<=import .* from ["'])([^"']+)(?=["'])|(?<=export .* from ["'])([^"']+)(?=["'])|(?<=import\s*["'])([^"']+)(?=["'])|(?<=import\s*\(["'])([^"']+)(?=["']\))/g; +async function loadModule(id, options = {}) { + const url = await resolve(id, options); + const code = await loadURL(url); + return evalModule(code, { ...options, url }); +} +async function evalModule(code, options = {}) { + const transformed = await transformModule(code, options); + const dataURL = toDataURL(transformed); + return import(dataURL).catch((error) => { + error.stack = error.stack.replace( + new RegExp(dataURL, "g"), + options.url || "_mlly_eval_" + ); + throw error; + }); +} +function transformModule(code, options = {}) { + if (options.url && options.url.endsWith(".json")) { + return Promise.resolve("export default " + code); + } + if (options.url) { + code = code.replace(/import\.meta\.url/g, `'${options.url}'`); + } + return Promise.resolve(code); +} +async function resolveImports(code, options) { + const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]); + if (imports.length === 0) { + return code; + } + const uniqueImports = [...new Set(imports)]; + const resolved = /* @__PURE__ */ new Map(); + await Promise.all( + uniqueImports.map(async (id) => { + let url = await resolve(id, options); + if (url.endsWith(".json")) { + const code2 = await loadURL(url); + url = toDataURL(await transformModule(code2, { url })); + } + resolved.set(id, url); + }) + ); + const re = new RegExp( + uniqueImports.map((index) => `(${index})`).join("|"), + "g" + ); + return code.replace(re, (id) => resolved.get(id)); +} + +const ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; +const CJS_RE = /([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m; +const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g; +const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]); +function hasESMSyntax(code, opts = {}) { + if (opts.stripComments) { + code = code.replace(COMMENT_RE, ""); + } + return ESM_RE.test(code); +} +function hasCJSSyntax(code, opts = {}) { + if (opts.stripComments) { + code = code.replace(COMMENT_RE, ""); + } + return CJS_RE.test(code); +} +function detectSyntax(code, opts = {}) { + if (opts.stripComments) { + code = code.replace(COMMENT_RE, ""); + } + const hasESM = hasESMSyntax(code, {}); + const hasCJS = hasCJSSyntax(code, {}); + return { + hasESM, + hasCJS, + isMixed: hasESM && hasCJS + }; +} +const validNodeImportDefaults = { + allowedProtocols: ["node", "file", "data"] +}; +async function isValidNodeImport(id, _options = {}) { + if (isNodeBuiltin(id)) { + return true; + } + const options = { ...validNodeImportDefaults, ..._options }; + const proto = getProtocol(id); + if (proto && !options.allowedProtocols?.includes(proto)) { + return false; + } + if (proto === "data") { + return true; + } + const resolvedPath = await resolvePath(id, options); + const extension = extname$1(resolvedPath); + if (BUILTIN_EXTENSIONS.has(extension)) { + return true; + } + if (extension !== ".js") { + return false; + } + const package_ = await readPackageJSON(resolvedPath).catch(() => { + }); + if (package_?.type === "module") { + return true; + } + if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(resolvedPath)) { + return false; + } + const code = options.code || await promises.readFile(resolvedPath, "utf8").catch(() => { + }) || ""; + return !hasESMSyntax(code); +} + +export { DYNAMIC_IMPORT_RE, ESM_STATIC_IMPORT_RE, EXPORT_DECAL_RE, EXPORT_DECAL_TYPE_RE, createCommonJS, createResolve, detectSyntax, evalModule, fileURLToPath, findDynamicImports, findExportNames, findExports, findStaticImports, findTypeExports, findTypeImports, getProtocol, hasCJSSyntax, hasESMSyntax, interopDefault, isNodeBuiltin, isValidNodeImport, loadModule, loadURL, lookupNodeModuleSubpath, normalizeid, parseNodeModulePath, parseStaticImport, parseTypeImport, pathToFileURL, resolve, resolveImports, resolveModuleExportNames, resolvePath, resolvePathSync, resolveSync, sanitizeFilePath, sanitizeURIComponent, toDataURL, transformModule }; diff --git a/web/node_modules/mlly/package.json b/web/node_modules/mlly/package.json new file mode 100644 index 0000000000000000000000000000000000000000..aa48fe43a8e97cc502542b95fda4ad5b6f083b25 --- /dev/null +++ b/web/node_modules/mlly/package.json @@ -0,0 +1,50 @@ +{ + "name": "mlly", + "version": "1.6.1", + "description": "Missing ECMAScript module utils for Node.js", + "repository": "unjs/mlly", + "license": "MIT", + "sideEffects": false, + "type": "module", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "unbuild", + "dev": "vitest", + "lint": "eslint --ext .ts,.js src test && prettier -c src test", + "lint:fix": "eslint --ext .ts,.js src test --fix && prettier -w src test", + "release": "pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags", + "test": "pnpm lint && pnpm test:types && vitest run", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "acorn": "^8.11.3", + "pathe": "^1.1.2", + "pkg-types": "^1.0.3", + "ufo": "^1.3.2" + }, + "devDependencies": { + "@types/node": "^20.11.16", + "@vitest/coverage-v8": "^1.2.2", + "changelogen": "^0.5.5", + "eslint": "^8.56.0", + "eslint-config-unjs": "^0.2.1", + "import-meta-resolve": "^4.0.0", + "jiti": "^1.21.0", + "prettier": "^3.2.4", + "std-env": "^3.7.0", + "typescript": "^5.3.3", + "unbuild": "^2.0.0", + "vitest": "^1.2.2" + }, + "packageManager": "pnpm@8.15.1" +} \ No newline at end of file diff --git a/web/node_modules/ms/index.js b/web/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c4498bcc212589664a5fe0d45e5908b174ab0a37 --- /dev/null +++ b/web/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/web/node_modules/ms/license.md b/web/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..69b61253a38926757b7de1d4df4880fc2105c2c9 --- /dev/null +++ b/web/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, 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/web/node_modules/ms/package.json b/web/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..eea666e1fb03d6ef0eb9edb7b8af363db911665f --- /dev/null +++ b/web/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/web/node_modules/ms/readme.md b/web/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9a1996b17e0de6854dd1cf10c5f2ee642e494085 --- /dev/null +++ b/web/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/web/node_modules/nanoid/LICENSE b/web/node_modules/nanoid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..37f56aa49f8e009ed7e582cb3e905a1e0d1666fd --- /dev/null +++ b/web/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/web/node_modules/nanoid/README.md b/web/node_modules/nanoid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35abb57d88a7613ff9c47a84cfb3ba4afbedea84 --- /dev/null +++ b/web/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/web/node_modules/nanoid/async/index.browser.cjs b/web/node_modules/nanoid/async/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..7e5bba837bfafefd92fab6492045dc1a7451c7f9 --- /dev/null +++ b/web/node_modules/nanoid/async/index.browser.cjs @@ -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 + 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)) + 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 +} +module.exports = { nanoid, customAlphabet, random } diff --git a/web/node_modules/nanoid/async/index.browser.js b/web/node_modules/nanoid/async/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..5ece04d63f7ab97d592f095e9e8c959424091ea5 --- /dev/null +++ b/web/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 + 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)) + 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/web/node_modules/nanoid/async/index.cjs b/web/node_modules/nanoid/async/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..50db10573d6aee1caf9527ef28cc6731c40e1139 --- /dev/null +++ b/web/node_modules/nanoid/async/index.cjs @@ -0,0 +1,35 @@ +let crypto = require('crypto') +let { urlAlphabet } = require('../url-alphabet/index.cjs') +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).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +module.exports = { nanoid, customAlphabet, random } diff --git a/web/node_modules/nanoid/async/index.d.ts b/web/node_modules/nanoid/async/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e919658b82e66e3bd39800232da5a469c8d13a8 --- /dev/null +++ b/web/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/web/node_modules/nanoid/async/index.js b/web/node_modules/nanoid/async/index.js new file mode 100644 index 0000000000000000000000000000000000000000..803fad6f4d20e4795efff7c015aeec4a6d08a2f0 --- /dev/null +++ b/web/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).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +export { nanoid, customAlphabet, random } diff --git a/web/node_modules/nanoid/async/index.native.js b/web/node_modules/nanoid/async/index.native.js new file mode 100644 index 0000000000000000000000000000000000000000..5cb3d57ad17a8f6db4a6e0afa8257de62f650138 --- /dev/null +++ b/web/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).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +export { nanoid, customAlphabet, random } diff --git a/web/node_modules/nanoid/async/package.json b/web/node_modules/nanoid/async/package.json new file mode 100644 index 0000000000000000000000000000000000000000..578cdb4cb9babb17e4e08b4f6a30c2e195d2afed --- /dev/null +++ b/web/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/web/node_modules/nanoid/bin/nanoid.cjs b/web/node_modules/nanoid/bin/nanoid.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c76db0faa81f6d683c4a18a212f804fb70cf8143 --- /dev/null +++ b/web/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/web/node_modules/nanoid/index.browser.cjs b/web/node_modules/nanoid/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..f800d6f4895fbd363f4c0c11ee40e1ba3bb5ab7f --- /dev/null +++ b/web/node_modules/nanoid/index.browser.cjs @@ -0,0 +1,34 @@ +let { urlAlphabet } = require('./url-alphabet/index.cjs') +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 + 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 + }, '') +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/web/node_modules/nanoid/index.browser.js b/web/node_modules/nanoid/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..8b3139b09e34d03b814f729b985159796bf2f636 --- /dev/null +++ b/web/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 + 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/web/node_modules/nanoid/index.cjs b/web/node_modules/nanoid/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0fa85e9dac9624d732c9651a6b97ac942dc3d64d --- /dev/null +++ b/web/node_modules/nanoid/index.cjs @@ -0,0 +1,45 @@ +let crypto = require('crypto') +let { urlAlphabet } = require('./url-alphabet/index.cjs') +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 +} +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/web/node_modules/nanoid/index.d.cts b/web/node_modules/nanoid/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/web/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/web/node_modules/nanoid/index.d.ts b/web/node_modules/nanoid/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/web/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/web/node_modules/nanoid/index.js b/web/node_modules/nanoid/index.js new file mode 100644 index 0000000000000000000000000000000000000000..21e155fca8691d663aef6b96f4448d0bd9f1a780 --- /dev/null +++ b/web/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/web/node_modules/nanoid/nanoid.js b/web/node_modules/nanoid/nanoid.js new file mode 100644 index 0000000000000000000000000000000000000000..ec242eadc85e4b0ef546c8fdc771f7e9d7d2f081 --- /dev/null +++ b/web/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/web/node_modules/nanoid/non-secure/index.cjs b/web/node_modules/nanoid/non-secure/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..09d57cdc0625d51bd1109b4ce2818e9553005eed --- /dev/null +++ b/web/node_modules/nanoid/non-secure/index.cjs @@ -0,0 +1,21 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + let i = size + while (i--) { + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} +let nanoid = (size = 21) => { + let id = '' + let i = size + while (i--) { + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} +module.exports = { nanoid, customAlphabet } diff --git a/web/node_modules/nanoid/non-secure/index.d.ts b/web/node_modules/nanoid/non-secure/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4965322d636016d678fccdd94c3aacdf1fc50075 --- /dev/null +++ b/web/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/web/node_modules/nanoid/non-secure/index.js b/web/node_modules/nanoid/non-secure/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e7e19adf23e9b2f2561aa8a6cdbd6bb30a33a8bb --- /dev/null +++ b/web/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 + while (i--) { + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} +let nanoid = (size = 21) => { + let id = '' + let i = size + while (i--) { + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} +export { nanoid, customAlphabet } diff --git a/web/node_modules/nanoid/non-secure/package.json b/web/node_modules/nanoid/non-secure/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/web/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/web/node_modules/nanoid/package.json b/web/node_modules/nanoid/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f24d9658ca167733dbe9c3fb3bcfc3f4e6d20c8 --- /dev/null +++ b/web/node_modules/nanoid/package.json @@ -0,0 +1,88 @@ +{ + "name": "nanoid", + "version": "3.3.7", + "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": { + ".": { + "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" + } + } +} \ No newline at end of file diff --git a/web/node_modules/nanoid/url-alphabet/index.cjs b/web/node_modules/nanoid/url-alphabet/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..757b709ccabe50fe68c6c85dbb1656b35bb03f5b --- /dev/null +++ b/web/node_modules/nanoid/url-alphabet/index.cjs @@ -0,0 +1,3 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +module.exports = { urlAlphabet } diff --git a/web/node_modules/nanoid/url-alphabet/index.js b/web/node_modules/nanoid/url-alphabet/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c2782e592e541a8ec8bd07038e997e63a16beb70 --- /dev/null +++ b/web/node_modules/nanoid/url-alphabet/index.js @@ -0,0 +1,3 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +export { urlAlphabet } diff --git a/web/node_modules/nanoid/url-alphabet/package.json b/web/node_modules/nanoid/url-alphabet/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/web/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/web/node_modules/npm-run-path/index.d.ts b/web/node_modules/npm-run-path/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25eca12ace73cb3a5e65bb1448d67405b4ea4666 --- /dev/null +++ b/web/node_modules/npm-run-path/index.d.ts @@ -0,0 +1,90 @@ +type CommonOptions = { + /** + Working directory. + + @default process.cwd() + */ + readonly cwd?: string | URL; + + /** + The path to the current Node.js executable. + + This can be either an absolute path or a path relative to the `cwd` option. + + @default [process.execPath](https://nodejs.org/api/process.html#processexecpath) + */ + readonly execPath?: string | URL; + + /** + Whether to push the current Node.js executable's directory (`execPath` option) to the front of PATH. + + @default true + */ + readonly addExecPath?: boolean; + + /** + Whether to push the locally installed binaries' directory to the front of PATH. + + @default true + */ + readonly preferLocal?: boolean; +}; + +export type RunPathOptions = CommonOptions & { + /** + PATH to be appended. + + Set it to an empty string to exclude the default PATH. + + @default [`PATH`](https://github.com/sindresorhus/path-key) + */ + readonly path?: string; +}; + +export type ProcessEnv = Record; + +export type EnvOptions = CommonOptions & { + /** + Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options. + + @default [process.env](https://nodejs.org/api/process.html#processenv) + */ + readonly env?: ProcessEnv; +}; + +/** +Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries. + +@returns The augmented path string. + +@example +``` +import childProcess from 'node:child_process'; +import {npmRunPath} from 'npm-run-path'; + +console.log(process.env.PATH); +//=> '/usr/local/bin' + +console.log(npmRunPath()); +//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin' +``` +*/ +export function npmRunPath(options?: RunPathOptions): string; + +/** +Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries. + +@returns The augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object. + +@example +``` +import childProcess from 'node:child_process'; +import {npmRunPathEnv} from 'npm-run-path'; + +// `foo` is a locally installed binary +childProcess.execFileSync('foo', { + env: npmRunPathEnv() +}); +``` +*/ +export function npmRunPathEnv(options?: EnvOptions): ProcessEnv; diff --git a/web/node_modules/npm-run-path/index.js b/web/node_modules/npm-run-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9d6c6373c558a03497a58d81dd58086d424cad11 --- /dev/null +++ b/web/node_modules/npm-run-path/index.js @@ -0,0 +1,52 @@ +import process from 'node:process'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import pathKey from 'path-key'; + +export const npmRunPath = ({ + cwd = process.cwd(), + path: pathOption = process.env[pathKey()], + preferLocal = true, + execPath = process.execPath, + addExecPath = true, +} = {}) => { + const cwdString = cwd instanceof URL ? fileURLToPath(cwd) : cwd; + const cwdPath = path.resolve(cwdString); + const result = []; + + if (preferLocal) { + applyPreferLocal(result, cwdPath); + } + + if (addExecPath) { + applyExecPath(result, execPath, cwdPath); + } + + return [...result, pathOption].join(path.delimiter); +}; + +const applyPreferLocal = (result, cwdPath) => { + let previous; + + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } +}; + +// Ensure the running `node` binary is used +const applyExecPath = (result, execPath, cwdPath) => { + const execPathString = execPath instanceof URL ? fileURLToPath(execPath) : execPath; + result.push(path.resolve(cwdPath, execPathString, '..')); +}; + +export const npmRunPathEnv = ({env = process.env, ...options} = {}) => { + env = {...env}; + + const pathName = pathKey({env}); + options.path = env[pathName]; + env[pathName] = npmRunPath(options); + + return env; +}; diff --git a/web/node_modules/npm-run-path/license b/web/node_modules/npm-run-path/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/npm-run-path/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/web/node_modules/npm-run-path/node_modules/path-key/index.d.ts b/web/node_modules/npm-run-path/node_modules/path-key/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f411d623a9315ca4a70b1806e184f053ea30c24d --- /dev/null +++ b/web/node_modules/npm-run-path/node_modules/path-key/index.d.ts @@ -0,0 +1,31 @@ +export interface Options { + /** + Use a custom environment variables object. + + Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env). + */ + readonly env?: Record; + + /** + Get the PATH key for a specific platform. + + Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform). + */ + readonly platform?: NodeJS.Platform; +} + +/** +Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform. + +@example +``` +import pathKey from 'path-key'; + +const key = pathKey(); +//=> 'PATH' + +const PATH = process.env[key]; +//=> '/usr/local/bin:/usr/bin:/bin' +``` +*/ +export default function pathKey(options?: Options): string; diff --git a/web/node_modules/npm-run-path/node_modules/path-key/index.js b/web/node_modules/npm-run-path/node_modules/path-key/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2c02914b078a7c707f0a15fd2a5afef50c215b2b --- /dev/null +++ b/web/node_modules/npm-run-path/node_modules/path-key/index.js @@ -0,0 +1,12 @@ +export default function pathKey(options = {}) { + const { + env = process.env, + platform = process.platform + } = options; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +} diff --git a/web/node_modules/npm-run-path/node_modules/path-key/license b/web/node_modules/npm-run-path/node_modules/path-key/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/npm-run-path/node_modules/path-key/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/web/node_modules/npm-run-path/node_modules/path-key/package.json b/web/node_modules/npm-run-path/node_modules/path-key/package.json new file mode 100644 index 0000000000000000000000000000000000000000..609070def82198425f05f483d3ccb8ea23d75ba8 --- /dev/null +++ b/web/node_modules/npm-run-path/node_modules/path-key/package.json @@ -0,0 +1,41 @@ +{ + "name": "path-key", + "version": "4.0.0", + "description": "Get the PATH environment variable key cross-platform", + "license": "MIT", + "repository": "sindresorhus/path-key", + "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": [ + "path", + "key", + "environment", + "env", + "variable", + "get", + "cross-platform", + "windows" + ], + "devDependencies": { + "@types/node": "^14.14.37", + "ava": "^3.15.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/web/node_modules/npm-run-path/node_modules/path-key/readme.md b/web/node_modules/npm-run-path/node_modules/path-key/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..aa2250646fce4143c03dd7532bdaf0f077431bd0 --- /dev/null +++ b/web/node_modules/npm-run-path/node_modules/path-key/readme.md @@ -0,0 +1,57 @@ +# 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 +import pathKey from '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/web/node_modules/npm-run-path/package.json b/web/node_modules/npm-run-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dd6a4ae3bc5e41edc80b20ee604668c41fd6ad7e --- /dev/null +++ b/web/node_modules/npm-run-path/package.json @@ -0,0 +1,49 @@ +{ + "name": "npm-run-path", + "version": "5.3.0", + "description": "Get your PATH prepended with locally installed binaries", + "license": "MIT", + "repository": "sindresorhus/npm-run-path", + "funding": "https://github.com/sponsors/sindresorhus", + "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.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "npm", + "run", + "path", + "package", + "bin", + "binary", + "binaries", + "script", + "cli", + "command-line", + "execute", + "executable" + ], + "dependencies": { + "path-key": "^4.0.0" + }, + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.17.0", + "xo": "^0.45.0" + } +} diff --git a/web/node_modules/npm-run-path/readme.md b/web/node_modules/npm-run-path/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..bec78f93a5860d62d71f7b4314dfc16a12c50660 --- /dev/null +++ b/web/node_modules/npm-run-path/readme.md @@ -0,0 +1,104 @@ +# npm-run-path + +> Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries + +In [npm run scripts](https://docs.npmjs.com/cli/run-script) you can execute locally installed binaries by name. This enables the same outside npm. + +## Install + +```sh +npm install npm-run-path +``` + +## Usage + +```js +import childProcess from 'node:child_process'; +import {npmRunPath, npmRunPathEnv} from 'npm-run-path'; + +console.log(process.env.PATH); +//=> '/usr/local/bin' + +console.log(npmRunPath()); +//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin' + +// `foo` is a locally installed binary +childProcess.execFileSync('foo', { + env: npmRunPathEnv() +}); +``` + +## API + +### npmRunPath(options?) + +`options`: [`Options`](#options)\ +_Returns_: `string` + +Returns the augmented PATH string. + +### npmRunPathEnv(options?) + +`options`: [`Options`](#options)\ +_Returns_: `object` + +Returns the augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object. + +### options + +Type: `object` + +#### cwd + +Type: `string | URL`\ +Default: `process.cwd()` + +The working directory. + +#### execPath + +Type: `string | URL`\ +Default: [`process.execPath`](https://nodejs.org/api/process.html#processexecpath) + +The path to the current Node.js executable. + +This can be either an absolute path or a path relative to the [`cwd` option](#cwd). + +#### addExecPath + +Type: `boolean`\ +Default: `true` + +Whether to push the current Node.js executable's directory ([`execPath`](#execpath) option) to the front of PATH. + +#### preferLocal + +Type: `boolean`\ +Default: `true` + +Whether to push the locally installed binaries' directory to the front of PATH. + +#### path + +Type: `string`\ +Default: [`PATH`](https://github.com/sindresorhus/path-key) + +The PATH to be appended. + +Set it to an empty string to exclude the default PATH. + +Only available with [`npmRunPath()`](#npmrunpathoptions), not [`npmRunPathEnv()`](#npmrunpathenvoptions). + +#### env + +Type: `object`\ +Default: [`process.env`](https://nodejs.org/api/process.html#processenv) + +Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options. + +Only available with [`npmRunPathEnv()`](#npmrunpathenvoptions), not [`npmRunPath()`](#npmrunpathoptions). + +## Related + +- [npm-run-path-cli](https://github.com/sindresorhus/npm-run-path-cli) - CLI for this module +- [execa](https://github.com/sindresorhus/execa) - Execute a locally installed binary diff --git a/web/node_modules/onetime/index.d.ts b/web/node_modules/onetime/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c80803f9960c7c60eca4b6cb46b35e70a1e30ba --- /dev/null +++ b/web/node_modules/onetime/index.d.ts @@ -0,0 +1,59 @@ +export interface Options { + /** + Throw an error when called more than once. + + @default false + */ + readonly throw?: boolean; +} + +declare const onetime: { + /** + Ensure a function is only called once. When called multiple times it will return the return value from the first call. + + @param fn - Function that should only be called once. + @returns A function that only calls `fn` once. + + @example + ``` + import onetime from 'onetime'; + + let index = 0; + + const foo = onetime(() => ++index); + + foo(); //=> 1 + foo(); //=> 1 + foo(); //=> 1 + + onetime.callCount(foo); //=> 3 + ``` + */ + ( + fn: (...arguments: ArgumentsType) => ReturnType, + options?: Options + ): (...arguments: ArgumentsType) => ReturnType; + + /** + Get the number of times `fn` has been called. + + @param fn - Function to get call count from. + @returns A number representing how many times `fn` has been called. + + @example + ``` + import onetime from 'onetime'; + + const foo = onetime(() => {}); + foo(); + foo(); + foo(); + + console.log(onetime.callCount(foo)); + //=> 3 + ``` + */ + callCount(fn: (...arguments: any[]) => unknown): number; +}; + +export default onetime; diff --git a/web/node_modules/onetime/index.js b/web/node_modules/onetime/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eae4f33e4c728801811bc3aab29b50cc3bf4afe4 --- /dev/null +++ b/web/node_modules/onetime/index.js @@ -0,0 +1,41 @@ +import mimicFunction from 'mimic-fn'; + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFunction(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +onetime.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; + +export default onetime; diff --git a/web/node_modules/onetime/license b/web/node_modules/onetime/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/onetime/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/web/node_modules/onetime/package.json b/web/node_modules/onetime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..475a1e39d6924e370bc0dc0e99b0e7d4a04755c3 --- /dev/null +++ b/web/node_modules/onetime/package.json @@ -0,0 +1,45 @@ +{ + "name": "onetime", + "version": "6.0.0", + "description": "Ensure a function is only called once", + "license": "MIT", + "repository": "sindresorhus/onetime", + "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": [ + "once", + "function", + "one", + "onetime", + "func", + "fn", + "single", + "call", + "called", + "prevent" + ], + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/web/node_modules/onetime/readme.md b/web/node_modules/onetime/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..e2b26fb3d3abea880b6c016ac3c4effe74e2a69a --- /dev/null +++ b/web/node_modules/onetime/readme.md @@ -0,0 +1,94 @@ +# onetime + +> Ensure a function is only called once + +When called multiple times it will return the return value from the first call. + +*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.* + +## Install + +``` +$ npm install onetime +``` + +## Usage + +```js +import onetime from 'onetime'; + +let index = 0; + +const foo = onetime(() => ++index); + +foo(); //=> 1 +foo(); //=> 1 +foo(); //=> 1 + +onetime.callCount(foo); //=> 3 +``` + +```js +import onetime from 'onetime'; + +const foo = onetime(() => {}, {throw: true}); + +foo(); + +foo(); +//=> Error: Function `foo` can only be called once +``` + +## API + +### onetime(fn, options?) + +Returns a function that only calls `fn` once. + +#### fn + +Type: `Function` + +Function that should only be called once. + +#### options + +Type: `object` + +##### throw + +Type: `boolean`\ +Default: `false` + +Throw an error when called more than once. + +### onetime.callCount(fn) + +Returns a number representing how many times `fn` has been called. + +Note: It throws an error if you pass in a function that is not wrapped by `onetime`. + +```js +import onetime from 'onetime'; + +const foo = onetime(() => {}); + +foo(); +foo(); +foo(); + +console.log(onetime.callCount(foo)); +//=> 3 +``` + +#### fn + +Type: `Function` + +Function to get call count from. + +## onetime for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of onetime 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-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/web/node_modules/p-limit/async-hooks-stub.js b/web/node_modules/p-limit/async-hooks-stub.js new file mode 100644 index 0000000000000000000000000000000000000000..913c7c6171a31464510d7ea6744d319aeb34682a --- /dev/null +++ b/web/node_modules/p-limit/async-hooks-stub.js @@ -0,0 +1,15 @@ +export const AsyncResource = { + bind(fn, _type, thisArg) { + return fn.bind(thisArg); + }, +}; + +export class AsyncLocalStorage { + getStore() { + return undefined; + } + + run(_store, callback) { + return callback(); + } +} diff --git a/web/node_modules/p-limit/index.d.ts b/web/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..303c7d92710db5da067818e654397cf3ec96ec4d --- /dev/null +++ b/web/node_modules/p-limit/index.d.ts @@ -0,0 +1,38 @@ +export type LimitFunction = { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments_: Arguments) => PromiseLike | ReturnType, + ...arguments_: Arguments + ): Promise; +}; + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +export default function pLimit(concurrency: number): LimitFunction; diff --git a/web/node_modules/p-limit/index.js b/web/node_modules/p-limit/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4a5a0f0bd7459bce97a245faa740a669deca8a8b --- /dev/null +++ b/web/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +import Queue from 'yocto-queue'; +import {AsyncResource} from '#async_hooks'; + +export default function pLimit(concurrency) { + if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (function_, resolve, arguments_) => { + activeCount++; + + const result = (async () => function_(...arguments_))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (function_, resolve, arguments_) => { + queue.enqueue( + AsyncResource.bind(run.bind(undefined, function_, resolve, arguments_)), + ); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (function_, ...arguments_) => new Promise(resolve => { + enqueue(function_, resolve, arguments_); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount, + }, + pendingCount: { + get: () => queue.size, + }, + clearQueue: { + value() { + queue.clear(); + }, + }, + }); + + return generator; +} diff --git a/web/node_modules/p-limit/license b/web/node_modules/p-limit/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/web/node_modules/p-limit/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/web/node_modules/p-limit/package.json b/web/node_modules/p-limit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6d5a9b7f400389f37f85ddc47f3801870a288fbb --- /dev/null +++ b/web/node_modules/p-limit/package.json @@ -0,0 +1,64 @@ +{ + "name": "p-limit", + "version": "5.0.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "imports": { + "#async_hooks": { + "node": "async_hooks", + "default": "./async-hooks-stub.js" + } + }, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "async-hooks-stub.js" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "devDependencies": { + "ava": "^5.3.1", + "delay": "^6.0.0", + "in-range": "^3.0.0", + "random-int": "^3.0.0", + "time-span": "^5.1.0", + "tsd": "^0.29.0", + "xo": "^0.56.0" + } +} diff --git a/web/node_modules/p-limit/readme.md b/web/node_modules/p-limit/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..4e890f8dc0083cfec5492d5deb184cd2a9311fed --- /dev/null +++ b/web/node_modules/p-limit/readme.md @@ -0,0 +1,88 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +*Works in Node.js and browsers.* + +## Install + +```sh +npm install p-limit +``` + +## Usage + +```js +import pLimit from 'p-limit'; + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +// Only one promise is run at once +const result = await Promise.all(input); +console.log(result); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) diff --git a/web/node_modules/path-key/index.d.ts b/web/node_modules/path-key/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c575d197502223b05301b1b338aaa28cfd54217 --- /dev/null +++ b/web/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/web/node_modules/path-key/index.js b/web/node_modules/path-key/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0cf6415d60938fa78ba51b277fa2a57fa0bdc587 --- /dev/null +++ b/web/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/web/node_modules/path-key/license b/web/node_modules/path-key/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/web/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/web/node_modules/path-key/package.json b/web/node_modules/path-key/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c8cbd383afc9550502c254ec6b96e46137e8d26b --- /dev/null +++ b/web/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/web/node_modules/path-key/readme.md b/web/node_modules/path-key/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..a9052d7a696bcde942b3820b9706942ddd6a8fd5 --- /dev/null +++ b/web/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/web/node_modules/pathe/LICENSE b/web/node_modules/pathe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..743af99259533dc56ef8c3a515727cd2adb42a74 --- /dev/null +++ b/web/node_modules/pathe/LICENSE @@ -0,0 +1,44 @@ +MIT License + +Copyright (c) Pooya Parsa - Daniel Roe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/web/node_modules/pathe/README.md b/web/node_modules/pathe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a2af0fd27cdb5acc9e5f021a7c276bc746b97910 --- /dev/null +++ b/web/node_modules/pathe/README.md @@ -0,0 +1,69 @@ +# 🛣️ pathe + +> Universal filesystem path utils + +[![version][npm-v-src]][npm-v-href] +[![downloads][npm-d-src]][npm-d-href] +[![size][size-src]][size-href] + +> **❓ Why** +> +> For [historical reasons](https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character), windows followed MS-DOS and using backslash for separating paths rather than slash used for macOS, Linux, and other Posix operating systems. Nowadays, [Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN) supports both Slash and Backslash for paths. [Node.js's built in `path` module](https://nodejs.org/api/path.html) in the default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used. **This makes inconsistent code behavior between Windows and POSIX.** +> Compared to popular [upath](https://github.com/anodynos/upath), pathe is providing **identical exports** of Node.js with normalization on **all operations** and written in modern **ESM/Typescript** and has **no dependency on Node.js**! + +This package is a drop-in replacement of the Node.js's [path module](https://nodejs.org/api/path.html) module and ensures paths are normalized with slash `/` and work in environments including Node.js. + +## 💿 Usage + +Install using npm or yarn: + +```bash +# npm +npm i pathe + +# yarn +yarn add pathe + +# pnpm +pnpm i pathe +``` + +Import: + +```js +// ESM / Typescript +import { resolve } from 'pathe' + +// CommonJS +const { resolve } = require('pathe') +``` + +Read more about path utils from [Node.js documentation](https://nodejs.org/api/path.html) and rest assured behavior is ALWAYS like POSIX regardless of your input paths format and running platform! + +### Extra utilties + +Pathe exports some extra utilities that do not exist in standard Node.js [path module](https://nodejs.org/api/path.html). +In order to use them, you can import from `pathe/utils` subpath: + +```js +import { filename, normalizeAliases, resolveAlias } from 'pathe/utils' +``` + +## License + +MIT. Made with 💖 + +Some code used from Node.js project. See [LICENSE](./LICENSE). + + +[npm-v-src]: https://img.shields.io/npm/v/pathe?style=flat-square +[npm-v-href]: https://npmjs.com/package/pathe + +[npm-d-src]: https://img.shields.io/npm/dm/pathe?style=flat-square +[npm-d-href]: https://npmjs.com/package/pathe + +[github-actions-src]: https://img.shields.io/github/workflow/status/unjs/pathe/ci/main?style=flat-square +[github-actions-href]: https://github.com/unjs/pathe/actions?query=workflow%3Aci + +[size-src]: https://packagephobia.now.sh/badge?p=pathe +[size-href]: https://packagephobia.now.sh/result?p=pathe diff --git a/web/node_modules/pathe/dist/index.cjs b/web/node_modules/pathe/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..3832e065bcfe92479e1d2a49c48c4f1e319c28f7 --- /dev/null +++ b/web/node_modules/pathe/dist/index.cjs @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +const index = require('./shared/pathe.1f0a373c.cjs'); + + + +exports.basename = index.basename; +exports.default = index.path; +exports.delimiter = index.delimiter; +exports.dirname = index.dirname; +exports.extname = index.extname; +exports.format = index.format; +exports.isAbsolute = index.isAbsolute; +exports.join = index.join; +exports.normalize = index.normalize; +exports.normalizeString = index.normalizeString; +exports.parse = index.parse; +exports.relative = index.relative; +exports.resolve = index.resolve; +exports.sep = index.sep; +exports.toNamespacedPath = index.toNamespacedPath; diff --git a/web/node_modules/pathe/dist/index.d.cts b/web/node_modules/pathe/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..531b6906507206b4594ff0ff830d605c4cf6a16a --- /dev/null +++ b/web/node_modules/pathe/dist/index.d.cts @@ -0,0 +1,36 @@ +import path$1 from 'node:path'; + +declare const sep = "/"; +declare const delimiter = ":"; +declare const normalize: typeof path$1.normalize; +declare const join: typeof path$1.join; +declare const resolve: typeof path$1.resolve; +declare function normalizeString(path: string, allowAboveRoot: boolean): string; +declare const isAbsolute: typeof path$1.isAbsolute; +declare const toNamespacedPath: typeof path$1.toNamespacedPath; +declare const extname: typeof path$1.extname; +declare const relative: typeof path$1.relative; +declare const dirname: typeof path$1.dirname; +declare const format: typeof path$1.format; +declare const basename: typeof path$1.basename; +declare const parse: typeof path$1.parse; + +declare const path_basename: typeof basename; +declare const path_delimiter: typeof delimiter; +declare const path_dirname: typeof dirname; +declare const path_extname: typeof extname; +declare const path_format: typeof format; +declare const path_isAbsolute: typeof isAbsolute; +declare const path_join: typeof join; +declare const path_normalize: typeof normalize; +declare const path_normalizeString: typeof normalizeString; +declare const path_parse: typeof parse; +declare const path_relative: typeof relative; +declare const path_resolve: typeof resolve; +declare const path_sep: typeof sep; +declare const path_toNamespacedPath: typeof toNamespacedPath; +declare namespace path { + export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath }; +} + +export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath }; diff --git a/web/node_modules/pathe/dist/index.d.mts b/web/node_modules/pathe/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..531b6906507206b4594ff0ff830d605c4cf6a16a --- /dev/null +++ b/web/node_modules/pathe/dist/index.d.mts @@ -0,0 +1,36 @@ +import path$1 from 'node:path'; + +declare const sep = "/"; +declare const delimiter = ":"; +declare const normalize: typeof path$1.normalize; +declare const join: typeof path$1.join; +declare const resolve: typeof path$1.resolve; +declare function normalizeString(path: string, allowAboveRoot: boolean): string; +declare const isAbsolute: typeof path$1.isAbsolute; +declare const toNamespacedPath: typeof path$1.toNamespacedPath; +declare const extname: typeof path$1.extname; +declare const relative: typeof path$1.relative; +declare const dirname: typeof path$1.dirname; +declare const format: typeof path$1.format; +declare const basename: typeof path$1.basename; +declare const parse: typeof path$1.parse; + +declare const path_basename: typeof basename; +declare const path_delimiter: typeof delimiter; +declare const path_dirname: typeof dirname; +declare const path_extname: typeof extname; +declare const path_format: typeof format; +declare const path_isAbsolute: typeof isAbsolute; +declare const path_join: typeof join; +declare const path_normalize: typeof normalize; +declare const path_normalizeString: typeof normalizeString; +declare const path_parse: typeof parse; +declare const path_relative: typeof relative; +declare const path_resolve: typeof resolve; +declare const path_sep: typeof sep; +declare const path_toNamespacedPath: typeof toNamespacedPath; +declare namespace path { + export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath }; +} + +export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath }; diff --git a/web/node_modules/pathe/dist/index.d.ts b/web/node_modules/pathe/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..531b6906507206b4594ff0ff830d605c4cf6a16a --- /dev/null +++ b/web/node_modules/pathe/dist/index.d.ts @@ -0,0 +1,36 @@ +import path$1 from 'node:path'; + +declare const sep = "/"; +declare const delimiter = ":"; +declare const normalize: typeof path$1.normalize; +declare const join: typeof path$1.join; +declare const resolve: typeof path$1.resolve; +declare function normalizeString(path: string, allowAboveRoot: boolean): string; +declare const isAbsolute: typeof path$1.isAbsolute; +declare const toNamespacedPath: typeof path$1.toNamespacedPath; +declare const extname: typeof path$1.extname; +declare const relative: typeof path$1.relative; +declare const dirname: typeof path$1.dirname; +declare const format: typeof path$1.format; +declare const basename: typeof path$1.basename; +declare const parse: typeof path$1.parse; + +declare const path_basename: typeof basename; +declare const path_delimiter: typeof delimiter; +declare const path_dirname: typeof dirname; +declare const path_extname: typeof extname; +declare const path_format: typeof format; +declare const path_isAbsolute: typeof isAbsolute; +declare const path_join: typeof join; +declare const path_normalize: typeof normalize; +declare const path_normalizeString: typeof normalizeString; +declare const path_parse: typeof parse; +declare const path_relative: typeof relative; +declare const path_resolve: typeof resolve; +declare const path_sep: typeof sep; +declare const path_toNamespacedPath: typeof toNamespacedPath; +declare namespace path { + export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath }; +} + +export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath }; diff --git a/web/node_modules/pathe/dist/index.mjs b/web/node_modules/pathe/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ecd6cd0180a313f7c3ffab5233f30c0cfc688d5e --- /dev/null +++ b/web/node_modules/pathe/dist/index.mjs @@ -0,0 +1 @@ +export { h as basename, p as default, d as delimiter, f as dirname, e as extname, g as format, i as isAbsolute, j as join, a as normalize, b as normalizeString, k as parse, c as relative, r as resolve, s as sep, t as toNamespacedPath } from './shared/pathe.ff20891b.mjs'; diff --git a/web/node_modules/pathe/dist/shared/pathe.1f0a373c.cjs b/web/node_modules/pathe/dist/shared/pathe.1f0a373c.cjs new file mode 100644 index 0000000000000000000000000000000000000000..64e3a33fdec47002d04642d0d8925c6b39e1ec3d --- /dev/null +++ b/web/node_modules/pathe/dist/shared/pathe.1f0a373c.cjs @@ -0,0 +1,238 @@ +'use strict'; + +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/; +const sep = "/"; +const delimiter = ":"; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...arguments_) { + if (arguments_.length === 0) { + return "."; + } + let joined; + for (const argument of arguments_) { + if (argument && argument.length > 0) { + if (joined === void 0) { + joined = argument; + } else { + joined += `/${argument}`; + } + } + } + if (joined === void 0) { + return "."; + } + return normalize(joined.replace(/\/\/+/g, "/")); +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const toNamespacedPath = function(p) { + return normalizeWindowsPath(p); +}; +const _EXTNAME_RE = /.(\.[^./]+)$/; +const extname = function(p) { + const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); + return match && match[1] || ""; +}; +const relative = function(from, to) { + const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"); + const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/"); + if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) { + return _to.join("/"); + } + const _fromCopy = [..._from]; + for (const segment of _fromCopy) { + if (_to[0] !== segment) { + break; + } + _from.shift(); + _to.shift(); + } + return [..._from.map(() => ".."), ..._to].join("/"); +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; +const format = function(p) { + const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean); + return normalizeWindowsPath( + p.root ? resolve(...segments) : segments.join("/") + ); +}; +const basename = function(p, extension) { + const lastSegment = normalizeWindowsPath(p).split("/").pop(); + return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; +}; +const parse = function(p) { + const root = normalizeWindowsPath(p).split("/").shift() || "/"; + const base = basename(p); + const extension = extname(base); + return { + root, + dir: dirname(p), + base, + ext: extension, + name: base.slice(0, base.length - extension.length) + }; +}; + +const path = { + __proto__: null, + basename: basename, + delimiter: delimiter, + dirname: dirname, + extname: extname, + format: format, + isAbsolute: isAbsolute, + join: join, + normalize: normalize, + normalizeString: normalizeString, + parse: parse, + relative: relative, + resolve: resolve, + sep: sep, + toNamespacedPath: toNamespacedPath +}; + +exports.basename = basename; +exports.delimiter = delimiter; +exports.dirname = dirname; +exports.extname = extname; +exports.format = format; +exports.isAbsolute = isAbsolute; +exports.join = join; +exports.normalize = normalize; +exports.normalizeString = normalizeString; +exports.normalizeWindowsPath = normalizeWindowsPath; +exports.parse = parse; +exports.path = path; +exports.relative = relative; +exports.resolve = resolve; +exports.sep = sep; +exports.toNamespacedPath = toNamespacedPath; diff --git a/web/node_modules/pathe/dist/shared/pathe.ff20891b.mjs b/web/node_modules/pathe/dist/shared/pathe.ff20891b.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e91d8d62418100270d1ed61b2b7e871422369ee0 --- /dev/null +++ b/web/node_modules/pathe/dist/shared/pathe.ff20891b.mjs @@ -0,0 +1,221 @@ +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/; +const sep = "/"; +const delimiter = ":"; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...arguments_) { + if (arguments_.length === 0) { + return "."; + } + let joined; + for (const argument of arguments_) { + if (argument && argument.length > 0) { + if (joined === void 0) { + joined = argument; + } else { + joined += `/${argument}`; + } + } + } + if (joined === void 0) { + return "."; + } + return normalize(joined.replace(/\/\/+/g, "/")); +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const toNamespacedPath = function(p) { + return normalizeWindowsPath(p); +}; +const _EXTNAME_RE = /.(\.[^./]+)$/; +const extname = function(p) { + const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); + return match && match[1] || ""; +}; +const relative = function(from, to) { + const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"); + const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/"); + if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) { + return _to.join("/"); + } + const _fromCopy = [..._from]; + for (const segment of _fromCopy) { + if (_to[0] !== segment) { + break; + } + _from.shift(); + _to.shift(); + } + return [..._from.map(() => ".."), ..._to].join("/"); +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; +const format = function(p) { + const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean); + return normalizeWindowsPath( + p.root ? resolve(...segments) : segments.join("/") + ); +}; +const basename = function(p, extension) { + const lastSegment = normalizeWindowsPath(p).split("/").pop(); + return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; +}; +const parse = function(p) { + const root = normalizeWindowsPath(p).split("/").shift() || "/"; + const base = basename(p); + const extension = extname(base); + return { + root, + dir: dirname(p), + base, + ext: extension, + name: base.slice(0, base.length - extension.length) + }; +}; + +const path = { + __proto__: null, + basename: basename, + delimiter: delimiter, + dirname: dirname, + extname: extname, + format: format, + isAbsolute: isAbsolute, + join: join, + normalize: normalize, + normalizeString: normalizeString, + parse: parse, + relative: relative, + resolve: resolve, + sep: sep, + toNamespacedPath: toNamespacedPath +}; + +export { normalize as a, normalizeString as b, relative as c, delimiter as d, extname as e, dirname as f, format as g, basename as h, isAbsolute as i, join as j, parse as k, normalizeWindowsPath as n, path as p, resolve as r, sep as s, toNamespacedPath as t }; diff --git a/web/node_modules/pathe/dist/utils.cjs b/web/node_modules/pathe/dist/utils.cjs new file mode 100644 index 0000000000000000000000000000000000000000..e2591bfcaff8ce8295192df12b6f39c6b4bf2fdb --- /dev/null +++ b/web/node_modules/pathe/dist/utils.cjs @@ -0,0 +1,58 @@ +'use strict'; + +const index = require('./shared/pathe.1f0a373c.cjs'); + +const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]); +const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); +function normalizeAliases(_aliases) { + if (_aliases[normalizedAliasSymbol]) { + return _aliases; + } + const aliases = Object.fromEntries( + Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b)) + ); + for (const key in aliases) { + for (const alias in aliases) { + if (alias === key || key.startsWith(alias)) { + continue; + } + if (aliases[key].startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) { + aliases[key] = aliases[alias] + aliases[key].slice(alias.length); + } + } + } + Object.defineProperty(aliases, normalizedAliasSymbol, { + value: true, + enumerable: false + }); + return aliases; +} +function resolveAlias(path, aliases) { + const _path = index.normalizeWindowsPath(path); + aliases = normalizeAliases(aliases); + for (const [alias, to] of Object.entries(aliases)) { + if (!_path.startsWith(alias)) { + continue; + } + const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias; + if (hasTrailingSlash(_path[_alias.length])) { + return index.join(to, _path.slice(alias.length)); + } + } + return _path; +} +const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/; +function filename(path) { + return path.match(FILENAME_RE)?.[2]; +} +function _compareAliases(a, b) { + return b.split("/").length - a.split("/").length; +} +function hasTrailingSlash(path = "/") { + const lastChar = path[path.length - 1]; + return lastChar === "/" || lastChar === "\\"; +} + +exports.filename = filename; +exports.normalizeAliases = normalizeAliases; +exports.resolveAlias = resolveAlias; diff --git a/web/node_modules/pathe/dist/utils.d.cts b/web/node_modules/pathe/dist/utils.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..2798305aaf6f42eef69c02cc31a119eed5e08b33 --- /dev/null +++ b/web/node_modules/pathe/dist/utils.d.cts @@ -0,0 +1,5 @@ +declare function normalizeAliases(_aliases: Record): Record; +declare function resolveAlias(path: string, aliases: Record): string; +declare function filename(path: string): string; + +export { filename, normalizeAliases, resolveAlias }; diff --git a/web/node_modules/pathe/dist/utils.d.mts b/web/node_modules/pathe/dist/utils.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2798305aaf6f42eef69c02cc31a119eed5e08b33 --- /dev/null +++ b/web/node_modules/pathe/dist/utils.d.mts @@ -0,0 +1,5 @@ +declare function normalizeAliases(_aliases: Record): Record; +declare function resolveAlias(path: string, aliases: Record): string; +declare function filename(path: string): string; + +export { filename, normalizeAliases, resolveAlias }; diff --git a/web/node_modules/pathe/dist/utils.d.ts b/web/node_modules/pathe/dist/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2798305aaf6f42eef69c02cc31a119eed5e08b33 --- /dev/null +++ b/web/node_modules/pathe/dist/utils.d.ts @@ -0,0 +1,5 @@ +declare function normalizeAliases(_aliases: Record): Record; +declare function resolveAlias(path: string, aliases: Record): string; +declare function filename(path: string): string; + +export { filename, normalizeAliases, resolveAlias }; diff --git a/web/node_modules/pathe/dist/utils.mjs b/web/node_modules/pathe/dist/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..004080bdf105cd4c7a7f3805f3bb6f629121bf00 --- /dev/null +++ b/web/node_modules/pathe/dist/utils.mjs @@ -0,0 +1,54 @@ +import { n as normalizeWindowsPath, j as join } from './shared/pathe.ff20891b.mjs'; + +const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]); +const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); +function normalizeAliases(_aliases) { + if (_aliases[normalizedAliasSymbol]) { + return _aliases; + } + const aliases = Object.fromEntries( + Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b)) + ); + for (const key in aliases) { + for (const alias in aliases) { + if (alias === key || key.startsWith(alias)) { + continue; + } + if (aliases[key].startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) { + aliases[key] = aliases[alias] + aliases[key].slice(alias.length); + } + } + } + Object.defineProperty(aliases, normalizedAliasSymbol, { + value: true, + enumerable: false + }); + return aliases; +} +function resolveAlias(path, aliases) { + const _path = normalizeWindowsPath(path); + aliases = normalizeAliases(aliases); + for (const [alias, to] of Object.entries(aliases)) { + if (!_path.startsWith(alias)) { + continue; + } + const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias; + if (hasTrailingSlash(_path[_alias.length])) { + return join(to, _path.slice(alias.length)); + } + } + return _path; +} +const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/; +function filename(path) { + return path.match(FILENAME_RE)?.[2]; +} +function _compareAliases(a, b) { + return b.split("/").length - a.split("/").length; +} +function hasTrailingSlash(path = "/") { + const lastChar = path[path.length - 1]; + return lastChar === "/" || lastChar === "\\"; +} + +export { filename, normalizeAliases, resolveAlias }; diff --git a/web/node_modules/pathe/package.json b/web/node_modules/pathe/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1b14f7dc435d1714726943691dd32b50bb10ba60 --- /dev/null +++ b/web/node_modules/pathe/package.json @@ -0,0 +1,48 @@ +{ + "name": "pathe", + "version": "1.1.2", + "description": "Universal filesystem path utils", + "repository": "unjs/pathe", + "license": "MIT", + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "import": "./dist/utils.mjs", + "require": "./dist/utils.cjs" + } + }, + "main": "./dist/index.cjs", + "types": "./dist/index.d.ts", + "files": [ + "dist", + "utils.d.ts" + ], + "devDependencies": { + "@types/node": "^20.10.8", + "@vitest/coverage-v8": "^1.1.3", + "changelogen": "^0.5.5", + "eslint": "^8.56.0", + "eslint-config-unjs": "^0.2.1", + "jiti": "^1.21.0", + "prettier": "^3.1.1", + "typescript": "^5.3.3", + "unbuild": "^2.0.0", + "vitest": "^1.1.3" + }, + "packageManager": "pnpm@8.14.0", + "scripts": { + "build": "unbuild", + "dev": "vitest", + "lint": "eslint --ext .ts . && prettier -c src test", + "lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w", + "release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags", + "test": "pnpm lint && vitest run --coverage", + "test:types": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/web/node_modules/pathe/utils.d.ts b/web/node_modules/pathe/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59cabd3e954b3f59e01a6dfb91187fe69fe10e87 --- /dev/null +++ b/web/node_modules/pathe/utils.d.ts @@ -0,0 +1 @@ +export * from "./dist/utils"; diff --git a/web/node_modules/pathval/CHANGELOG.md b/web/node_modules/pathval/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..804de5e8431924bef3e7b8f28d744abaa7a46d97 --- /dev/null +++ b/web/node_modules/pathval/CHANGELOG.md @@ -0,0 +1,18 @@ + +0.1.1 / 2013-12-30 +================== + + * expose parse + * rename lib to index + +0.1.0 / 2013-12-28 +================== + + * API BREAKING! `get` has been changed, see the README for migration path + * Add `set` method + * Start using simple-assert (closes #2) + +0.0.1 / 2013-11-24 +================== + + * Initial implementation diff --git a/web/node_modules/pathval/LICENSE b/web/node_modules/pathval/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..90d22da6af51f0ba1249d4f355f6a55fbccc8805 --- /dev/null +++ b/web/node_modules/pathval/LICENSE @@ -0,0 +1,16 @@ +MIT License + +Copyright (c) 2011-2013 Jake Luer jake@alogicalparadox.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/web/node_modules/pathval/README.md b/web/node_modules/pathval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..22a841eb930c2b7b36cbcef1ba3d5bb194edf6cf --- /dev/null +++ b/web/node_modules/pathval/README.md @@ -0,0 +1,147 @@ +

+ + ChaiJS + +
+ pathval +

+ +

+ Tool for Object value retrieval given a string path for node and the browser. +

+ +

+ + license:mit + + + tag:? + + + build:? + + + coverage:? + + + npm:? + + + dependencies:? + + + devDependencies:? + +
+ + Selenium Test Status + +
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is pathval? + +Pathval is a module which you can use to retrieve or set an Object's property for a given `String` path. + +## Installation + +### Node.js + +`pathval` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install pathval + +### Browsers + +You can also use it within the browser; install via npm and use the `pathval.js` file found within the download. For example: + +```html + +``` + +## Usage + +The primary export of `pathval` is an object which has the following methods: + +* `hasProperty(object, name)` - Checks whether an `object` has `name`d property or numeric array index. +* `getPathInfo(object, path)` - Returns an object with info indicating the value of the `parent` of that path, the `name ` of the property we're retrieving and its `value`. +* `getPathValue(object, path)` - Retrieves the value of a property at a given `path` inside an `object`'. +* `setPathValue(object, path, value)` - Sets the `value` of a property at a given `path` inside an `object` and returns the object in which the property has been set. + +```js +var pathval = require('pathval'); +``` + +#### .hasProperty(object, name) + +```js +var pathval = require('pathval'); + +var obj = { prop: 'a value' }; +pathval.hasProperty(obj, 'prop'); // true +``` + +#### .getPathInfo(object, path) + +```js +var pathval = require('pathval'); + +var obj = { earth: { country: 'Brazil' } }; +pathval.getPathInfo(obj, 'earth.country'); // { parent: { country: 'Brazil' }, name: 'country', value: 'Brazil', exists: true } +``` + +#### .getPathValue(object, path) + +```js +var pathval = require('pathval'); + +var obj = { earth: { country: 'Brazil' } }; +pathval.getPathValue(obj, 'earth.country'); // 'Brazil' +``` + +#### .setPathValue(object, path, value) + +```js +var pathval = require('pathval'); + +var obj = { earth: { country: 'Brazil' } }; +pathval.setPathValue(obj, 'earth.country', 'USA'); + +obj.earth.country; // 'USA' +``` diff --git a/web/node_modules/pathval/index.js b/web/node_modules/pathval/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d0dc43e0882e2eac4ea154a1ac0ebb387687b865 --- /dev/null +++ b/web/node_modules/pathval/index.js @@ -0,0 +1,301 @@ +'use strict'; + +/* ! + * Chai - pathval utility + * Copyright(c) 2012-2014 Jake Luer + * @see https://github.com/logicalparadox/filtr + * MIT Licensed + */ + +/** + * ### .hasProperty(object, name) + * + * This allows checking whether an object has own + * or inherited from prototype chain named property. + * + * Basically does the same thing as the `in` + * operator but works properly with null/undefined values + * and other primitives. + * + * var obj = { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * + * The following would be the results. + * + * hasProperty(obj, 'str'); // true + * hasProperty(obj, 'constructor'); // true + * hasProperty(obj, 'bar'); // false + * + * hasProperty(obj.str, 'length'); // true + * hasProperty(obj.str, 1); // true + * hasProperty(obj.str, 5); // false + * + * hasProperty(obj.arr, 'length'); // true + * hasProperty(obj.arr, 2); // true + * hasProperty(obj.arr, 3); // false + * + * @param {Object} object + * @param {String|Symbol} name + * @returns {Boolean} whether it exists + * @namespace Utils + * @name hasProperty + * @api public + */ + +function hasProperty(obj, name) { + if (typeof obj === 'undefined' || obj === null) { + return false; + } + + // The `in` operator does not work with primitives. + return name in Object(obj); +} + +/* ! + * ## parsePath(path) + * + * Helper function used to parse string object + * paths. Use in conjunction with `internalGetPathValue`. + * + * var parsed = parsePath('myobject.property.subprop'); + * + * ### Paths: + * + * * Can be infinitely deep and nested. + * * Arrays are also valid using the formal `myobject.document[3].property`. + * * Literal dots and brackets (not delimiter) must be backslash-escaped. + * + * @param {String} path + * @returns {Object} parsed + * @api private + */ + +function parsePath(path) { + var str = path.replace(/([^\\])\[/g, '$1.['); + var parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map(function mapMatches(value) { + if ( + value === 'constructor' || + value === '__proto__' || + value === 'prototype' + ) { + return {}; + } + var regexp = /^\[(\d+)\]$/; + var mArr = regexp.exec(value); + var parsed = null; + if (mArr) { + parsed = { i: parseFloat(mArr[1]) }; + } else { + parsed = { p: value.replace(/\\([.[\]])/g, '$1') }; + } + + return parsed; + }); +} + +/* ! + * ## internalGetPathValue(obj, parsed[, pathDepth]) + * + * Helper companion function for `.parsePath` that returns + * the value located at the parsed address. + * + * var value = getPathValue(obj, parsed); + * + * @param {Object} object to search against + * @param {Object} parsed definition from `parsePath`. + * @param {Number} depth (nesting level) of the property we want to retrieve + * @returns {Object|Undefined} value + * @api private + */ + +function internalGetPathValue(obj, parsed, pathDepth) { + var temporaryValue = obj; + var res = null; + pathDepth = typeof pathDepth === 'undefined' ? parsed.length : pathDepth; + + for (var i = 0; i < pathDepth; i++) { + var part = parsed[i]; + if (temporaryValue) { + if (typeof part.p === 'undefined') { + temporaryValue = temporaryValue[part.i]; + } else { + temporaryValue = temporaryValue[part.p]; + } + + if (i === pathDepth - 1) { + res = temporaryValue; + } + } + } + + return res; +} + +/* ! + * ## internalSetPathValue(obj, value, parsed) + * + * Companion function for `parsePath` that sets + * the value located at a parsed address. + * + * internalSetPathValue(obj, 'value', parsed); + * + * @param {Object} object to search and define on + * @param {*} value to use upon set + * @param {Object} parsed definition from `parsePath` + * @api private + */ + +function internalSetPathValue(obj, val, parsed) { + var tempObj = obj; + var pathDepth = parsed.length; + var part = null; + // Here we iterate through every part of the path + for (var i = 0; i < pathDepth; i++) { + var propName = null; + var propVal = null; + part = parsed[i]; + + // If it's the last part of the path, we set the 'propName' value with the property name + if (i === pathDepth - 1) { + propName = typeof part.p === 'undefined' ? part.i : part.p; + // Now we set the property with the name held by 'propName' on object with the desired val + tempObj[propName] = val; + } else if (typeof part.p !== 'undefined' && tempObj[part.p]) { + tempObj = tempObj[part.p]; + } else if (typeof part.i !== 'undefined' && tempObj[part.i]) { + tempObj = tempObj[part.i]; + } else { + // If the obj doesn't have the property we create one with that name to define it + var next = parsed[i + 1]; + // Here we set the name of the property which will be defined + propName = typeof part.p === 'undefined' ? part.i : part.p; + // Here we decide if this property will be an array or a new object + propVal = typeof next.p === 'undefined' ? [] : {}; + tempObj[propName] = propVal; + tempObj = tempObj[propName]; + } + } +} + +/** + * ### .getPathInfo(object, path) + * + * This allows the retrieval of property info in an + * object given a string path. + * + * The path info consists of an object with the + * following properties: + * + * * parent - The parent object of the property referenced by `path` + * * name - The name of the final property, a number if it was an array indexer + * * value - The value of the property, if it exists, otherwise `undefined` + * * exists - Whether the property exists or not + * + * @param {Object} object + * @param {String} path + * @returns {Object} info + * @namespace Utils + * @name getPathInfo + * @api public + */ + +function getPathInfo(obj, path) { + var parsed = parsePath(path); + var last = parsed[parsed.length - 1]; + var info = { + parent: + parsed.length > 1 ? + internalGetPathValue(obj, parsed, parsed.length - 1) : + obj, + name: last.p || last.i, + value: internalGetPathValue(obj, parsed), + }; + info.exists = hasProperty(info.parent, info.name); + + return info; +} + +/** + * ### .getPathValue(object, path) + * + * This allows the retrieval of values in an + * object given a string path. + * + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * } + * + * The following would be the results. + * + * getPathValue(obj, 'prop1.str'); // Hello + * getPathValue(obj, 'prop1.att[2]'); // b + * getPathValue(obj, 'prop2.arr[0].nested'); // Universe + * + * @param {Object} object + * @param {String} path + * @returns {Object} value or `undefined` + * @namespace Utils + * @name getPathValue + * @api public + */ + +function getPathValue(obj, path) { + var info = getPathInfo(obj, path); + return info.value; +} + +/** + * ### .setPathValue(object, path, value) + * + * Define the value in an object at a given string path. + * + * ```js + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * }; + * ``` + * + * The following would be acceptable. + * + * ```js + * var properties = require('tea-properties'); + * properties.set(obj, 'prop1.str', 'Hello Universe!'); + * properties.set(obj, 'prop1.arr[2]', 'B'); + * properties.set(obj, 'prop2.arr[0].nested.value', { hello: 'universe' }); + * ``` + * + * @param {Object} object + * @param {String} path + * @param {Mixed} value + * @api private + */ + +function setPathValue(obj, path, val) { + var parsed = parsePath(path); + internalSetPathValue(obj, val, parsed); + return obj; +} + +module.exports = { + hasProperty: hasProperty, + getPathInfo: getPathInfo, + getPathValue: getPathValue, + setPathValue: setPathValue, +}; diff --git a/web/node_modules/pathval/package.json b/web/node_modules/pathval/package.json new file mode 100644 index 0000000000000000000000000000000000000000..48ead1bdbb44e2b2667754989f147d9c0bcad225 --- /dev/null +++ b/web/node_modules/pathval/package.json @@ -0,0 +1,80 @@ +{ + "name": "pathval", + "description": "Object value retrieval given a string path", + "homepage": "https://github.com/chaijs/pathval", + "version": "1.1.1", + "keywords": [ + "pathval", + "value retrieval", + "chai util" + ], + "license": "MIT", + "author": "Veselin Todorov ", + "files": [ + "index.js", + "pathval.js" + ], + "main": "./index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/chaijs/pathval.git" + }, + "scripts": { + "build": "browserify --standalone pathval -o pathval.js", + "lint": "eslint --ignore-path .gitignore .", + "lint:fix": "npm run lint -- --fix", + "prepublish": "npm run build", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser && npm run upload-coverage", + "test:browser": "karma start --singleRun=true", + "test:node": "nyc mocha", + "upload-coverage": "lcov-result-merger 'coverage/**/lcov.info' | coveralls; exit 0" + }, + "config": { + "ghooks": { + "commit-msg": "validate-commit-msg" + } + }, + "eslintConfig": { + "extends": [ + "strict/es5" + ], + "env": { + "es6": true + }, + "globals": { + "HTMLElement": false + }, + "rules": { + "complexity": 0, + "max-statements": 0 + } + }, + "devDependencies": { + "browserify": "^17.0.0", + "browserify-istanbul": "^3.0.1", + "coveralls": "^3.1.0", + "eslint": "^7.13.0", + "eslint-config-strict": "^14.0.1", + "eslint-plugin-filenames": "^1.3.2", + "ghooks": "^2.0.4", + "karma": "^5.2.3", + "karma-browserify": "^7.0.0", + "karma-coverage": "^2.0.3", + "karma-mocha": "^2.0.1", + "karma-phantomjs-launcher": "^1.0.4", + "karma-sauce-launcher": "^4.3.3", + "lcov-result-merger": "^3.1.0", + "mocha": "^8.2.1", + "nyc": "^15.1.0", + "phantomjs-prebuilt": "^2.1.16", + "semantic-release": "^17.2.2", + "simple-assert": "^1.0.0", + "travis-after-all": "^1.4.5", + "validate-commit-msg": "^2.14.0" + }, + "engines": { + "node": "*" + } +} diff --git a/web/node_modules/pathval/pathval.js b/web/node_modules/pathval/pathval.js new file mode 100644 index 0000000000000000000000000000000000000000..0070ed4586ce0473ac2034cb9150db29759269e9 --- /dev/null +++ b/web/node_modules/pathval/pathval.js @@ -0,0 +1 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i Colors } + +export = picocolors diff --git a/web/node_modules/picocolors/picocolors.js b/web/node_modules/picocolors/picocolors.js new file mode 100644 index 0000000000000000000000000000000000000000..fdb630451d89b134b069355bb97556e39b0b171a --- /dev/null +++ b/web/node_modules/picocolors/picocolors.js @@ -0,0 +1,58 @@ +let tty = require("tty") + +let isColorSupported = + !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && + ("FORCE_COLOR" in process.env || + process.argv.includes("--color") || + process.platform === "win32" || + (tty.isatty(1) && process.env.TERM !== "dumb") || + "CI" in process.env) + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input + let 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 start = string.substring(0, index) + replace + let end = string.substring(index + close.length) + let nextIndex = end.indexOf(close) + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +} + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}) + +module.exports = createColors() +module.exports.createColors = createColors diff --git a/web/node_modules/picocolors/types.ts b/web/node_modules/picocolors/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4bacee4909e7f562fb13f89720c8ae57c4922fc --- /dev/null +++ b/web/node_modules/picocolors/types.ts @@ -0,0 +1,30 @@ +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 +} diff --git a/web/node_modules/pkg-types/LICENSE b/web/node_modules/pkg-types/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..743af99259533dc56ef8c3a515727cd2adb42a74 --- /dev/null +++ b/web/node_modules/pkg-types/LICENSE @@ -0,0 +1,44 @@ +MIT License + +Copyright (c) Pooya Parsa - Daniel Roe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/web/node_modules/pkg-types/README.md b/web/node_modules/pkg-types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..07f69285b6c9d2c42f151bedc6a88483fac7284e --- /dev/null +++ b/web/node_modules/pkg-types/README.md @@ -0,0 +1,141 @@ +# pkg-types + +> Node.js utilities and TypeScript definitions for `package.json` and `tsconfig.json` + +``` +\⍩⃝/ +``` + +## Install + +```sh +# npm +npm i pkg-types + +# yarn +yarn add pkg-types + +# pnpm +pnpm add pkg-types +``` + +## Usage + +### `readPackageJSON` + +```js +import { readPackageJSON } from 'pkg-types' +const localPackageJson = await readPackageJSON() +// or +const packageJson = await readPackageJSON('/fully/resolved/path/to/folder') +``` + +### `writePackageJSON` + +```js +import { writePackageJSON } from 'pkg-types' + +await writePackageJSON('path/to/package.json', pkg) +``` + +### `resolvePackageJSON` + +```js +import { resolvePackageJSON } from 'pkg-types' +const filename = await resolvePackageJSON() +// or +const packageJson = await resolvePackageJSON('/fully/resolved/path/to/folder') +``` + +### `readTSConfig` + +```js +import { readTSConfig } from 'pkg-types' +const tsconfig = await readTSConfig() +// or +const tsconfig = await readTSConfig('/fully/resolved/path/to/folder') +``` + +### `writeTSConfig` + +```js +import { writeTSConfig } from 'pkg-types' + +await writeTSConfig('path/to/tsconfig.json', tsconfig) +``` + +### `resolveTSConfig` + +```js +import { resolveTSConfig } from 'pkg-types' +const filename = await resolveTSConfig() +// or +const tsconfig = await resolveTSConfig('/fully/resolved/path/to/folder') +``` + +### `resolveFile` + +```js +import { resolveFile } from 'pkg-types' +const filename = await resolveFile('README.md', { + startingFrom: id, + rootPattern: /^node_modules$/, + matcher: filename => filename.endsWith('.md'), +}) +``` + +### `resolveLockFile` + +Find path to the lock file (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`, `npm-shrinkwrap.json`) or throws an error. + +```js +import { resolveLockFile } from 'pkg-types' +const lockfile = await resolveLockFile('.') +``` + +### `findWorkspaceDir` + +Try to detect workspace dir by in order: + +1. Nearest `.git` directory +2. Farthest lockfile +3. Farthest `package.json` file + +If fails, throws an error. + +```js +import { findWorkspaceDir } from 'pkg-types' +const workspaceDir = await findWorkspaceDir('.') +``` + +## Types + +**Note:** In order to make types working, you need to install `typescript` as a devDependency. + +You can directly use typed interfaces: + +```ts +import type { TSConfig, PackageJSON } from 'pkg-types' +``` + +You can also use define utils for type support for using in plain `.js` files and auto-complete in IDE. + +```js +import type { definePackageJSON } from 'pkg-types' + +const pkg = definePackageJSON({}) +``` + +```js +import type { defineTSConfig } from 'pkg-types' + +const pkg = defineTSConfig({}) +``` + +## Alternatives + +- [dominikg/tsconfck](https://github.com/dominikg/tsconfck) + +## License + +MIT - Made with 💛 diff --git a/web/node_modules/pkg-types/dist/index.cjs b/web/node_modules/pkg-types/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..36243f9fedddc9afe58fbda99d2606f65eda6c24 --- /dev/null +++ b/web/node_modules/pkg-types/dist/index.cjs @@ -0,0 +1,162 @@ +'use strict'; + +const node_fs = require('node:fs'); +const pathe = require('pathe'); +const mlly = require('mlly'); + +const defaultFindOptions = { + startingFrom: ".", + rootPattern: /^node_modules$/, + reverse: false, + test: (filePath) => { + try { + if (node_fs.statSync(filePath).isFile()) { + return true; + } + } catch { + } + } +}; +async function findFile(filename, _options = {}) { + const options = { ...defaultFindOptions, ..._options }; + const basePath = pathe.resolve(options.startingFrom); + const leadingSlash = basePath[0] === "/"; + const segments = basePath.split("/").filter(Boolean); + if (leadingSlash) { + segments[0] = "/" + segments[0]; + } + let root = segments.findIndex((r) => r.match(options.rootPattern)); + if (root === -1) { + root = 0; + } + if (!options.reverse) { + for (let index = segments.length; index > root; index--) { + const filePath = pathe.join(...segments.slice(0, index), filename); + if (await options.test(filePath)) { + return filePath; + } + } + } else { + for (let index = root + 1; index <= segments.length; index++) { + const filePath = pathe.join(...segments.slice(0, index), filename); + if (await options.test(filePath)) { + return filePath; + } + } + } + throw new Error( + `Cannot find matching ${filename} in ${options.startingFrom} or parent directories` + ); +} +function findNearestFile(filename, _options = {}) { + return findFile(filename, _options); +} +function findFarthestFile(filename, _options = {}) { + return findFile(filename, { ..._options, reverse: true }); +} + +function definePackageJSON(package_) { + return package_; +} +function defineTSConfig(tsconfig) { + return tsconfig; +} +const FileCache = /* @__PURE__ */ new Map(); +async function readPackageJSON(id, options = {}) { + const resolvedPath = await resolvePackageJSON(id, options); + const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache; + if (options.cache && cache.has(resolvedPath)) { + return cache.get(resolvedPath); + } + const blob = await node_fs.promises.readFile(resolvedPath, "utf8"); + const parsed = JSON.parse(blob); + cache.set(resolvedPath, parsed); + return parsed; +} +async function writePackageJSON(path, package_) { + await node_fs.promises.writeFile(path, JSON.stringify(package_, void 0, 2)); +} +async function readTSConfig(id, options = {}) { + const resolvedPath = await resolveTSConfig(id, options); + const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache; + if (options.cache && cache.has(resolvedPath)) { + return cache.get(resolvedPath); + } + const blob = await node_fs.promises.readFile(resolvedPath, "utf8"); + const jsonc = await import('jsonc-parser'); + const parsed = jsonc.parse(blob); + cache.set(resolvedPath, parsed); + return parsed; +} +async function writeTSConfig(path, tsconfig) { + await node_fs.promises.writeFile(path, JSON.stringify(tsconfig, void 0, 2)); +} +async function resolvePackageJSON(id = process.cwd(), options = {}) { + const resolvedPath = pathe.isAbsolute(id) ? id : await mlly.resolvePath(id, options); + return findNearestFile("package.json", { + startingFrom: resolvedPath, + ...options + }); +} +async function resolveTSConfig(id = process.cwd(), options = {}) { + const resolvedPath = pathe.isAbsolute(id) ? id : await mlly.resolvePath(id, options); + return findNearestFile("tsconfig.json", { + startingFrom: resolvedPath, + ...options + }); +} +const lockFiles = [ + "yarn.lock", + "package-lock.json", + "pnpm-lock.yaml", + "npm-shrinkwrap.json", + "bun.lockb" +]; +async function resolveLockfile(id = process.cwd(), options = {}) { + const resolvedPath = pathe.isAbsolute(id) ? id : await mlly.resolvePath(id, options); + const _options = { startingFrom: resolvedPath, ...options }; + for (const lockFile of lockFiles) { + try { + return await findNearestFile(lockFile, _options); + } catch { + } + } + throw new Error("No lockfile found from " + id); +} +async function findWorkspaceDir(id = process.cwd(), options = {}) { + const resolvedPath = pathe.isAbsolute(id) ? id : await mlly.resolvePath(id, options); + const _options = { startingFrom: resolvedPath, ...options }; + try { + const r = await findNearestFile(".git/config", _options); + return pathe.resolve(r, "../.."); + } catch { + } + try { + const r = await resolveLockfile(resolvedPath, { + ..._options, + reverse: true + }); + return pathe.dirname(r); + } catch { + } + try { + const r = await findFile(resolvedPath, _options); + return pathe.dirname(r); + } catch { + } + throw new Error("Cannot detect workspace root from " + id); +} + +exports.definePackageJSON = definePackageJSON; +exports.defineTSConfig = defineTSConfig; +exports.findFarthestFile = findFarthestFile; +exports.findFile = findFile; +exports.findNearestFile = findNearestFile; +exports.findWorkspaceDir = findWorkspaceDir; +exports.readPackageJSON = readPackageJSON; +exports.readTSConfig = readTSConfig; +exports.resolveLockfile = resolveLockfile; +exports.resolvePackageJSON = resolvePackageJSON; +exports.resolveTSConfig = resolveTSConfig; +exports.writePackageJSON = writePackageJSON; +exports.writeTSConfig = writeTSConfig; diff --git a/web/node_modules/pkg-types/dist/index.d.ts b/web/node_modules/pkg-types/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9e9f8f51e6a090da3ba7a5b9e1c721007fed43f --- /dev/null +++ b/web/node_modules/pkg-types/dist/index.d.ts @@ -0,0 +1,208 @@ +import { ResolveOptions as ResolveOptions$1 } from 'mlly'; +import { CompilerOptions, TypeAcquisition } from 'typescript'; + +interface FindFileOptions { + /** + * The starting directory for the search. + * @default . (same as `process.cwd()`) + */ + startingFrom?: string; + /** + * A pattern to match a path segment above which you don't want to ascend + * @default /^node_modules$/ + */ + rootPattern?: RegExp; + /** + * If true, search starts from root level descending into subdirectories + */ + reverse?: boolean; + /** + * A matcher that can evaluate whether the given path is a valid file (for example, + * by testing whether the file path exists. + * + * @default fs.statSync(path).isFile() + */ + test?: (filePath: string) => boolean | undefined | Promise; +} +/** @deprecated */ +type FindNearestFileOptions = FindFileOptions; +declare function findFile(filename: string, _options?: FindFileOptions): Promise; +declare function findNearestFile(filename: string, _options?: FindFileOptions): Promise; +declare function findFarthestFile(filename: string, _options?: FindFileOptions): Promise; + +type StripEnums> = { + [K in keyof T]: T[K] extends boolean ? T[K] : T[K] extends string ? T[K] : T[K] extends object ? T[K] : T[K] extends Array ? T[K] : T[K] extends undefined ? undefined : any; +}; +interface TSConfig { + compilerOptions?: StripEnums; + exclude?: string[]; + compileOnSave?: boolean; + extends?: string; + files?: string[]; + include?: string[]; + typeAcquisition?: TypeAcquisition; +} + +/** + * A “person” is an object with a “name” field and optionally “url” and “email”. Or you can shorten that all into a single string, and npm will parse it for you. + */ +type PackageJsonPerson = string | { + name: string; + email?: string; + url?: string; +}; +interface PackageJson { + /** + * The name is what your thing is called. + * Some rules: + + - The name must be less than or equal to 214 characters. This includes the scope for scoped packages. + - The name can’t start with a dot or an underscore. + - New packages must not have uppercase letters in the name. + - The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can’t contain any non-URL-safe characters. + + */ + name?: string; + /** + * Version must be parseable by `node-semver`, which is bundled with npm as a dependency. (`npm install semver` to use it yourself.) + */ + version?: string; + /** + * Put a description in it. It’s a string. This helps people discover your package, as it’s listed in `npm search`. + */ + description?: string; + /** + * Put keywords in it. It’s an array of strings. This helps people discover your package as it’s listed in `npm search`. + */ + keywords?: string[]; + /** + * The url to the project homepage. + */ + homepage?: string; + /** + * The url to your project’s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package. + */ + bugs?: string | { + url?: string; + email?: string; + }; + /** + * You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you’re placing on it. + */ + license?: string; + /** + * Specify the place where your code lives. This is helpful for people who want to contribute. If the git repo is on GitHub, then the `npm docs` command will be able to find you. + * For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same shortcut syntax you use for npm install: + */ + repository?: string | { + type: string; + url: string; + /** + * If the `package.json` for your package is not in the root directory (for example if it is part of a monorepo), you can specify the directory in which it lives: + */ + directory?: string; + }; + scripts?: Record; + /** + * If you set `"private": true` in your package.json, then npm will refuse to publish it. + */ + private?: boolean; + /** + * The “author” is one person. + */ + author?: PackageJsonPerson; + /** + * “contributors” is an array of people. + */ + contributors?: PackageJsonPerson[]; + /** + * The optional `files` field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. File patterns follow a similar syntax to `.gitignore`, but reversed: including a file, directory, or glob pattern (`*`, `**\/*`, and such) will make it so that file is included in the tarball when it’s packed. Omitting the field will make it default to `["*"]`, which means it will include all files. + */ + files?: string[]; + /** + * The main field is a module ID that is the primary entry point to your program. That is, if your package is named `foo`, and a user installs it, and then does `require("foo")`, then your main module’s exports object will be returned. + * This should be a module ID relative to the root of your package folder. + * For most modules, it makes the most sense to have a main script and often not much else. + */ + main?: string; + /** + * If your module is meant to be used client-side the browser field should be used instead of the main field. This is helpful to hint users that it might rely on primitives that aren’t available in Node.js modules. (e.g. window) + */ + browser?: string; + /** + * A map of command name to local file name. On install, npm will symlink that file into `prefix/bin` for global installs, or `./node_modules/.bin/` for local installs. + */ + bin?: string | Record; + /** + * Specify either a single file or an array of filenames to put in place for the `man` program to find. + */ + man?: string | string[]; + /** + * Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL. + */ + dependencies?: Record; + /** + * If someone is planning on downloading and using your module in their program, then they probably don’t want or need to download and build the external test or documentation framework that you use. + * In this case, it’s best to map these additional items in a `devDependencies` object. + */ + devDependencies?: Record; + /** + * If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the `optionalDependencies` object. This is a map of package name to version or url, just like the `dependencies` object. The difference is that build failures do not cause installation to fail. + */ + optionalDependencies?: Record; + /** + * In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a `require` of this host. This is usually referred to as a plugin. Notably, your module may be exposing a specific interface, expected and specified by the host documentation. + */ + peerDependencies?: Record; + /** + * TypeScript typings, typically ending by .d.ts + */ + types?: string; + typings?: string; + /** + * Non-Standard Node.js alternate entry-point to main. + * An initial implementation for supporting CJS packages (from main), and use module for ESM modules. + */ + module?: string; + /** + * Make main entry-point be loaded as an ESM module, support "export" syntax instead of "require" + * + * Docs: + * - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_package_json_type_field + * + * @default 'commonjs' + * @since Node.js v14 + */ + type?: "module" | "commonjs"; + /** + * Alternate and extensible alternative to "main" entry point. + * + * When using `{type: "module"}`, any ESM module file MUST end with `.mjs` extension. + * + * Docs: + * - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_exports_sugar + * + * @default 'commonjs' + * @since Node.js v14 + */ + exports?: string | Record<"import" | "require" | "." | "node" | "browser" | string, string | Record<"import" | "require" | string, string>>; + workspaces?: string[]; + [key: string]: any; +} + +type ResolveOptions = ResolveOptions$1 & FindFileOptions; +type ReadOptions = { + cache?: boolean | Map>; +}; +declare function definePackageJSON(package_: PackageJson): PackageJson; +declare function defineTSConfig(tsconfig: TSConfig): TSConfig; +declare function readPackageJSON(id?: string, options?: ResolveOptions & ReadOptions): Promise; +declare function writePackageJSON(path: string, package_: PackageJson): Promise; +declare function readTSConfig(id?: string, options?: ResolveOptions & ReadOptions): Promise; +declare function writeTSConfig(path: string, tsconfig: TSConfig): Promise; +declare function resolvePackageJSON(id?: string, options?: ResolveOptions): Promise; +declare function resolveTSConfig(id?: string, options?: ResolveOptions): Promise; +declare function resolveLockfile(id?: string, options?: ResolveOptions): Promise; +declare function findWorkspaceDir(id?: string, options?: ResolveOptions): Promise; + +export { FindFileOptions, FindNearestFileOptions, PackageJson, PackageJsonPerson, ReadOptions, ResolveOptions, StripEnums, TSConfig, definePackageJSON, defineTSConfig, findFarthestFile, findFile, findNearestFile, findWorkspaceDir, readPackageJSON, readTSConfig, resolveLockfile, resolvePackageJSON, resolveTSConfig, writePackageJSON, writeTSConfig }; diff --git a/web/node_modules/pkg-types/dist/index.mjs b/web/node_modules/pkg-types/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..994904e4444902af17414e37e084637cf3d37ae5 --- /dev/null +++ b/web/node_modules/pkg-types/dist/index.mjs @@ -0,0 +1,148 @@ +import { statSync, promises } from 'node:fs'; +import { resolve, join, isAbsolute, dirname } from 'pathe'; +import { resolvePath } from 'mlly'; + +const defaultFindOptions = { + startingFrom: ".", + rootPattern: /^node_modules$/, + reverse: false, + test: (filePath) => { + try { + if (statSync(filePath).isFile()) { + return true; + } + } catch { + } + } +}; +async function findFile(filename, _options = {}) { + const options = { ...defaultFindOptions, ..._options }; + const basePath = resolve(options.startingFrom); + const leadingSlash = basePath[0] === "/"; + const segments = basePath.split("/").filter(Boolean); + if (leadingSlash) { + segments[0] = "/" + segments[0]; + } + let root = segments.findIndex((r) => r.match(options.rootPattern)); + if (root === -1) { + root = 0; + } + if (!options.reverse) { + for (let index = segments.length; index > root; index--) { + const filePath = join(...segments.slice(0, index), filename); + if (await options.test(filePath)) { + return filePath; + } + } + } else { + for (let index = root + 1; index <= segments.length; index++) { + const filePath = join(...segments.slice(0, index), filename); + if (await options.test(filePath)) { + return filePath; + } + } + } + throw new Error( + `Cannot find matching ${filename} in ${options.startingFrom} or parent directories` + ); +} +function findNearestFile(filename, _options = {}) { + return findFile(filename, _options); +} +function findFarthestFile(filename, _options = {}) { + return findFile(filename, { ..._options, reverse: true }); +} + +function definePackageJSON(package_) { + return package_; +} +function defineTSConfig(tsconfig) { + return tsconfig; +} +const FileCache = /* @__PURE__ */ new Map(); +async function readPackageJSON(id, options = {}) { + const resolvedPath = await resolvePackageJSON(id, options); + const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache; + if (options.cache && cache.has(resolvedPath)) { + return cache.get(resolvedPath); + } + const blob = await promises.readFile(resolvedPath, "utf8"); + const parsed = JSON.parse(blob); + cache.set(resolvedPath, parsed); + return parsed; +} +async function writePackageJSON(path, package_) { + await promises.writeFile(path, JSON.stringify(package_, void 0, 2)); +} +async function readTSConfig(id, options = {}) { + const resolvedPath = await resolveTSConfig(id, options); + const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache; + if (options.cache && cache.has(resolvedPath)) { + return cache.get(resolvedPath); + } + const blob = await promises.readFile(resolvedPath, "utf8"); + const jsonc = await import('jsonc-parser'); + const parsed = jsonc.parse(blob); + cache.set(resolvedPath, parsed); + return parsed; +} +async function writeTSConfig(path, tsconfig) { + await promises.writeFile(path, JSON.stringify(tsconfig, void 0, 2)); +} +async function resolvePackageJSON(id = process.cwd(), options = {}) { + const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, options); + return findNearestFile("package.json", { + startingFrom: resolvedPath, + ...options + }); +} +async function resolveTSConfig(id = process.cwd(), options = {}) { + const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, options); + return findNearestFile("tsconfig.json", { + startingFrom: resolvedPath, + ...options + }); +} +const lockFiles = [ + "yarn.lock", + "package-lock.json", + "pnpm-lock.yaml", + "npm-shrinkwrap.json", + "bun.lockb" +]; +async function resolveLockfile(id = process.cwd(), options = {}) { + const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, options); + const _options = { startingFrom: resolvedPath, ...options }; + for (const lockFile of lockFiles) { + try { + return await findNearestFile(lockFile, _options); + } catch { + } + } + throw new Error("No lockfile found from " + id); +} +async function findWorkspaceDir(id = process.cwd(), options = {}) { + const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, options); + const _options = { startingFrom: resolvedPath, ...options }; + try { + const r = await findNearestFile(".git/config", _options); + return resolve(r, "../.."); + } catch { + } + try { + const r = await resolveLockfile(resolvedPath, { + ..._options, + reverse: true + }); + return dirname(r); + } catch { + } + try { + const r = await findFile(resolvedPath, _options); + return dirname(r); + } catch { + } + throw new Error("Cannot detect workspace root from " + id); +} + +export { definePackageJSON, defineTSConfig, findFarthestFile, findFile, findNearestFile, findWorkspaceDir, readPackageJSON, readTSConfig, resolveLockfile, resolvePackageJSON, resolveTSConfig, writePackageJSON, writeTSConfig }; diff --git a/web/node_modules/pkg-types/package.json b/web/node_modules/pkg-types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a1a1e192d3e78cc69d0670ef675c24d39f4408d3 --- /dev/null +++ b/web/node_modules/pkg-types/package.json @@ -0,0 +1,46 @@ +{ + "name": "pkg-types", + "version": "1.0.3", + "description": "Node.js utilities and TypeScript definitions for `package.json` and `tsconfig.json`", + "license": "MIT", + "main": "./dist/index.cjs", + "sideEffects": false, + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "types": "./dist/index.d.ts", + "repository": "unjs/pkg-types", + "files": [ + "dist" + ], + "scripts": { + "prepack": "unbuild", + "dev": "vitest", + "release": "pnpm test && changelogen --release && npm publish && git push --follow-tags", + "lint": "eslint --ext .ts,.js,.mjs,.cjs . && prettier -c src test", + "lint:fix": "eslint --fix --ext .ts,.js,.mjs,.cjs . && prettier -w src test", + "test": "vitest run --coverage", + "test:types": "tsc --noEmit --module esnext --skipLibCheck --moduleResolution node ./test/*.test.ts" + }, + "dependencies": { + "jsonc-parser": "^3.2.0", + "mlly": "^1.2.0", + "pathe": "^1.1.0" + }, + "devDependencies": { + "@types/node": "^18.16.3", + "@vitest/coverage-c8": "^0.30.1", + "changelogen": "^0.5.3", + "eslint": "^8.39.0", + "eslint-config-unjs": "^0.1.0", + "expect-type": "^0.15.0", + "jiti": "^1.18.2", + "prettier": "^2.8.8", + "typescript": "^5.0.4", + "unbuild": "^1.2.1", + "vitest": "^0.30.1" + }, + "packageManager": "pnpm@8.3.1" +} \ No newline at end of file diff --git a/web/node_modules/postcss/LICENSE b/web/node_modules/postcss/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..da057b4562a8b8fcd8ef3898f795cd08aa412ab4 --- /dev/null +++ b/web/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/web/node_modules/postcss/README.md b/web/node_modules/postcss/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9b646dd0539610df85ac18f4b8ec5fe7d00f4ca1 --- /dev/null +++ b/web/node_modules/postcss/README.md @@ -0,0 +1,28 @@ +# 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 is one of the most popular CSS tools. + +--- + +  Made in Evil Martians, product consulting 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/web/node_modules/postcss/lib/at-rule.d.ts b/web/node_modules/postcss/lib/at-rule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bdee38bee9a75f43e9fbb9deab07ce9a4734220 --- /dev/null +++ b/web/node_modules/postcss/lib/at-rule.d.ts @@ -0,0 +1,137 @@ +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 { + /** + * The at-rule’s name immediately follows the `@`. + * + * ```js + * const root = postcss.parse('@media print {}') + * const media = root.first + * media.name //=> 'media' + * ``` + */ + name: string + /** + * 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'] + /** + * 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' + * ``` + */ + params: string + parent: ContainerWithChildren | undefined + + raws: AtRule.AtRuleRaws + + type: 'atrule' + + constructor(defaults?: AtRule.AtRuleProps) + assign(overrides: AtRule.AtRuleProps | object): this + clone(overrides?: Partial): AtRule + cloneAfter(overrides?: Partial): AtRule + cloneBefore(overrides?: Partial): AtRule +} + +declare class AtRule extends AtRule_ {} + +export = AtRule diff --git a/web/node_modules/postcss/lib/at-rule.js b/web/node_modules/postcss/lib/at-rule.js new file mode 100644 index 0000000000000000000000000000000000000000..9486447b029c6c9991ca1b62e5a5d57c611a7503 --- /dev/null +++ b/web/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/web/node_modules/postcss/lib/comment.d.ts b/web/node_modules/postcss/lib/comment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2445088ec14ed5f3105eb1d4567d75390462181 --- /dev/null +++ b/web/node_modules/postcss/lib/comment.d.ts @@ -0,0 +1,67 @@ +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 + /** + * The comment's text. + */ + text: string + + type: 'comment' + + constructor(defaults?: Comment.CommentProps) + assign(overrides: Comment.CommentProps | object): this + clone(overrides?: Partial): Comment + cloneAfter(overrides?: Partial): Comment + cloneBefore(overrides?: Partial): Comment +} + +declare class Comment extends Comment_ {} + +export = Comment diff --git a/web/node_modules/postcss/lib/comment.js b/web/node_modules/postcss/lib/comment.js new file mode 100644 index 0000000000000000000000000000000000000000..c56650645caed3bb47cf7a39d18696ec47140ca3 --- /dev/null +++ b/web/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/web/node_modules/postcss/lib/container.d.ts b/web/node_modules/postcss/lib/container.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d16b85d08a39d8d71206520f2cd64b88e17c6e26 --- /dev/null +++ b/web/node_modules/postcss/lib/container.d.ts @@ -0,0 +1,490 @@ +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 Rule from './rule.js' + +declare namespace Container { + export class ContainerWithChildren< + Child extends Node = ChildNode + > extends Container_ { + nodes: Child[] + } + + 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?: string[] + } + + export interface ContainerProps extends NodeProps { + nodes?: (ChildNode | ChildProps)[] + } + + // 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 + + /** + * 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: ( + | ChildProps + | ChildProps[] + | Node + | Node[] + | string + | string[] + | undefined + )[] + ): this + + assign(overrides: Container.ContainerProps | object): this + clone(overrides?: Partial): Container + cloneAfter(overrides?: Partial): Container + cloneBefore(overrides?: Partial): Container + + /** + * 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: + | Child + | Child[] + | ChildProps + | ChildProps[] + | string + | string[] + | undefined + ): this + /** + * 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: + | Child + | Child[] + | ChildProps + | ChildProps[] + | string + | string[] + | undefined + ): 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. + */ + + /** + * 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: ( + | ChildProps + | ChildProps[] + | Node + | Node[] + | string + | string[] + | undefined + )[] + ): 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} opts Options to speed up the search. + * @param callback 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 + /** + * 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 +} + +declare class Container< + Child extends Node = ChildNode +> extends Container_ {} + +export = Container diff --git a/web/node_modules/postcss/lib/container.js b/web/node_modules/postcss/lib/container.js new file mode 100644 index 0000000000000000000000000000000000000000..462e3f0d3944ed56d37403d95b229c2942f9e731 --- /dev/null +++ b/web/node_modules/postcss/lib/container.js @@ -0,0 +1,441 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let Declaration = require('./declaration') +let Comment = require('./comment') +let Node = require('./node') + +let parse, Rule, AtRule, Root + +function cleanSource(nodes) { + return nodes.map(i => { + if (i.nodes) i.nodes = cleanSource(i.nodes) + delete i.source + return i + }) +} + +function markDirtyUp(node) { + node[isClean] = false + if (node.proxyOf.nodes) { + for (let i of node.proxyOf.nodes) { + markDirtyUp(i) + } + } +} + +class Container extends Node { + 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 = [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]) markDirtyUp(i) + 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) + } + }) + } + + 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] + } +} + +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/web/node_modules/postcss/lib/css-syntax-error.d.ts b/web/node_modules/postcss/lib/css-syntax-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2d11bf9845839e6b872a5ba5ad49b60c9238df7 --- /dev/null +++ b/web/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_ { + /** + * 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/web/node_modules/postcss/lib/css-syntax-error.js b/web/node_modules/postcss/lib/css-syntax-error.js new file mode 100644 index 0000000000000000000000000000000000000000..169303329e6359e12d59b32cfffc302dd84d2280 --- /dev/null +++ b/web/node_modules/postcss/lib/css-syntax-error.js @@ -0,0 +1,100 @@ +'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 + if (terminalHighlight) { + if (color) css = terminalHighlight(css) + } + + 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 + + let mark, aside + if (color) { + let { bold, gray, red } = pico.createColors(true) + mark = text => bold(red(text)) + aside = text => gray(text) + } else { + mark = aside = str => str + } + + return lines + .slice(start, end) + .map((line, index) => { + let number = start + 1 + index + let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ' + if (number === this.line) { + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line.slice(0, this.column - 1).replace(/[^\t]/g, ' ') + return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^') + } + return ' ' + aside(gutter) + 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/web/node_modules/postcss/lib/declaration.d.ts b/web/node_modules/postcss/lib/declaration.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5db984a4c42eea51a0e9d2ab5b40585f3e5778f --- /dev/null +++ b/web/node_modules/postcss/lib/declaration.d.ts @@ -0,0 +1,148 @@ +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 { + /** + * 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 + * ``` + */ + important: boolean + + parent: ContainerWithChildren | undefined + + /** + * The property name for a CSS declaration. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first.first + * + * decl.prop //=> 'color' + * ``` + */ + prop: string + + raws: Declaration.DeclarationRaws + + type: 'decl' + + /** + * 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' + * ``` + */ + 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 + * ``` + */ + variable: boolean + + constructor(defaults?: Declaration.DeclarationProps) + assign(overrides: Declaration.DeclarationProps | object): this + clone(overrides?: Partial): Declaration + cloneAfter(overrides?: Partial): Declaration + cloneBefore(overrides?: Partial): Declaration +} + +declare class Declaration extends Declaration_ {} + +export = Declaration diff --git a/web/node_modules/postcss/lib/declaration.js b/web/node_modules/postcss/lib/declaration.js new file mode 100644 index 0000000000000000000000000000000000000000..a04bdec36a5149adc3e48b4cb3f9e704254cd740 --- /dev/null +++ b/web/node_modules/postcss/lib/declaration.js @@ -0,0 +1,24 @@ +'use strict' + +let Node = require('./node') + +class Declaration extends Node { + constructor(defaults) { + if ( + defaults && + typeof defaults.value !== 'undefined' && + typeof defaults.value !== 'string' + ) { + defaults = { ...defaults, value: String(defaults.value) } + } + super(defaults) + this.type = 'decl' + } + + get variable() { + return this.prop.startsWith('--') || this.prop[0] === '$' + } +} + +module.exports = Declaration +Declaration.default = Declaration diff --git a/web/node_modules/postcss/lib/document.d.ts b/web/node_modules/postcss/lib/document.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a368f166a0c57b69dfbd25876d4e544d67db8845 --- /dev/null +++ b/web/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?: 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): Document + cloneAfter(overrides?: Partial): Document + cloneBefore(overrides?: Partial): Document + + /** + * 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/web/node_modules/postcss/lib/document.js b/web/node_modules/postcss/lib/document.js new file mode 100644 index 0000000000000000000000000000000000000000..44689917fc57d210b1a4dfad4187ac721c6eb16d --- /dev/null +++ b/web/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/web/node_modules/postcss/lib/fromJSON.d.ts b/web/node_modules/postcss/lib/fromJSON.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1deedbd3344a7b98d810515b34dad8b4f1eb2d6 --- /dev/null +++ b/web/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/web/node_modules/postcss/lib/fromJSON.js b/web/node_modules/postcss/lib/fromJSON.js new file mode 100644 index 0000000000000000000000000000000000000000..09f2b89aa698adf926fae201ca39ad96a52fd488 --- /dev/null +++ b/web/node_modules/postcss/lib/fromJSON.js @@ -0,0 +1,54 @@ +'use strict' + +let Declaration = require('./declaration') +let PreviousMap = require('./previous-map') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Input = require('./input') +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/web/node_modules/postcss/lib/input.d.ts b/web/node_modules/postcss/lib/input.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c718bd1d94f74780e7cc77a97f67e4d8950ca8db --- /dev/null +++ b/web/node_modules/postcss/lib/input.d.ts @@ -0,0 +1,194 @@ +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 + + /** + * Absolute path to the source file. + */ + file?: string + + /** + * Line of inclusive start position in source file. + */ + line: 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 + + /** + * 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 + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + error( + message: string, + start: + | { + column: number + line: number + } + | { + offset: number + }, + end: + | { + column: number + line: number + } + | { + offset: number + }, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + /** + * Returns `CssSyntaxError` with information about the error and its position. + */ + error( + message: string, + line: number, + column: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + error( + message: string, + offset: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + /** + * 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 + /** + * 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 +} + +declare class Input extends Input_ {} + +export = Input diff --git a/web/node_modules/postcss/lib/input.js b/web/node_modules/postcss/lib/input.js new file mode 100644 index 0000000000000000000000000000000000000000..4b5ee5e02f8ecdf880594d191ec1e84b983faeaa --- /dev/null +++ b/web/node_modules/postcss/lib/input.js @@ -0,0 +1,248 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { fileURLToPath, pathToFileURL } = require('url') +let { isAbsolute, resolve } = require('path') +let { nanoid } = require('nanoid/non-secure') + +let terminalHighlight = require('./terminal-highlight') +let CssSyntaxError = require('./css-syntax-error') +let PreviousMap = require('./previous-map') + +let fromOffsetCache = Symbol('fromOffsetCache') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(resolve && isAbsolute) + +class Input { + 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 + } + + 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 result, endLine, endColumn + + if (line && typeof line === 'object') { + let start = line + let end = column + if (typeof start.offset === 'number') { + let pos = this.fromOffset(start.offset) + line = pos.line + column = pos.col + } else { + line = start.line + column = start.column + } + if (typeof end.offset === 'number') { + let pos = this.fromOffset(end.offset) + endLine = pos.line + endColumn = pos.col + } else { + endLine = end.line + endColumn = end.column + } + } else if (!column) { + let pos = this.fromOffset(line) + line = pos.line + column = pos.col + } + + 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, line, source: this.css } + if (this.file) { + if (pathToFileURL) { + result.input.url = pathToFileURL(this.file).toString() + } + result.input.file = this.file + } + + return result + } + + fromOffset(offset) { + let lastLine, lineToIndex + if (!this[fromOffsetCache]) { + let lines = this.css.split('\n') + 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 + } + + this[fromOffsetCache] = lineToIndex + } else { + lineToIndex = this[fromOffsetCache] + } + 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 + } + + get from() { + return this.file || this.id + } +} + +module.exports = Input +Input.default = Input + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input) +} diff --git a/web/node_modules/postcss/lib/lazy-result.d.ts b/web/node_modules/postcss/lib/lazy-result.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd291aa3a79faba1dd68edd4da167d12d3d776b2 --- /dev/null +++ b/web/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'] + + /** + * @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[] + + /** + * 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 +} + +declare class LazyResult< + RootNode = Document | Root +> extends LazyResult_ {} + +export = LazyResult diff --git a/web/node_modules/postcss/lib/lazy-result.js b/web/node_modules/postcss/lib/lazy-result.js new file mode 100644 index 0000000000000000000000000000000000000000..126f40c7e9d7a1f131e2d75b68aeab6c93ee9673 --- /dev/null +++ b/web/node_modules/postcss/lib/lazy-result.js @@ -0,0 +1,550 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let MapGenerator = require('./map-generator') +let stringify = require('./stringify') +let Container = require('./container') +let Document = require('./document') +let warnOnce = require('./warn-once') +let Result = require('./result') +let parse = require('./parse') +let Root = require('./root') + +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 { + 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() + } + + 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' + } +} + +LazyResult.registerPostcss = dependant => { + postcss = dependant +} + +module.exports = LazyResult +LazyResult.default = LazyResult + +Root.registerLazyResult(LazyResult) +Document.registerLazyResult(LazyResult) diff --git a/web/node_modules/postcss/lib/list.d.ts b/web/node_modules/postcss/lib/list.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a74d74cf0ebf390f76141a210cfbf9f1be9c798 --- /dev/null +++ b/web/node_modules/postcss/lib/list.d.ts @@ -0,0 +1,57 @@ +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: string[], last: boolean): string[] + } +} + +// eslint-disable-next-line @typescript-eslint/no-redeclare +declare const list: list.List + +export = list diff --git a/web/node_modules/postcss/lib/list.js b/web/node_modules/postcss/lib/list.js new file mode 100644 index 0000000000000000000000000000000000000000..1b31f9809f2cc41616cc9527e7f601d256e669f8 --- /dev/null +++ b/web/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/web/node_modules/postcss/lib/map-generator.js b/web/node_modules/postcss/lib/map-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..ea1ef5ec20dad337a184cfb22e149dfc8e534f6e --- /dev/null +++ b/web/node_modules/postcss/lib/map-generator.js @@ -0,0 +1,360 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { dirname, relative, resolve, sep } = require('path') +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.indexOf('# sourceMappingURL=') === 0) { + 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) + } else { + this.map = new SourceMapGenerator({ file: this.outputFile() }) + 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() }) + + let line = 1 + let column = 1 + + let noSource = '' + let mapping = { + generated: { column: 0, line: 0 }, + original: { column: 0, line: 0 }, + source: '' + } + + let lines, last + 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/web/node_modules/postcss/lib/no-work-result.d.ts b/web/node_modules/postcss/lib/no-work-result.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..803907654ee4e7bfb74a81fbc1e58bed0678fd43 --- /dev/null +++ b/web/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'] + constructor(processor: Processor, css: string, opts: ResultOptions) + async(): Promise> + sync(): Result + toString(): string + warnings(): Warning[] + 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 +} + +declare class NoWorkResult extends NoWorkResult_ {} + +export = NoWorkResult diff --git a/web/node_modules/postcss/lib/no-work-result.js b/web/node_modules/postcss/lib/no-work-result.js new file mode 100644 index 0000000000000000000000000000000000000000..05821b7a318c04b787b62441872b2680681aea4f --- /dev/null +++ b/web/node_modules/postcss/lib/no-work-result.js @@ -0,0 +1,138 @@ +'use strict' + +let MapGenerator = require('./map-generator') +let stringify = require('./stringify') +let warnOnce = require('./warn-once') +let parse = require('./parse') +const Result = require('./result') + +class 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 [] + } + + 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' + } +} + +module.exports = NoWorkResult +NoWorkResult.default = NoWorkResult diff --git a/web/node_modules/postcss/lib/node.d.ts b/web/node_modules/postcss/lib/node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59716564517b7bf17c3b477fd3ce7b554ff841b3 --- /dev/null +++ b/web/node_modules/postcss/lib/node.d.ts @@ -0,0 +1,536 @@ +import AtRule = require('./at-rule.js') + +import { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container 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. + */ + 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 | 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 | 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): Node + + /** + * 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): Node + + /** + * 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): Node + + /** + * 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: ( + | Node.ChildNode + | Node.ChildNode[] + | Node.ChildProps + | Node.ChildProps[] + )[] + ): 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 +} + +declare class Node extends Node_ {} + +export = Node diff --git a/web/node_modules/postcss/lib/node.js b/web/node_modules/postcss/lib/node.js new file mode 100644 index 0000000000000000000000000000000000000000..d79dd56e54d544bb906ab0b5b67ff252155b3068 --- /dev/null +++ b/web/node_modules/postcss/lib/node.js @@ -0,0 +1,381 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let CssSyntaxError = require('./css-syntax-error') +let Stringifier = require('./stringifier') +let stringify = require('./stringify') + +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 +} + +class Node { + 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 + } + } + } + + 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, stringRepresentation) { + let pos = this.source.start + if (opts.index) { + pos = this.positionInside(opts.index, stringRepresentation) + } else if (opts.word) { + stringRepresentation = this.toString() + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index, stringRepresentation) + } + return pos + } + + positionInside(index, stringRepresentation) { + let string = stringRepresentation || this.toString() + let column = this.source.start.column + let line = this.source.start.line + + for (let i = 0; i < index; i++) { + if (string[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return { column, line } + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] + } + + rangeBy(opts) { + let start = { + column: this.source.start.column, + line: this.source.start.line + } + let end = this.source.end + ? { + column: this.source.end.column + 1, + line: this.source.end.line + } + : { + column: start.column + 1, + line: start.line + } + + if (opts.word) { + let stringRepresentation = this.toString() + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) { + start = this.positionInside(index, stringRepresentation) + end = this.positionInside(index + opts.word.length, stringRepresentation) + } + } else { + if (opts.start) { + start = { + column: opts.start.column, + line: opts.start.line + } + } else if (opts.index) { + start = this.positionInside(opts.index) + } + + if (opts.end) { + end = { + column: opts.end.column, + line: opts.end.line + } + } else if (opts.endIndex) { + 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 } + } + + 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') { + 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) + } + + get proxyOf() { + return this + } +} + +module.exports = Node +Node.default = Node diff --git a/web/node_modules/postcss/lib/parse.d.ts b/web/node_modules/postcss/lib/parse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c943a4d6279c8bb944b3f26004548bb9e4cb98e --- /dev/null +++ b/web/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/web/node_modules/postcss/lib/parse.js b/web/node_modules/postcss/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..971431f238b124ec071fd7b7fac973e1aac8ec3c --- /dev/null +++ b/web/node_modules/postcss/lib/parse.js @@ -0,0 +1,42 @@ +'use strict' + +let Container = require('./container') +let Parser = require('./parser') +let Input = require('./input') + +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/web/node_modules/postcss/lib/parser.js b/web/node_modules/postcss/lib/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..bc761dedaea4a0b3239a8af4648fda853c2fa332 --- /dev/null +++ b/web/node_modules/postcss/lib/parser.js @@ -0,0 +1,609 @@ +'use strict' + +let Declaration = require('./declaration') +let tokenizer = require('./tokenize') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Root = require('./root') +let Rule = require('./rule') + +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 token, type, prev + 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().indexOf('!') === 0 && type !== 'space') { + break + } + str = cache.pop()[1] + str + } + if (str.trim().indexOf('!') === 0) { + 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 = '' + } + } + } + + // 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', + { 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/web/node_modules/postcss/lib/postcss.d.mts b/web/node_modules/postcss/lib/postcss.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a8ca8c7a1882a5f6f52aef08e957cdea144efc39 --- /dev/null +++ b/web/node_modules/postcss/lib/postcss.d.mts @@ -0,0 +1,72 @@ +export { + // postcss function / namespace + default, + + // Value exports from postcss.mjs + stringify, + fromJSON, + // @ts-expect-error This value exists, but it’s untyped. + plugin, + parse, + list, + + document, + comment, + atRule, + rule, + decl, + root, + + CssSyntaxError, + Declaration, + Container, + Processor, + Document, + Comment, + Warning, + AtRule, + Result, + Input, + Rule, + Root, + Node, + + // Type-only exports + AcceptedPlugin, + AnyNode, + AtRuleProps, + Builder, + ChildNode, + ChildProps, + CommentProps, + ContainerProps, + DeclarationProps, + DocumentProps, + FilePosition, + Helpers, + JSONHydrator, + Message, + NodeErrorOptions, + NodeProps, + OldPlugin, + Parser, + Plugin, + PluginCreator, + Position, + Postcss, + ProcessOptions, + RootProps, + RuleProps, + Source, + SourceMap, + SourceMapOptions, + Stringifier, + Syntax, + TransformCallback, + Transformer, + WarningOptions, + + // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here. + type LazyResult, + +} from './postcss.js' diff --git a/web/node_modules/postcss/lib/postcss.d.ts b/web/node_modules/postcss/lib/postcss.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..49af61c394e5edb4e7ed67bc8b77a629b688eb9f --- /dev/null +++ b/web/node_modules/postcss/lib/postcss.d.ts @@ -0,0 +1,441 @@ +import { RawSourceMap, SourceMapGenerator } from 'source-map-js' + +import AtRule, { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { ContainerProps } 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, + Node, + NodeErrorOptions, + NodeProps, + Position, + Processor, + Result, + Root, + RootProps, + Rule, + RuleProps, + Source, + Warning, + WarningOptions + } + + export type SourceMap = SourceMapGenerator & { + toJSON(): RawSourceMap + } + + 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 { + /** + * The path of the CSS source file. You should always set `from`, + * because it is used in source map generation and syntax error messages. + */ + from?: string | undefined + + /** + * Source map options + */ + map?: boolean | SourceMapOptions + + /** + * Function to generate AST by string. + */ + parser?: Parser | Syntax + + /** + * Class to generate string by AST. + */ + stringifier?: Stringifier | Syntax + + /** + * Object with parse and stringify. + */ + syntax?: Syntax + + /** + * The path where you'll put the output CSS file. You should always set `to` + * to generate correct source maps. + */ + to?: string + } + + export type Postcss = typeof postcss + + /** + * Default function to convert a node tree into a CSS string. + */ + export let stringify: Stringifier + + /** + * Parses source css and returns a new `Root` or `Document` node, + * which contains the source CSS nodes. + * + * ```js + * // Simple CSS concatenation with source map support + * const root1 = postcss.parse(css1, { from: file1 }) + * const root2 = postcss.parse(css2, { from: file2 }) + * root1.append(root2).toResult().css + * ``` + */ + export let parse: Parser + + /** + * Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes. + * + * ```js + * const json = root.toJSON() + * // save to file, send by network, etc + * const root2 = postcss.fromJSON(json) + * ``` + */ + export let fromJSON: JSONHydrator + + /** + * Creates a new `Comment` node. + * + * @param defaults Properties for the new node. + * @return New comment node + */ + export function comment(defaults?: CommentProps): Comment + + /** + * Creates a new `AtRule` node. + * + * @param defaults Properties for the new node. + * @return New at-rule node. + */ + export function atRule(defaults?: AtRuleProps): AtRule + + /** + * Creates a new `Declaration` node. + * + * @param defaults Properties for the new node. + * @return New declaration node. + */ + export function decl(defaults?: DeclarationProps): Declaration + + /** + * Creates a new `Rule` node. + * + * @param default Properties for the new node. + * @return New rule node. + */ + export function rule(defaults?: RuleProps): Rule + + /** + * Creates a new `Root` node. + * + * @param defaults Properties for the new node. + * @return New root node. + */ + export function root(defaults?: RootProps): Root + + /** + * Creates a new `Document` node. + * + * @param defaults Properties for the new node. + * @return New document node. + */ + export function document(defaults?: DocumentProps): Document + + export { postcss as default } +} + +/** + * Create a new `Processor` instance that will apply `plugins` + * as CSS processors. + * + * ```js + * let postcss = require('postcss') + * + * postcss(plugins).process(css, { from, to }).then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param plugins PostCSS plugins. + * @return Processor to process multiple CSS. + */ +declare function postcss(plugins?: postcss.AcceptedPlugin[]): Processor +declare function postcss(...plugins: postcss.AcceptedPlugin[]): Processor + +export = postcss diff --git a/web/node_modules/postcss/lib/postcss.js b/web/node_modules/postcss/lib/postcss.js new file mode 100644 index 0000000000000000000000000000000000000000..080ee8378977d092c94f10c9e567dac78db78812 --- /dev/null +++ b/web/node_modules/postcss/lib/postcss.js @@ -0,0 +1,101 @@ +'use strict' + +let CssSyntaxError = require('./css-syntax-error') +let Declaration = require('./declaration') +let LazyResult = require('./lazy-result') +let Container = require('./container') +let Processor = require('./processor') +let stringify = require('./stringify') +let fromJSON = require('./fromJSON') +let Document = require('./document') +let Warning = require('./warning') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Result = require('./result.js') +let Input = require('./input') +let parse = require('./parse') +let list = require('./list') +let Rule = require('./rule') +let Root = require('./root') +let Node = require('./node') + +function postcss(...plugins) { + if (plugins.length === 1 && Array.isArray(plugins[0])) { + plugins = plugins[0] + } + return new Processor(plugins) +} + +postcss.plugin = function plugin(name, initializer) { + let warningPrinted = false + function creator(...args) { + // eslint-disable-next-line no-console + if (console && console.warn && !warningPrinted) { + warningPrinted = true + // eslint-disable-next-line no-console + console.warn( + name + + ': postcss.plugin was deprecated. Migration guide:\n' + + 'https://evilmartians.com/chronicles/postcss-8-plugin-migration' + ) + if (process.env.LANG && process.env.LANG.startsWith('cn')) { + /* c8 ignore next 7 */ + // eslint-disable-next-line no-console + console.warn( + name + + ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + + 'https://www.w3ctech.com/topic/2226' + ) + } + } + let transformer = initializer(...args) + transformer.postcssPlugin = name + transformer.postcssVersion = new Processor().version + return transformer + } + + let cache + Object.defineProperty(creator, 'postcss', { + get() { + if (!cache) cache = creator() + return cache + } + }) + + creator.process = function (css, processOpts, pluginOpts) { + return postcss([creator(pluginOpts)]).process(css, processOpts) + } + + return creator +} + +postcss.stringify = stringify +postcss.parse = parse +postcss.fromJSON = fromJSON +postcss.list = list + +postcss.comment = defaults => new Comment(defaults) +postcss.atRule = defaults => new AtRule(defaults) +postcss.decl = defaults => new Declaration(defaults) +postcss.rule = defaults => new Rule(defaults) +postcss.root = defaults => new Root(defaults) +postcss.document = defaults => new Document(defaults) + +postcss.CssSyntaxError = CssSyntaxError +postcss.Declaration = Declaration +postcss.Container = Container +postcss.Processor = Processor +postcss.Document = Document +postcss.Comment = Comment +postcss.Warning = Warning +postcss.AtRule = AtRule +postcss.Result = Result +postcss.Input = Input +postcss.Rule = Rule +postcss.Root = Root +postcss.Node = Node + +LazyResult.registerPostcss(postcss) + +module.exports = postcss +postcss.default = postcss diff --git a/web/node_modules/postcss/lib/postcss.mjs b/web/node_modules/postcss/lib/postcss.mjs new file mode 100644 index 0000000000000000000000000000000000000000..35075988c69c7316f5d64361fc65795e1e5e6c68 --- /dev/null +++ b/web/node_modules/postcss/lib/postcss.mjs @@ -0,0 +1,30 @@ +import postcss from './postcss.js' + +export default postcss + +export const stringify = postcss.stringify +export const fromJSON = postcss.fromJSON +export const plugin = postcss.plugin +export const parse = postcss.parse +export const list = postcss.list + +export const document = postcss.document +export const comment = postcss.comment +export const atRule = postcss.atRule +export const rule = postcss.rule +export const decl = postcss.decl +export const root = postcss.root + +export const CssSyntaxError = postcss.CssSyntaxError +export const Declaration = postcss.Declaration +export const Container = postcss.Container +export const Processor = postcss.Processor +export const Document = postcss.Document +export const Comment = postcss.Comment +export const Warning = postcss.Warning +export const AtRule = postcss.AtRule +export const Result = postcss.Result +export const Input = postcss.Input +export const Rule = postcss.Rule +export const Root = postcss.Root +export const Node = postcss.Node diff --git a/web/node_modules/postcss/lib/previous-map.d.ts b/web/node_modules/postcss/lib/previous-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23edeb5c5efc6c0f328282bf4a3b5f338587b11a --- /dev/null +++ b/web/node_modules/postcss/lib/previous-map.d.ts @@ -0,0 +1,81 @@ +import { SourceMapConsumer } from 'source-map-js' + +import { ProcessOptions } from './postcss.js' + +declare namespace PreviousMap { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { PreviousMap_ as default } +} + +/** + * Source map information from input CSS. + * For example, source map after Sass compiler. + * + * This class will automatically find source map in input CSS or in file system + * near input file (according `from` option). + * + * ```js + * const root = parse(css, { from: 'a.sass.css' }) + * root.input.map //=> PreviousMap + * ``` + */ +declare class PreviousMap_ { + /** + * `sourceMappingURL` content. + */ + annotation?: string + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + */ + file?: string + + /** + * Was source map inlined by data-uri to input CSS. + */ + inline: boolean + + /** + * Path to source map file. + */ + mapFile?: string + + /** + * The directory with source map file, if source map is in separated file. + */ + root?: string + + /** + * Source map file content. + */ + text?: string + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * Create a instance of `SourceMapGenerator` class + * from the `source-map` library to work with source map information. + * + * It is lazy method, so it will create object only on first call + * and then it will use cache. + * + * @return Object with source map information. + */ + consumer(): SourceMapConsumer + + /** + * Does source map contains `sourcesContent` with input source text. + * + * @return Is `sourcesContent` present. + */ + withContent(): boolean +} + +declare class PreviousMap extends PreviousMap_ {} + +export = PreviousMap diff --git a/web/node_modules/postcss/lib/previous-map.js b/web/node_modules/postcss/lib/previous-map.js new file mode 100644 index 0000000000000000000000000000000000000000..f3093dfb8e77e305a648ae72a8062cac759e81e9 --- /dev/null +++ b/web/node_modules/postcss/lib/previous-map.js @@ -0,0 +1,142 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { existsSync, readFileSync } = require('fs') +let { dirname, join } = require('path') + +function fromBase64(str) { + if (Buffer) { + return Buffer.from(str, 'base64').toString() + } else { + /* c8 ignore next 2 */ + return window.atob(str) + } +} + +class PreviousMap { + constructor(css, opts) { + if (opts.map === false) return + this.loadAnnotation(css) + this.inline = this.startWith(this.annotation, 'data:') + + let prev = opts.map ? opts.map.prev : undefined + let text = this.loadMap(opts.from, prev) + if (!this.mapFile && opts.from) { + this.mapFile = opts.from + } + if (this.mapFile) this.root = dirname(this.mapFile) + if (text) this.text = text + } + + consumer() { + if (!this.consumerCache) { + this.consumerCache = new SourceMapConsumer(this.text) + } + return this.consumerCache + } + + decodeInline(text) { + let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/ + let baseUri = /^data:application\/json;base64,/ + let charsetUri = /^data:application\/json;charset=utf-?8,/ + let uri = /^data:application\/json,/ + + if (charsetUri.test(text) || uri.test(text)) { + return decodeURIComponent(text.substr(RegExp.lastMatch.length)) + } + + if (baseCharsetUri.test(text) || baseUri.test(text)) { + return fromBase64(text.substr(RegExp.lastMatch.length)) + } + + let encoding = text.match(/data:application\/json;([^,]+),/)[1] + throw new Error('Unsupported source map encoding ' + encoding) + } + + getAnnotationURL(sourceMapString) { + return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim() + } + + isMap(map) { + if (typeof map !== 'object') return false + return ( + typeof map.mappings === 'string' || + typeof map._mappings === 'string' || + Array.isArray(map.sections) + ) + } + + loadAnnotation(css) { + let comments = css.match(/\/\*\s*# sourceMappingURL=/gm) + if (!comments) return + + // sourceMappingURLs from comments, strings, etc. + let start = css.lastIndexOf(comments.pop()) + let end = css.indexOf('*/', start) + + if (start > -1 && end > -1) { + // Locate the last sourceMappingURL to avoid pickin + this.annotation = this.getAnnotationURL(css.substring(start, end)) + } + } + + loadFile(path) { + this.root = dirname(path) + if (existsSync(path)) { + this.mapFile = path + return readFileSync(path, 'utf-8').toString().trim() + } + } + + loadMap(file, prev) { + if (prev === false) return false + + if (prev) { + if (typeof prev === 'string') { + return prev + } else if (typeof prev === 'function') { + let prevPath = prev(file) + if (prevPath) { + let map = this.loadFile(prevPath) + if (!map) { + throw new Error( + 'Unable to load previous source map: ' + prevPath.toString() + ) + } + return map + } + } else if (prev instanceof SourceMapConsumer) { + return SourceMapGenerator.fromSourceMap(prev).toString() + } else if (prev instanceof SourceMapGenerator) { + return prev.toString() + } else if (this.isMap(prev)) { + return JSON.stringify(prev) + } else { + throw new Error( + 'Unsupported previous source map format: ' + prev.toString() + ) + } + } else if (this.inline) { + return this.decodeInline(this.annotation) + } else if (this.annotation) { + let map = this.annotation + if (file) map = join(dirname(file), map) + return this.loadFile(map) + } + } + + startWith(string, start) { + if (!string) return false + return string.substr(0, start.length) === start + } + + withContent() { + return !!( + this.consumer().sourcesContent && + this.consumer().sourcesContent.length > 0 + ) + } +} + +module.exports = PreviousMap +PreviousMap.default = PreviousMap diff --git a/web/node_modules/postcss/lib/processor.d.ts b/web/node_modules/postcss/lib/processor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..50c9a07d3f502e22aaffb6df3bfd4f8f70e607e3 --- /dev/null +++ b/web/node_modules/postcss/lib/processor.d.ts @@ -0,0 +1,115 @@ +import Document from './document.js' +import LazyResult from './lazy-result.js' +import NoWorkResult from './no-work-result.js' +import { + AcceptedPlugin, + Plugin, + ProcessOptions, + TransformCallback, + Transformer +} from './postcss.js' +import Result from './result.js' +import Root from './root.js' + +declare namespace Processor { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Processor_ as default } +} + +/** + * Contains plugins to process CSS. Create one `Processor` instance, + * initialize its plugins, and then use that instance on numerous CSS files. + * + * ```js + * const processor = postcss([autoprefixer, postcssNested]) + * processor.process(css1).then(result => console.log(result.css)) + * processor.process(css2).then(result => console.log(result.css)) + * ``` + */ +declare class Processor_ { + /** + * Plugins added to this processor. + * + * ```js + * const processor = postcss([autoprefixer, postcssNested]) + * processor.plugins.length //=> 2 + * ``` + */ + plugins: (Plugin | TransformCallback | Transformer)[] + + /** + * Current PostCSS version. + * + * ```js + * if (result.processor.version.split('.')[0] !== '6') { + * throw new Error('This plugin works only with PostCSS 6') + * } + * ``` + */ + version: string + + /** + * @param plugins PostCSS plugins + */ + constructor(plugins?: AcceptedPlugin[]) + + /** + * Parses source CSS and returns a `LazyResult` Promise proxy. + * Because some plugins can be asynchronous it doesn’t make + * any transformations. Transformations will be applied + * in the `LazyResult` methods. + * + * ```js + * processor.process(css, { from: 'a.css', to: 'a.out.css' }) + * .then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param css String with input CSS or any object with a `toString()` method, + * like a Buffer. Optionally, send a `Result` instance + * and the processor will take the `Root` from it. + * @param opts Options. + * @return Promise proxy. + */ + process( + css: { toString(): string } | LazyResult | Result | Root | string + ): LazyResult | NoWorkResult + process( + css: { toString(): string } | LazyResult | Result | Root | string, + options: ProcessOptions + ): LazyResult + + /** + * Adds a plugin to be used as a CSS processor. + * + * PostCSS plugin can be in 4 formats: + * * A plugin in `Plugin` format. + * * A plugin creator function with `pluginCreator.postcss = true`. + * PostCSS will call this function without argument to get plugin. + * * A function. PostCSS will pass the function a {@link Root} + * as the first argument and current `Result` instance + * as the second. + * * Another `Processor` instance. PostCSS will copy plugins + * from that instance into this one. + * + * Plugins can also be added by passing them as arguments when creating + * a `postcss` instance (see [`postcss(plugins)`]). + * + * Asynchronous plugins should return a `Promise` instance. + * + * ```js + * const processor = postcss() + * .use(autoprefixer) + * .use(postcssNested) + * ``` + * + * @param plugin PostCSS plugin or `Processor` with plugins. + * @return Current processor to make methods chain. + */ + use(plugin: AcceptedPlugin): this +} + +declare class Processor extends Processor_ {} + +export = Processor diff --git a/web/node_modules/postcss/lib/processor.js b/web/node_modules/postcss/lib/processor.js new file mode 100644 index 0000000000000000000000000000000000000000..b9e587cdc86202f3627b65c51079b2cb7f60ad5c --- /dev/null +++ b/web/node_modules/postcss/lib/processor.js @@ -0,0 +1,67 @@ +'use strict' + +let NoWorkResult = require('./no-work-result') +let LazyResult = require('./lazy-result') +let Document = require('./document') +let Root = require('./root') + +class Processor { + constructor(plugins = []) { + this.version = '8.4.35' + this.plugins = this.normalize(plugins) + } + + normalize(plugins) { + let normalized = [] + for (let i of plugins) { + if (i.postcss === true) { + i = i() + } else if (i.postcss) { + i = i.postcss + } + + if (typeof i === 'object' && Array.isArray(i.plugins)) { + normalized = normalized.concat(i.plugins) + } else if (typeof i === 'object' && i.postcssPlugin) { + normalized.push(i) + } else if (typeof i === 'function') { + normalized.push(i) + } else if (typeof i === 'object' && (i.parse || i.stringify)) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + + 'one of the syntax/parser/stringifier options as outlined ' + + 'in your PostCSS runner documentation.' + ) + } + } else { + throw new Error(i + ' is not a PostCSS plugin') + } + } + return normalized + } + + process(css, opts = {}) { + if ( + !this.plugins.length && + !opts.parser && + !opts.stringifier && + !opts.syntax + ) { + return new NoWorkResult(this, css, opts) + } else { + return new LazyResult(this, css, opts) + } + } + + use(plugin) { + this.plugins = this.plugins.concat(this.normalize([plugin])) + return this + } +} + +module.exports = Processor +Processor.default = Processor + +Root.registerProcessor(Processor) +Document.registerProcessor(Processor) diff --git a/web/node_modules/postcss/lib/result.d.ts b/web/node_modules/postcss/lib/result.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3dcbdab132f245ebf8f88c83d39554302ae1d5a --- /dev/null +++ b/web/node_modules/postcss/lib/result.d.ts @@ -0,0 +1,206 @@ +import { + Document, + Node, + Plugin, + ProcessOptions, + Root, + SourceMap, + TransformCallback, + Warning, + WarningOptions +} from './postcss.js' +import Processor from './processor.js' + +declare namespace Result { + export interface Message { + [others: string]: any + + /** + * Source PostCSS plugin name. + */ + plugin?: string + + /** + * Message type. + */ + type: string + } + + export interface ResultOptions extends ProcessOptions { + /** + * The CSS node that was the source of the warning. + */ + node?: Node + + /** + * Name of plugin that created this warning. `Result#warn` will fill it + * automatically with `Plugin#postcssPlugin` value. + */ + plugin?: string + } + + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Result_ as default } +} + +/** + * Provides the result of the PostCSS transformations. + * + * A Result instance is returned by `LazyResult#then` + * or `Root#toResult` methods. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }) + * ``` + * + * ```js + * const result2 = postcss.parse(css).toResult() + * ``` + */ +declare class Result_ { + /** + * A CSS string representing of `Result#root`. + * + * ```js + * postcss.parse('a{}').toResult().css //=> "a{}" + * ``` + */ + css: string + + /** + * Last runned PostCSS plugin. + */ + lastPlugin: Plugin | TransformCallback + + /** + * An instance of `SourceMapGenerator` class from the `source-map` library, + * representing changes to the `Result#root` instance. + * + * ```js + * result.map.toJSON() //=> { version: 3, file: 'a.css', … } + * ``` + * + * ```js + * if (result.map) { + * fs.writeFileSync(result.opts.to + '.map', result.map.toString()) + * } + * ``` + */ + map: SourceMap + + /** + * Contains messages from plugins (e.g., warnings or custom messages). + * Each message should have type and plugin properties. + * + * ```js + * AtRule: { + * import: (atRule, { result }) { + * const importedFile = parseImport(atRule) + * result.messages.push({ + * type: 'dependency', + * plugin: 'postcss-import', + * file: importedFile, + * parent: result.opts.from + * }) + * } + * } + * ``` + */ + messages: Result.Message[] + + /** + * Options from the `Processor#process` or `Root#toResult` call + * that produced this Result instance.] + * + * ```js + * root.toResult(opts).opts === opts + * ``` + */ + opts: Result.ResultOptions + + /** + * The Processor instance used for this transformation. + * + * ```js + * for (const plugin of result.processor.plugins) { + * if (plugin.postcssPlugin === 'postcss-bad') { + * throw 'postcss-good is incompatible with postcss-bad' + * } + * }) + * ``` + */ + processor: Processor + + /** + * Root node after all transformations. + * + * ```js + * root.toResult().root === root + * ``` + */ + root: RootNode + + /** + * @param processor Processor used for this transformation. + * @param root Root node after all transformations. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, root: RootNode, opts: Result.ResultOptions) + + /** + * Returns for `Result#css` content. + * + * ```js + * result + '' === result.css + * ``` + * + * @return String representing of `Result#root`. + */ + toString(): string + + /** + * Creates an instance of `Warning` and adds it to `Result#messages`. + * + * ```js + * if (decl.important) { + * result.warn('Avoid !important', { node: decl, word: '!important' }) + * } + * ``` + * + * @param text Warning message. + * @param opts Warning options. + * @return Created warning. + */ + warn(message: string, options?: WarningOptions): Warning + + /** + * Returns warnings from plugins. Filters `Warning` instances + * from `Result#messages`. + * + * ```js + * result.warnings().forEach(warn => { + * console.warn(warn.toString()) + * }) + * ``` + * + * @return Warnings from plugins. + */ + warnings(): Warning[] + + /** + * An alias for the `Result#css` property. + * Use it with syntaxes that generate non-CSS output. + * + * ```js + * result.css === result.content + * ``` + */ + get content(): string +} + +declare class Result extends Result_ {} + +export = Result diff --git a/web/node_modules/postcss/lib/result.js b/web/node_modules/postcss/lib/result.js new file mode 100644 index 0000000000000000000000000000000000000000..a39751de0989ac55ee54b0733a3acc75f59819f1 --- /dev/null +++ b/web/node_modules/postcss/lib/result.js @@ -0,0 +1,42 @@ +'use strict' + +let Warning = require('./warning') + +class Result { + constructor(processor, root, opts) { + this.processor = processor + this.messages = [] + this.root = root + this.opts = opts + this.css = undefined + this.map = undefined + } + + toString() { + return this.css + } + + warn(text, opts = {}) { + if (!opts.plugin) { + if (this.lastPlugin && this.lastPlugin.postcssPlugin) { + opts.plugin = this.lastPlugin.postcssPlugin + } + } + + let warning = new Warning(text, opts) + this.messages.push(warning) + + return warning + } + + warnings() { + return this.messages.filter(i => i.type === 'warning') + } + + get content() { + return this.css + } +} + +module.exports = Result +Result.default = Result diff --git a/web/node_modules/postcss/lib/root.d.ts b/web/node_modules/postcss/lib/root.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9046aacdf146dbb380feef3719319b0daf45656f --- /dev/null +++ b/web/node_modules/postcss/lib/root.d.ts @@ -0,0 +1,87 @@ +import Container, { ContainerProps } from './container.js' +import Document from './document.js' +import { ProcessOptions } from './postcss.js' +import Result from './result.js' + +declare namespace Root { + export interface RootRaws extends Record { + /** + * The space symbols after the last child to the end of file. + */ + after?: string + + /** + * Non-CSS code after `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeAfter?: string + + /** + * Non-CSS code before `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeBefore?: string + + /** + * Is the last child has an (optional) semicolon. + */ + semicolon?: boolean + } + + export interface RootProps extends ContainerProps { + /** + * Information used to generate byte-to-byte equal node string + * as it was in the origin input. + * */ + raws?: RootRaws + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Root_ as default } +} + +/** + * Represents a CSS file and contains all its parsed nodes. + * + * ```js + * const root = postcss.parse('a{color:black} b{z-index:2}') + * root.type //=> 'root' + * root.nodes.length //=> 2 + * ``` + */ +declare class Root_ extends Container { + nodes: NonNullable + parent: Document | undefined + raws: Root.RootRaws + type: 'root' + + constructor(defaults?: Root.RootProps) + + assign(overrides: object | Root.RootProps): this + clone(overrides?: Partial): Root + cloneAfter(overrides?: Partial): Root + cloneBefore(overrides?: Partial): Root + + /** + * Returns a `Result` instance representing the root’s CSS. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * root1.append(root2) + * const result = root1.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current root’s CSS. + */ + toResult(options?: ProcessOptions): Result +} + +declare class Root extends Root_ {} + +export = Root diff --git a/web/node_modules/postcss/lib/root.js b/web/node_modules/postcss/lib/root.js new file mode 100644 index 0000000000000000000000000000000000000000..ea574edca70c45641753c6392fcd675971788cf7 --- /dev/null +++ b/web/node_modules/postcss/lib/root.js @@ -0,0 +1,61 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Root extends Container { + constructor(defaults) { + super(defaults) + this.type = 'root' + if (!this.nodes) this.nodes = [] + } + + normalize(child, sample, type) { + let nodes = super.normalize(child) + + if (sample) { + if (type === 'prepend') { + if (this.nodes.length > 1) { + sample.raws.before = this.nodes[1].raws.before + } else { + delete sample.raws.before + } + } else if (this.first !== sample) { + for (let node of nodes) { + node.raws.before = sample.raws.before + } + } + } + + return nodes + } + + removeChild(child, ignore) { + let index = this.index(child) + + if (!ignore && index === 0 && this.nodes.length > 1) { + this.nodes[1].raws.before = this.nodes[index].raws.before + } + + return super.removeChild(child) + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + return lazy.stringify() + } +} + +Root.registerLazyResult = dependant => { + LazyResult = dependant +} + +Root.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Root +Root.default = Root + +Container.registerRoot(Root) diff --git a/web/node_modules/postcss/lib/rule.d.ts b/web/node_modules/postcss/lib/rule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc5dd721a89815208542061d8fb1737ef5481b80 --- /dev/null +++ b/web/node_modules/postcss/lib/rule.d.ts @@ -0,0 +1,117 @@ +import Container, { + ContainerProps, + ContainerWithChildren +} from './container.js' + +declare namespace Rule { + export interface RuleRaws extends Record { + /** + * The space symbols after the last child of the node to the end of the node. + */ + after?: string + + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The symbols between the selector and `{` for rules. + */ + between?: string + + /** + * Contains `true` if there is semicolon after rule. + */ + ownSemicolon?: string + + /** + * The rule’s selector with comments. + */ + selector?: { + raw: string + value: string + } + + /** + * Contains `true` if the last child has an (optional) semicolon. + */ + semicolon?: boolean + } + + export interface RuleProps extends ContainerProps { + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: RuleRaws + /** Selector or selectors of the rule. */ + selector?: string + /** Selectors of the rule represented as an array of strings. */ + selectors?: string[] + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Rule_ as default } +} + +/** + * Represents a CSS rule: a selector followed by a declaration block. + * + * ```js + * Once (root, { Rule }) { + * let a = new Rule({ selector: 'a' }) + * a.append(…) + * root.append(a) + * } + * ``` + * + * ```js + * const root = postcss.parse('a{}') + * const rule = root.first + * rule.type //=> 'rule' + * rule.toString() //=> 'a{}' + * ``` + */ +declare class Rule_ extends Container { + nodes: NonNullable + parent: ContainerWithChildren | undefined + raws: Rule.RuleRaws + /** + * The rule’s full selector represented as a string. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * rule.selector //=> 'a, b' + * ``` + */ + selector: string + + /** + * An array containing the rule’s individual selectors. + * Groups of selectors are split at commas. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * + * rule.selector //=> 'a, b' + * rule.selectors //=> ['a', 'b'] + * + * rule.selectors = ['a', 'strong'] + * rule.selector //=> 'a, strong' + * ``` + */ + selectors: string[] + + type: 'rule' + + constructor(defaults?: Rule.RuleProps) + assign(overrides: object | Rule.RuleProps): this + clone(overrides?: Partial): Rule + cloneAfter(overrides?: Partial): Rule + cloneBefore(overrides?: Partial): Rule +} + +declare class Rule extends Rule_ {} + +export = Rule diff --git a/web/node_modules/postcss/lib/rule.js b/web/node_modules/postcss/lib/rule.js new file mode 100644 index 0000000000000000000000000000000000000000..a93ab25bf0c13b250ebd9fd2916e562b16e97152 --- /dev/null +++ b/web/node_modules/postcss/lib/rule.js @@ -0,0 +1,27 @@ +'use strict' + +let Container = require('./container') +let list = require('./list') + +class Rule extends Container { + constructor(defaults) { + super(defaults) + this.type = 'rule' + if (!this.nodes) this.nodes = [] + } + + get selectors() { + return list.comma(this.selector) + } + + set selectors(values) { + let match = this.selector ? this.selector.match(/,\s*/) : null + let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen') + this.selector = values.join(sep) + } +} + +module.exports = Rule +Rule.default = Rule + +Container.registerRule(Rule) diff --git a/web/node_modules/postcss/lib/stringifier.d.ts b/web/node_modules/postcss/lib/stringifier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f707a6aa320afb5dcb3590497ea744c50a37daca --- /dev/null +++ b/web/node_modules/postcss/lib/stringifier.d.ts @@ -0,0 +1,46 @@ +import { + AnyNode, + AtRule, + Builder, + Comment, + Container, + Declaration, + Document, + Root, + Rule +} from './postcss.js' + +declare namespace Stringifier { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Stringifier_ as default } +} + +declare class Stringifier_ { + builder: Builder + constructor(builder: Builder) + atrule(node: AtRule, semicolon?: boolean): void + beforeAfter(node: AnyNode, detect: 'after' | 'before'): string + block(node: AnyNode, start: string): void + body(node: Container): void + comment(node: Comment): void + decl(node: Declaration, semicolon?: boolean): void + document(node: Document): void + raw(node: AnyNode, own: null | string, detect?: string): string + rawBeforeClose(root: Root): string | undefined + rawBeforeComment(root: Root, node: Comment): string | undefined + rawBeforeDecl(root: Root, node: Declaration): string | undefined + rawBeforeOpen(root: Root): string | undefined + rawBeforeRule(root: Root): string | undefined + rawColon(root: Root): string | undefined + rawEmptyBody(root: Root): string | undefined + rawIndent(root: Root): string | undefined + rawSemicolon(root: Root): boolean | undefined + rawValue(node: AnyNode, prop: string): string + root(node: Root): void + rule(node: Rule): void + stringify(node: AnyNode, semicolon?: boolean): void +} + +declare class Stringifier extends Stringifier_ {} + +export = Stringifier diff --git a/web/node_modules/postcss/lib/stringifier.js b/web/node_modules/postcss/lib/stringifier.js new file mode 100644 index 0000000000000000000000000000000000000000..e07ad12e7b37dccdb4d5e2a0280b814af6e62ba2 --- /dev/null +++ b/web/node_modules/postcss/lib/stringifier.js @@ -0,0 +1,353 @@ +'use strict' + +const DEFAULT_RAW = { + after: '\n', + beforeClose: '\n', + beforeComment: '\n', + beforeDecl: '\n', + beforeOpen: ' ', + beforeRule: '\n', + colon: ': ', + commentLeft: ' ', + commentRight: ' ', + emptyBody: '', + indent: ' ', + semicolon: false +} + +function capitalize(str) { + return str[0].toUpperCase() + str.slice(1) +} + +class Stringifier { + constructor(builder) { + this.builder = builder + } + + atrule(node, semicolon) { + let name = '@' + node.name + let params = node.params ? this.rawValue(node, 'params') : '' + + if (typeof node.raws.afterName !== 'undefined') { + name += node.raws.afterName + } else if (params) { + name += ' ' + } + + if (node.nodes) { + this.block(node, name + params) + } else { + let end = (node.raws.between || '') + (semicolon ? ';' : '') + this.builder(name + params + end, node) + } + } + + beforeAfter(node, detect) { + let value + if (node.type === 'decl') { + value = this.raw(node, null, 'beforeDecl') + } else if (node.type === 'comment') { + value = this.raw(node, null, 'beforeComment') + } else if (detect === 'before') { + value = this.raw(node, null, 'beforeRule') + } else { + value = this.raw(node, null, 'beforeClose') + } + + let buf = node.parent + let depth = 0 + while (buf && buf.type !== 'root') { + depth += 1 + buf = buf.parent + } + + if (value.includes('\n')) { + let indent = this.raw(node, null, 'indent') + if (indent.length) { + for (let step = 0; step < depth; step++) value += indent + } + } + + return value + } + + block(node, start) { + let between = this.raw(node, 'between', 'beforeOpen') + this.builder(start + between + '{', node, 'start') + + let after + if (node.nodes && node.nodes.length) { + this.body(node) + after = this.raw(node, 'after') + } else { + after = this.raw(node, 'after', 'emptyBody') + } + + if (after) this.builder(after) + this.builder('}', node, 'end') + } + + body(node) { + let last = node.nodes.length - 1 + while (last > 0) { + if (node.nodes[last].type !== 'comment') break + last -= 1 + } + + let semicolon = this.raw(node, 'semicolon') + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i] + let before = this.raw(child, 'before') + if (before) this.builder(before) + this.stringify(child, last !== i || semicolon) + } + } + + comment(node) { + let left = this.raw(node, 'left', 'commentLeft') + let right = this.raw(node, 'right', 'commentRight') + this.builder('/*' + left + node.text + right + '*/', node) + } + + decl(node, semicolon) { + let between = this.raw(node, 'between', 'colon') + let string = node.prop + between + this.rawValue(node, 'value') + + if (node.important) { + string += node.raws.important || ' !important' + } + + if (semicolon) string += ';' + this.builder(string, node) + } + + document(node) { + this.body(node) + } + + raw(node, own, detect) { + let value + if (!detect) detect = own + + // Already had + if (own) { + value = node.raws[own] + if (typeof value !== 'undefined') return value + } + + let parent = node.parent + + if (detect === 'before') { + // Hack for first rule in CSS + if (!parent || (parent.type === 'root' && parent.first === node)) { + return '' + } + + // `root` nodes in `document` should use only their own raws + if (parent && parent.type === 'document') { + return '' + } + } + + // Floating child without parent + if (!parent) return DEFAULT_RAW[detect] + + // Detect style by other nodes + let root = node.root() + if (!root.rawCache) root.rawCache = {} + if (typeof root.rawCache[detect] !== 'undefined') { + return root.rawCache[detect] + } + + if (detect === 'before' || detect === 'after') { + return this.beforeAfter(node, detect) + } else { + let method = 'raw' + capitalize(detect) + if (this[method]) { + value = this[method](root, node) + } else { + root.walk(i => { + value = i.raws[own] + if (typeof value !== 'undefined') return false + }) + } + } + + if (typeof value === 'undefined') value = DEFAULT_RAW[detect] + + root.rawCache[detect] = value + return value + } + + rawBeforeClose(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length > 0) { + if (typeof i.raws.after !== 'undefined') { + value = i.raws.after + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawBeforeComment(root, node) { + let value + root.walkComments(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeDecl') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeDecl(root, node) { + let value + root.walkDecls(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeRule') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeOpen(root) { + let value + root.walk(i => { + if (i.type !== 'decl') { + value = i.raws.between + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawBeforeRule(root) { + let value + root.walk(i => { + if (i.nodes && (i.parent !== root || root.first !== i)) { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawColon(root) { + let value + root.walkDecls(i => { + if (typeof i.raws.between !== 'undefined') { + value = i.raws.between.replace(/[^\s:]/g, '') + return false + } + }) + return value + } + + rawEmptyBody(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length === 0) { + value = i.raws.after + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawIndent(root) { + if (root.raws.indent) return root.raws.indent + let value + root.walk(i => { + let p = i.parent + if (p && p !== root && p.parent && p.parent === root) { + if (typeof i.raws.before !== 'undefined') { + let parts = i.raws.before.split('\n') + value = parts[parts.length - 1] + value = value.replace(/\S/g, '') + return false + } + } + }) + return value + } + + rawSemicolon(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length && i.last.type === 'decl') { + value = i.raws.semicolon + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawValue(node, prop) { + let value = node[prop] + let raw = node.raws[prop] + if (raw && raw.value === value) { + return raw.raw + } + + return value + } + + root(node) { + this.body(node) + if (node.raws.after) this.builder(node.raws.after) + } + + rule(node) { + this.block(node, this.rawValue(node, 'selector')) + if (node.raws.ownSemicolon) { + this.builder(node.raws.ownSemicolon, node, 'end') + } + } + + stringify(node, semicolon) { + /* c8 ignore start */ + if (!this[node.type]) { + throw new Error( + 'Unknown AST node type ' + + node.type + + '. ' + + 'Maybe you need to change PostCSS stringifier.' + ) + } + /* c8 ignore stop */ + this[node.type](node, semicolon) + } +} + +module.exports = Stringifier +Stringifier.default = Stringifier diff --git a/web/node_modules/postcss/lib/stringify.d.ts b/web/node_modules/postcss/lib/stringify.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06ad0b4de4b40de7caae2172f94a75dc7de3b5b1 --- /dev/null +++ b/web/node_modules/postcss/lib/stringify.d.ts @@ -0,0 +1,9 @@ +import { Stringifier } from './postcss.js' + +interface Stringify extends Stringifier { + default: Stringify +} + +declare const stringify: Stringify + +export = stringify diff --git a/web/node_modules/postcss/lib/stringify.js b/web/node_modules/postcss/lib/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..77bd0178bbc95d57719117bec456a086b5a142a0 --- /dev/null +++ b/web/node_modules/postcss/lib/stringify.js @@ -0,0 +1,11 @@ +'use strict' + +let Stringifier = require('./stringifier') + +function stringify(node, builder) { + let str = new Stringifier(builder) + str.stringify(node) +} + +module.exports = stringify +stringify.default = stringify diff --git a/web/node_modules/postcss/lib/symbols.js b/web/node_modules/postcss/lib/symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..a142c268d464bd4093653baea44ea7abb85e1496 --- /dev/null +++ b/web/node_modules/postcss/lib/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports.isClean = Symbol('isClean') + +module.exports.my = Symbol('my') diff --git a/web/node_modules/postcss/lib/terminal-highlight.js b/web/node_modules/postcss/lib/terminal-highlight.js new file mode 100644 index 0000000000000000000000000000000000000000..6196c9df19d6fc2c3bd0c3de7dc662dca5408048 --- /dev/null +++ b/web/node_modules/postcss/lib/terminal-highlight.js @@ -0,0 +1,70 @@ +'use strict' + +let pico = require('picocolors') + +let tokenizer = require('./tokenize') + +let Input + +function registerInput(dependant) { + Input = dependant +} + +const HIGHLIGHT_THEME = { + ';': pico.yellow, + ':': pico.yellow, + '(': pico.cyan, + ')': pico.cyan, + '[': pico.yellow, + ']': pico.yellow, + '{': pico.yellow, + '}': pico.yellow, + 'at-word': pico.cyan, + 'brackets': pico.cyan, + 'call': pico.cyan, + 'class': pico.yellow, + 'comment': pico.gray, + 'hash': pico.magenta, + 'string': pico.green +} + +function getTokenType([type, value], processor) { + if (type === 'word') { + if (value[0] === '.') { + return 'class' + } + if (value[0] === '#') { + return 'hash' + } + } + + if (!processor.endOfFile()) { + let next = processor.nextToken() + processor.back(next) + if (next[0] === 'brackets' || next[0] === '(') return 'call' + } + + return type +} + +function terminalHighlight(css) { + let processor = tokenizer(new Input(css), { ignoreErrors: true }) + let result = '' + while (!processor.endOfFile()) { + let token = processor.nextToken() + let color = HIGHLIGHT_THEME[getTokenType(token, processor)] + if (color) { + result += token[1] + .split(/\r?\n/) + .map(i => color(i)) + .join('\n') + } else { + result += token[1] + } + } + return result +} + +terminalHighlight.registerInput = registerInput + +module.exports = terminalHighlight diff --git a/web/node_modules/postcss/lib/tokenize.js b/web/node_modules/postcss/lib/tokenize.js new file mode 100644 index 0000000000000000000000000000000000000000..39a20a37d5c7abd3e343291c42684b2d5d3e944e --- /dev/null +++ b/web/node_modules/postcss/lib/tokenize.js @@ -0,0 +1,266 @@ +'use strict' + +const SINGLE_QUOTE = "'".charCodeAt(0) +const DOUBLE_QUOTE = '"'.charCodeAt(0) +const BACKSLASH = '\\'.charCodeAt(0) +const SLASH = '/'.charCodeAt(0) +const NEWLINE = '\n'.charCodeAt(0) +const SPACE = ' '.charCodeAt(0) +const FEED = '\f'.charCodeAt(0) +const TAB = '\t'.charCodeAt(0) +const CR = '\r'.charCodeAt(0) +const OPEN_SQUARE = '['.charCodeAt(0) +const CLOSE_SQUARE = ']'.charCodeAt(0) +const OPEN_PARENTHESES = '('.charCodeAt(0) +const CLOSE_PARENTHESES = ')'.charCodeAt(0) +const OPEN_CURLY = '{'.charCodeAt(0) +const CLOSE_CURLY = '}'.charCodeAt(0) +const SEMICOLON = ';'.charCodeAt(0) +const ASTERISK = '*'.charCodeAt(0) +const COLON = ':'.charCodeAt(0) +const AT = '@'.charCodeAt(0) + +const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g +const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g +const RE_BAD_BRACKET = /.[\r\n"'(/\\]/ +const RE_HEX_ESCAPE = /[\da-f]/i + +module.exports = function tokenizer(input, options = {}) { + let css = input.css.valueOf() + let ignore = options.ignoreErrors + + let code, next, quote, content, escape + let escaped, escapePos, prev, n, currentToken + + let length = css.length + let pos = 0 + let buffer = [] + let returned = [] + + function position() { + return pos + } + + function unclosed(what) { + throw input.error('Unclosed ' + what, pos) + } + + function endOfFile() { + return returned.length === 0 && pos >= length + } + + function nextToken(opts) { + if (returned.length) return returned.pop() + if (pos >= length) return + + let ignoreUnclosed = opts ? opts.ignoreUnclosed : false + + code = css.charCodeAt(pos) + + switch (code) { + case NEWLINE: + case SPACE: + case TAB: + case CR: + case FEED: { + next = pos + do { + next += 1 + code = css.charCodeAt(next) + } while ( + code === SPACE || + code === NEWLINE || + code === TAB || + code === CR || + code === FEED + ) + + currentToken = ['space', css.slice(pos, next)] + pos = next - 1 + break + } + + case OPEN_SQUARE: + case CLOSE_SQUARE: + case OPEN_CURLY: + case CLOSE_CURLY: + case COLON: + case SEMICOLON: + case CLOSE_PARENTHESES: { + let controlChar = String.fromCharCode(code) + currentToken = [controlChar, controlChar, pos] + break + } + + case OPEN_PARENTHESES: { + prev = buffer.length ? buffer.pop()[1] : '' + n = css.charCodeAt(pos + 1) + if ( + prev === 'url' && + n !== SINGLE_QUOTE && + n !== DOUBLE_QUOTE && + n !== SPACE && + n !== NEWLINE && + n !== TAB && + n !== FEED && + n !== CR + ) { + next = pos + do { + escaped = false + next = css.indexOf(')', next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + break + } else { + unclosed('bracket') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['brackets', css.slice(pos, next + 1), pos, next] + + pos = next + } else { + next = css.indexOf(')', pos + 1) + content = css.slice(pos, next + 1) + + if (next === -1 || RE_BAD_BRACKET.test(content)) { + currentToken = ['(', '(', pos] + } else { + currentToken = ['brackets', content, pos, next] + pos = next + } + } + + break + } + + case SINGLE_QUOTE: + case DOUBLE_QUOTE: { + quote = code === SINGLE_QUOTE ? "'" : '"' + next = pos + do { + escaped = false + next = css.indexOf(quote, next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + 1 + break + } else { + unclosed('string') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['string', css.slice(pos, next + 1), pos, next] + pos = next + break + } + + case AT: { + RE_AT_END.lastIndex = pos + 1 + RE_AT_END.test(css) + if (RE_AT_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_AT_END.lastIndex - 2 + } + + currentToken = ['at-word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + case BACKSLASH: { + next = pos + escape = true + while (css.charCodeAt(next + 1) === BACKSLASH) { + next += 1 + escape = !escape + } + code = css.charCodeAt(next + 1) + if ( + escape && + code !== SLASH && + code !== SPACE && + code !== NEWLINE && + code !== TAB && + code !== CR && + code !== FEED + ) { + next += 1 + if (RE_HEX_ESCAPE.test(css.charAt(next))) { + while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { + next += 1 + } + if (css.charCodeAt(next + 1) === SPACE) { + next += 1 + } + } + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + default: { + if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { + next = css.indexOf('*/', pos + 2) + 1 + if (next === 0) { + if (ignore || ignoreUnclosed) { + next = css.length + } else { + unclosed('comment') + } + } + + currentToken = ['comment', css.slice(pos, next + 1), pos, next] + pos = next + } else { + RE_WORD_END.lastIndex = pos + 1 + RE_WORD_END.test(css) + if (RE_WORD_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_WORD_END.lastIndex - 2 + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + buffer.push(currentToken) + pos = next + } + + break + } + } + + pos++ + return currentToken + } + + function back(token) { + returned.push(token) + } + + return { + back, + endOfFile, + nextToken, + position + } +} diff --git a/web/node_modules/postcss/lib/warn-once.js b/web/node_modules/postcss/lib/warn-once.js new file mode 100644 index 0000000000000000000000000000000000000000..316e1cf462f076c803b4f5e023c4d81bdba308b9 --- /dev/null +++ b/web/node_modules/postcss/lib/warn-once.js @@ -0,0 +1,13 @@ +/* eslint-disable no-console */ +'use strict' + +let printed = {} + +module.exports = function warnOnce(message) { + if (printed[message]) return + printed[message] = true + + if (typeof console !== 'undefined' && console.warn) { + console.warn(message) + } +} diff --git a/web/node_modules/postcss/lib/warning.d.ts b/web/node_modules/postcss/lib/warning.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b25bba81603e800598a65f70447f35a17b0b9d00 --- /dev/null +++ b/web/node_modules/postcss/lib/warning.d.ts @@ -0,0 +1,147 @@ +import { RangePosition } from './css-syntax-error.js' +import Node from './node.js' + +declare namespace Warning { + export interface WarningOptions { + /** + * End position, exclusive, in CSS node string that caused the warning. + */ + end?: RangePosition + + /** + * End index, exclusive, in CSS node string that caused the warning. + */ + endIndex?: number + + /** + * Start index, inclusive, in CSS node string that caused the warning. + */ + index?: number + + /** + * CSS node that caused the warning. + */ + node?: Node + + /** + * Name of the plugin that created this warning. `Result#warn` fills + * this property automatically. + */ + plugin?: string + + /** + * Start position, inclusive, in CSS node string that caused the warning. + */ + start?: RangePosition + + /** + * Word in CSS source that caused the warning. + */ + word?: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Warning_ as default } +} + +/** + * Represents a plugin’s warning. It can be created using `Node#warn`. + * + * ```js + * if (decl.important) { + * decl.warn(result, 'Avoid !important', { word: '!important' }) + * } + * ``` + */ +declare class Warning_ { + /** + * Column for inclusive start position in the input file with this warning’s source. + * + * ```js + * warning.column //=> 6 + * ``` + */ + column: number + + /** + * Column for exclusive end position in the input file with this warning’s source. + * + * ```js + * warning.endColumn //=> 4 + * ``` + */ + endColumn?: number + + /** + * Line for exclusive end position in the input file with this warning’s source. + * + * ```js + * warning.endLine //=> 6 + * ``` + */ + endLine?: number + + /** + * Line for inclusive start position in the input file with this warning’s source. + * + * ```js + * warning.line //=> 5 + * ``` + */ + line: number + + /** + * Contains the CSS node that caused the warning. + * + * ```js + * warning.node.toString() //=> 'color: white !important' + * ``` + */ + node: Node + + /** + * The name of the plugin that created this warning. + * When you call `Node#warn` it will fill this property automatically. + * + * ```js + * warning.plugin //=> 'postcss-important' + * ``` + */ + plugin: string + + /** + * The warning message. + * + * ```js + * warning.text //=> 'Try to avoid !important' + * ``` + */ + text: string + + /** + * Type to filter warnings from `Result#messages`. + * Always equal to `"warning"`. + */ + type: 'warning' + + /** + * @param text Warning message. + * @param opts Warning options. + */ + constructor(text: string, opts?: Warning.WarningOptions) + + /** + * Returns a warning position and message. + * + * ```js + * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important' + * ``` + * + * @return Warning position and message. + */ + toString(): string +} + +declare class Warning extends Warning_ {} + +export = Warning diff --git a/web/node_modules/postcss/lib/warning.js b/web/node_modules/postcss/lib/warning.js new file mode 100644 index 0000000000000000000000000000000000000000..3a3d79c938026c5559f0f5538b6ab0d47d1e7a27 --- /dev/null +++ b/web/node_modules/postcss/lib/warning.js @@ -0,0 +1,37 @@ +'use strict' + +class Warning { + constructor(text, opts = {}) { + this.type = 'warning' + this.text = text + + if (opts.node && opts.node.source) { + let range = opts.node.rangeBy(opts) + this.line = range.start.line + this.column = range.start.column + this.endLine = range.end.line + this.endColumn = range.end.column + } + + for (let opt in opts) this[opt] = opts[opt] + } + + toString() { + if (this.node) { + return this.node.error(this.text, { + index: this.index, + plugin: this.plugin, + word: this.word + }).message + } + + if (this.plugin) { + return this.plugin + ': ' + this.text + } + + return this.text + } +} + +module.exports = Warning +Warning.default = Warning diff --git a/web/node_modules/postcss/package.json b/web/node_modules/postcss/package.json new file mode 100644 index 0000000000000000000000000000000000000000..68e1036d41b8587aea3285e8d22570a6004555aa --- /dev/null +++ b/web/node_modules/postcss/package.json @@ -0,0 +1,88 @@ +{ + "name": "postcss", + "version": "8.4.35", + "description": "Tool for transforming styles with JS plugins", + "engines": { + "node": "^10 || ^12 || >=14" + }, + "exports": { + ".": { + "require": "./lib/postcss.js", + "import": "./lib/postcss.mjs" + }, + "./lib/at-rule": "./lib/at-rule.js", + "./lib/comment": "./lib/comment.js", + "./lib/container": "./lib/container.js", + "./lib/css-syntax-error": "./lib/css-syntax-error.js", + "./lib/declaration": "./lib/declaration.js", + "./lib/fromJSON": "./lib/fromJSON.js", + "./lib/input": "./lib/input.js", + "./lib/lazy-result": "./lib/lazy-result.js", + "./lib/no-work-result": "./lib/no-work-result.js", + "./lib/list": "./lib/list.js", + "./lib/map-generator": "./lib/map-generator.js", + "./lib/node": "./lib/node.js", + "./lib/parse": "./lib/parse.js", + "./lib/parser": "./lib/parser.js", + "./lib/postcss": "./lib/postcss.js", + "./lib/previous-map": "./lib/previous-map.js", + "./lib/processor": "./lib/processor.js", + "./lib/result": "./lib/result.js", + "./lib/root": "./lib/root.js", + "./lib/rule": "./lib/rule.js", + "./lib/stringifier": "./lib/stringifier.js", + "./lib/stringify": "./lib/stringify.js", + "./lib/symbols": "./lib/symbols.js", + "./lib/terminal-highlight": "./lib/terminal-highlight.js", + "./lib/tokenize": "./lib/tokenize.js", + "./lib/warn-once": "./lib/warn-once.js", + "./lib/warning": "./lib/warning.js", + "./package.json": "./package.json" + }, + "main": "./lib/postcss.js", + "types": "./lib/postcss.d.ts", + "keywords": [ + "css", + "postcss", + "rework", + "preprocessor", + "parser", + "source map", + "transform", + "manipulation", + "transpiler" + ], + "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" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "homepage": "https://postcss.org/", + "repository": "postcss/postcss", + "bugs": { + "url": "https://github.com/postcss/postcss/issues" + }, + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "browser": { + "./lib/terminal-highlight": false, + "source-map-js": false, + "path": false, + "url": false, + "fs": false + } +} diff --git a/web/node_modules/pretty-format/LICENSE b/web/node_modules/pretty-format/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b93be90515ccd0b9daedaa589e42bf5929693f1f --- /dev/null +++ b/web/node_modules/pretty-format/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +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/web/node_modules/pretty-format/README.md b/web/node_modules/pretty-format/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0cc1bcff0f502571db7162dc42865e318281f797 --- /dev/null +++ b/web/node_modules/pretty-format/README.md @@ -0,0 +1,463 @@ +# pretty-format + +Stringify any JavaScript value. + +- Serialize built-in JavaScript types. +- Serialize application-specific data types with built-in or user-defined plugins. + +## Installation + +```sh +$ yarn add pretty-format +``` + +## Usage + +```js +const {format: prettyFormat} = require('pretty-format'); // CommonJS +``` + +```js +import {format as prettyFormat} from 'pretty-format'; // ES2015 modules +``` + +```js +const val = {object: {}}; +val.circularReference = val; +val[Symbol('foo')] = 'foo'; +val.map = new Map([['prop', 'value']]); +val.array = [-0, Infinity, NaN]; + +console.log(prettyFormat(val)); +/* +Object { + "array": Array [ + -0, + Infinity, + NaN, + ], + "circularReference": [Circular], + "map": Map { + "prop" => "value", + }, + "object": Object {}, + Symbol(foo): "foo", +} +*/ +``` + +## Usage with options + +```js +function onClick() {} + +console.log(prettyFormat(onClick)); +/* +[Function onClick] +*/ + +const options = { + printFunctionName: false, +}; +console.log(prettyFormat(onClick, options)); +/* +[Function] +*/ +``` + + +| key | type | default | description | +| :-------------------- | :--------------- | :---------- | :-------------------------------------------------------------------------------------- | +| `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects | +| `compareKeys` | `function\|null` | `undefined` | compare function used when sorting object keys, `null` can be used to skip over sorting | +| `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions | +| `escapeString` | `boolean` | `true` | escape special characters in strings | +| `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) | +| `indent` | `number` | `2` | spaces in each level of indentation | +| `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on | +| `maxWidth` | `number` | `Infinity` | number of elements to print in arrays, sets, and so on | +| `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks | +| `plugins` | `array` | `[]` | plugins to serialize application-specific data types | +| `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays | +| `printFunctionName` | `boolean` | `true` | include or omit the name of a function | +| `theme` | `object` | | colors to highlight syntax in terminal | + +Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors) + +```js +const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green', +}; +``` + +## Usage with plugins + +The `pretty-format` package provides some built-in plugins, including: + +- `ReactElement` for elements from `react` +- `ReactTestComponent` for test objects from `react-test-renderer` + +```js +// CommonJS +const React = require('react'); +const renderer = require('react-test-renderer'); +const {format: prettyFormat, plugins} = require('pretty-format'); + +const {ReactElement, ReactTestComponent} = plugins; +``` + +```js +// ES2015 modules and destructuring assignment +import React from 'react'; +import renderer from 'react-test-renderer'; +import {plugins, format as prettyFormat} from 'pretty-format'; + +const {ReactElement, ReactTestComponent} = plugins; +``` + +```js +const onClick = () => {}; +const element = React.createElement('button', {onClick}, 'Hello World'); + +const formatted1 = prettyFormat(element, { + plugins: [ReactElement], + printFunctionName: false, +}); +const formatted2 = prettyFormat(renderer.create(element).toJSON(), { + plugins: [ReactTestComponent], + printFunctionName: false, +}); +/* + +*/ +``` + +## Usage in Jest + +For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**. + +To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then: + +In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration. + +```js +import serializer from 'my-serializer-module'; +expect.addSnapshotSerializer(serializer); + +// tests which have `expect(value).toMatchSnapshot()` assertions +``` + +For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file: + +```json +{ + "jest": { + "snapshotSerializers": ["my-serializer-module"] + } +} +``` + +## Writing plugins + +A plugin is a JavaScript object. + +If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either: + +- `serialize(val, …)` method of the **improved** interface (available in **version 21** or later) +- `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method) + +### test + +Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors: + +- `TypeError: Cannot read property 'whatever' of null` +- `TypeError: Cannot read property 'whatever' of undefined` + +For example, `test` method of built-in `ReactElement` plugin: + +```js +const elementSymbol = Symbol.for('react.element'); +const test = val => val && val.$$typeof === elementSymbol; +``` + +Pay attention to efficiency in `test` because `pretty-format` calls it often. + +### serialize + +The **improved** interface is available in **version 21** or later. + +Write `serialize` to return a string, given the arguments: + +- `val` which “passed the test” +- unchanging `config` object: derived from `options` +- current `indentation` string: concatenate to `indent` from `config` +- current `depth` number: compare to `maxDepth` from `config` +- current `refs` array: find circular references in objects +- `printer` callback function: serialize children + +### config + + +| key | type | description | +| :------------------ | :--------------- | :-------------------------------------------------------------------------------------- | +| `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects | +| `compareKeys` | `function\|null` | compare function used when sorting object keys, `null` can be used to skip over sorting | +| `colors` | `Object` | escape codes for colors to highlight syntax | +| `escapeRegex` | `boolean` | escape special characters in regular expressions | +| `escapeString` | `boolean` | escape special characters in strings | +| `indent` | `string` | spaces in each level of indentation | +| `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on | +| `min` | `boolean` | minimize added space: no indentation nor line breaks | +| `plugins` | `array` | plugins to serialize application-specific data types | +| `printFunctionName` | `boolean` | include or omit the name of a function | +| `spacingInner` | `string` | spacing to separate items in a list | +| `spacingOuter` | `string` | spacing to enclose a list of items | + +Each property of `colors` in `config` corresponds to a property of `theme` in `options`: + +- the key is the same (for example, `tag`) +- the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) + +Some properties in `config` are derived from `min` in `options`: + +- `spacingInner` and `spacingOuter` are **newline** if `min` is `false` +- `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true` + +### Example of serialize and test + +This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays. + +```js +// We reused more code when we factored out a function for child items +// that is independent of depth, name, and enclosing punctuation (see below). +const SEPARATOR = ','; +function serializeItems(items, config, indentation, depth, refs, printer) { + if (items.length === 0) { + return ''; + } + const indentationItems = indentation + config.indent; + return ( + config.spacingOuter + + items + .map( + item => + indentationItems + + printer(item, config, indentationItems, depth, refs), // callback + ) + .join(SEPARATOR + config.spacingInner) + + (config.min ? '' : SEPARATOR) + // following the last item + config.spacingOuter + + indentation + ); +} + +const plugin = { + test(val) { + return Array.isArray(val); + }, + serialize(array, config, indentation, depth, refs, printer) { + const name = array.constructor.name; + return ++depth > config.maxDepth + ? `[${name}]` + : `${config.min ? '' : `${name} `}[${serializeItems( + array, + config, + indentation, + depth, + refs, + printer, + )}]`; + }, +}; +``` + +```js +const val = { + filter: 'completed', + items: [ + { + text: 'Write test', + completed: true, + }, + { + text: 'Write serialize', + completed: true, + }, + ], +}; +``` + +```js +console.log( + prettyFormat(val, { + plugins: [plugin], + }), +); +/* +Object { + "filter": "completed", + "items": Array [ + Object { + "completed": true, + "text": "Write test", + }, + Object { + "completed": true, + "text": "Write serialize", + }, + ], +} +*/ +``` + +```js +console.log( + prettyFormat(val, { + indent: 4, + plugins: [plugin], + }), +); +/* +Object { + "filter": "completed", + "items": Array [ + Object { + "completed": true, + "text": "Write test", + }, + Object { + "completed": true, + "text": "Write serialize", + }, + ], +} +*/ +``` + +```js +console.log( + prettyFormat(val, { + maxDepth: 1, + plugins: [plugin], + }), +); +/* +Object { + "filter": "completed", + "items": [Array], +} +*/ +``` + +```js +console.log( + prettyFormat(val, { + min: true, + plugins: [plugin], + }), +); +/* +{"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]} +*/ +``` + +### print + +The **original** interface is adequate for plugins: + +- that **do not** depend on options other than `highlight` or `min` +- that **do not** depend on `depth` or `refs` in recursive traversal, and +- if values either + - do **not** require indentation, or + - do **not** occur as children of JavaScript data structures (for example, array) + +Write `print` to return a string, given the arguments: + +- `val` which “passed the test” +- current `printer(valChild)` callback function: serialize children +- current `indenter(lines)` callback function: indent lines at the next level +- unchanging `config` object: derived from `options` +- unchanging `colors` object: derived from `options` + +The 3 properties of `config` are `min` in `options` and: + +- `spacing` and `edgeSpacing` are **newline** if `min` is `false` +- `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true` + +Each property of `colors` corresponds to a property of `theme` in `options`: + +- the key is the same (for example, `tag`) +- the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) + +### Example of print and test + +This plugin prints functions with the **number of named arguments** excluding rest argument. + +```js +const plugin = { + print(val) { + return `[Function ${val.name || 'anonymous'} ${val.length}]`; + }, + test(val) { + return typeof val === 'function'; + }, +}; +``` + +```js +const val = { + onClick(event) {}, + render() {}, +}; + +prettyFormat(val, { + plugins: [plugin], +}); +/* +Object { + "onClick": [Function onClick 1], + "render": [Function render 0], +} +*/ + +prettyFormat(val); +/* +Object { + "onClick": [Function onClick], + "render": [Function render], +} +*/ +``` + +This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above. + +```js +prettyFormat(val, { + plugins: [pluginOld], + printFunctionName: false, +}); +/* +Object { + "onClick": [Function onClick 1], + "render": [Function render 0], +} +*/ + +prettyFormat(val, { + printFunctionName: false, +}); +/* +Object { + "onClick": [Function], + "render": [Function], +} +*/ +``` diff --git a/web/node_modules/pretty-format/build/collections.js b/web/node_modules/pretty-format/build/collections.js new file mode 100644 index 0000000000000000000000000000000000000000..a8b846fe5ff7b4642d5cd5781d820f12b00c9daa --- /dev/null +++ b/web/node_modules/pretty-format/build/collections.js @@ -0,0 +1,180 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printIteratorEntries = printIteratorEntries; +exports.printIteratorValues = printIteratorValues; +exports.printListItems = printListItems; +exports.printObjectProperties = printObjectProperties; +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const getKeysOfEnumerableProperties = (object, compareKeys) => { + const rawKeys = Object.keys(object); + const keys = compareKeys !== null ? rawKeys.sort(compareKeys) : rawKeys; + if (Object.getOwnPropertySymbols) { + Object.getOwnPropertySymbols(object).forEach(symbol => { + if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { + keys.push(symbol); + } + }); + } + return keys; +}; + +/** + * Return entries (for example, of a map) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ +function printIteratorEntries( + iterator, + config, + indentation, + depth, + refs, + printer, + // Too bad, so sad that separator for ECMAScript Map has been ' => ' + // What a distracting diff if you change a data structure to/from + // ECMAScript Object or Immutable.Map/OrderedMap which use the default. + separator = ': ' +) { + let result = ''; + let width = 0; + let current = iterator.next(); + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + while (!current.done) { + result += indentationNext; + if (width++ === config.maxWidth) { + result += '…'; + break; + } + const name = printer( + current.value[0], + config, + indentationNext, + depth, + refs + ); + const value = printer( + current.value[1], + config, + indentationNext, + depth, + refs + ); + result += name + separator + value; + current = iterator.next(); + if (!current.done) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ','; + } + } + result += config.spacingOuter + indentation; + } + return result; +} + +/** + * Return values (for example, of a set) + * with spacing, indentation, and comma + * without surrounding punctuation (braces or brackets) + */ +function printIteratorValues( + iterator, + config, + indentation, + depth, + refs, + printer +) { + let result = ''; + let width = 0; + let current = iterator.next(); + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + while (!current.done) { + result += indentationNext; + if (width++ === config.maxWidth) { + result += '…'; + break; + } + result += printer(current.value, config, indentationNext, depth, refs); + current = iterator.next(); + if (!current.done) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ','; + } + } + result += config.spacingOuter + indentation; + } + return result; +} + +/** + * Return items (for example, of an array) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, brackets) + **/ +function printListItems(list, config, indentation, depth, refs, printer) { + let result = ''; + if (list.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + for (let i = 0; i < list.length; i++) { + result += indentationNext; + if (i === config.maxWidth) { + result += '…'; + break; + } + if (i in list) { + result += printer(list[i], config, indentationNext, depth, refs); + } + if (i < list.length - 1) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ','; + } + } + result += config.spacingOuter + indentation; + } + return result; +} + +/** + * Return properties of an object + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ +function printObjectProperties(val, config, indentation, depth, refs, printer) { + let result = ''; + const keys = getKeysOfEnumerableProperties(val, config.compareKeys); + if (keys.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const name = printer(key, config, indentationNext, depth, refs); + const value = printer(val[key], config, indentationNext, depth, refs); + result += `${indentationNext + name}: ${value}`; + if (i < keys.length - 1) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ','; + } + } + result += config.spacingOuter + indentation; + } + return result; +} diff --git a/web/node_modules/pretty-format/build/index.d.ts b/web/node_modules/pretty-format/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e99a5e1c1968be6864930dd03da1638df407fc0 --- /dev/null +++ b/web/node_modules/pretty-format/build/index.d.ts @@ -0,0 +1,163 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {SnapshotFormat} from '@jest/schemas'; + +export declare type Colors = { + comment: { + close: string; + open: string; + }; + content: { + close: string; + open: string; + }; + prop: { + close: string; + open: string; + }; + tag: { + close: string; + open: string; + }; + value: { + close: string; + open: string; + }; +}; + +export declare type CompareKeys = + | ((a: string, b: string) => number) + | null + | undefined; + +export declare type Config = { + callToJSON: boolean; + compareKeys: CompareKeys; + colors: Colors; + escapeRegex: boolean; + escapeString: boolean; + indent: string; + maxDepth: number; + maxWidth: number; + min: boolean; + plugins: Plugins; + printBasicPrototype: boolean; + printFunctionName: boolean; + spacingInner: string; + spacingOuter: string; +}; + +export declare const DEFAULT_OPTIONS: { + callToJSON: true; + compareKeys: undefined; + escapeRegex: false; + escapeString: true; + highlight: false; + indent: number; + maxDepth: number; + maxWidth: number; + min: false; + plugins: never[]; + printBasicPrototype: true; + printFunctionName: true; + theme: Required<{ + readonly comment?: string | undefined; + readonly content?: string | undefined; + readonly prop?: string | undefined; + readonly tag?: string | undefined; + readonly value?: string | undefined; + }>; +}; + +/** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ +declare function format(val: unknown, options?: OptionsReceived): string; +export default format; +export {format}; + +declare type Indent = (arg0: string) => string; + +export declare type NewPlugin = { + serialize: ( + val: any, + config: Config, + indentation: string, + depth: number, + refs: Refs, + printer: Printer, + ) => string; + test: Test; +}; + +export declare type OldPlugin = { + print: ( + val: unknown, + print: Print, + indent: Indent, + options: PluginOptions, + colors: Colors, + ) => string; + test: Test; +}; + +export declare interface Options + extends Omit { + compareKeys: CompareKeys; + theme: Required; +} + +export declare type OptionsReceived = PrettyFormatOptions; + +declare type Plugin_2 = NewPlugin | OldPlugin; +export {Plugin_2 as Plugin}; + +declare type PluginOptions = { + edgeSpacing: string; + min: boolean; + spacing: string; +}; + +export declare type Plugins = Array; + +export declare const plugins: { + AsymmetricMatcher: NewPlugin; + DOMCollection: NewPlugin; + DOMElement: NewPlugin; + Immutable: NewPlugin; + ReactElement: NewPlugin; + ReactTestComponent: NewPlugin; +}; + +export declare interface PrettyFormatOptions + extends Omit { + compareKeys?: CompareKeys; + plugins?: Plugins; +} + +declare type Print = (arg0: unknown) => string; + +export declare type Printer = ( + val: unknown, + config: Config, + indentation: string, + depth: number, + refs: Refs, + hasCalledToJSON?: boolean, +) => string; + +export declare type Refs = Array; + +declare type RequiredOptions = Required; + +declare type Test = (arg0: any) => boolean; + +export declare type Theme = Options['theme']; + +export {}; diff --git a/web/node_modules/pretty-format/build/index.js b/web/node_modules/pretty-format/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8d3a562949eda2bcfd41456aac6cf89d66b2e5b2 --- /dev/null +++ b/web/node_modules/pretty-format/build/index.js @@ -0,0 +1,478 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.DEFAULT_OPTIONS = void 0; +exports.format = format; +exports.plugins = void 0; +var _ansiStyles = _interopRequireDefault(require('ansi-styles')); +var _collections = require('./collections'); +var _AsymmetricMatcher = _interopRequireDefault( + require('./plugins/AsymmetricMatcher') +); +var _DOMCollection = _interopRequireDefault(require('./plugins/DOMCollection')); +var _DOMElement = _interopRequireDefault(require('./plugins/DOMElement')); +var _Immutable = _interopRequireDefault(require('./plugins/Immutable')); +var _ReactElement = _interopRequireDefault(require('./plugins/ReactElement')); +var _ReactTestComponent = _interopRequireDefault( + require('./plugins/ReactTestComponent') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ + +const toString = Object.prototype.toString; +const toISOString = Date.prototype.toISOString; +const errorToString = Error.prototype.toString; +const regExpToString = RegExp.prototype.toString; + +/** + * Explicitly comparing typeof constructor to function avoids undefined as name + * when mock identity-obj-proxy returns the key as the value for any key. + */ +const getConstructorName = val => + (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; + +/* global window */ +/** Is val is equal to global window object? Works even if it does not exist :) */ +const isWindow = val => typeof window !== 'undefined' && val === window; +const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; +const NEWLINE_REGEXP = /\n/gi; +class PrettyFormatPluginError extends Error { + constructor(message, stack) { + super(message); + this.stack = stack; + this.name = this.constructor.name; + } +} +function isToStringedArrayType(toStringed) { + return ( + toStringed === '[object Array]' || + toStringed === '[object ArrayBuffer]' || + toStringed === '[object DataView]' || + toStringed === '[object Float32Array]' || + toStringed === '[object Float64Array]' || + toStringed === '[object Int8Array]' || + toStringed === '[object Int16Array]' || + toStringed === '[object Int32Array]' || + toStringed === '[object Uint8Array]' || + toStringed === '[object Uint8ClampedArray]' || + toStringed === '[object Uint16Array]' || + toStringed === '[object Uint32Array]' + ); +} +function printNumber(val) { + return Object.is(val, -0) ? '-0' : String(val); +} +function printBigInt(val) { + return String(`${val}n`); +} +function printFunction(val, printFunctionName) { + if (!printFunctionName) { + return '[Function]'; + } + return `[Function ${val.name || 'anonymous'}]`; +} +function printSymbol(val) { + return String(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); +} +function printError(val) { + return `[${errorToString.call(val)}]`; +} + +/** + * The first port of call for printing an object, handles most of the + * data-types in JS. + */ +function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { + if (val === true || val === false) { + return `${val}`; + } + if (val === undefined) { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + const typeOf = typeof val; + if (typeOf === 'number') { + return printNumber(val); + } + if (typeOf === 'bigint') { + return printBigInt(val); + } + if (typeOf === 'string') { + if (escapeString) { + return `"${val.replace(/"|\\/g, '\\$&')}"`; + } + return `"${val}"`; + } + if (typeOf === 'function') { + return printFunction(val, printFunctionName); + } + if (typeOf === 'symbol') { + return printSymbol(val); + } + const toStringed = toString.call(val); + if (toStringed === '[object WeakMap]') { + return 'WeakMap {}'; + } + if (toStringed === '[object WeakSet]') { + return 'WeakSet {}'; + } + if ( + toStringed === '[object Function]' || + toStringed === '[object GeneratorFunction]' + ) { + return printFunction(val, printFunctionName); + } + if (toStringed === '[object Symbol]') { + return printSymbol(val); + } + if (toStringed === '[object Date]') { + return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); + } + if (toStringed === '[object Error]') { + return printError(val); + } + if (toStringed === '[object RegExp]') { + if (escapeRegex) { + // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js + return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + } + return regExpToString.call(val); + } + if (val instanceof Error) { + return printError(val); + } + return null; +} + +/** + * Handles more complex objects ( such as objects with circular references. + * maps and sets etc ) + */ +function printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON +) { + if (refs.indexOf(val) !== -1) { + return '[Circular]'; + } + refs = refs.slice(); + refs.push(val); + const hitMaxDepth = ++depth > config.maxDepth; + const min = config.min; + if ( + config.callToJSON && + !hitMaxDepth && + val.toJSON && + typeof val.toJSON === 'function' && + !hasCalledToJSON + ) { + return printer(val.toJSON(), config, indentation, depth, refs, true); + } + const toStringed = toString.call(val); + if (toStringed === '[object Arguments]') { + return hitMaxDepth + ? '[Arguments]' + : `${min ? '' : 'Arguments '}[${(0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + )}]`; + } + if (isToStringedArrayType(toStringed)) { + return hitMaxDepth + ? `[${val.constructor.name}]` + : `${ + min + ? '' + : !config.printBasicPrototype && val.constructor.name === 'Array' + ? '' + : `${val.constructor.name} ` + }[${(0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + )}]`; + } + if (toStringed === '[object Map]') { + return hitMaxDepth + ? '[Map]' + : `Map {${(0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer, + ' => ' + )}}`; + } + if (toStringed === '[object Set]') { + return hitMaxDepth + ? '[Set]' + : `Set {${(0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + )}}`; + } + + // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + return hitMaxDepth || isWindow(val) + ? `[${getConstructorName(val)}]` + : `${ + min + ? '' + : !config.printBasicPrototype && getConstructorName(val) === 'Object' + ? '' + : `${getConstructorName(val)} ` + }{${(0, _collections.printObjectProperties)( + val, + config, + indentation, + depth, + refs, + printer + )}}`; +} +function isNewPlugin(plugin) { + return plugin.serialize != null; +} +function printPlugin(plugin, val, config, indentation, depth, refs) { + let printed; + try { + printed = isNewPlugin(plugin) + ? plugin.serialize(val, config, indentation, depth, refs, printer) + : plugin.print( + val, + valChild => printer(valChild, config, indentation, depth, refs), + str => { + const indentationNext = indentation + config.indent; + return ( + indentationNext + + str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) + ); + }, + { + edgeSpacing: config.spacingOuter, + min: config.min, + spacing: config.spacingInner + }, + config.colors + ); + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + if (typeof printed !== 'string') { + throw new Error( + `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` + ); + } + return printed; +} +function findPlugin(plugins, val) { + for (let p = 0; p < plugins.length; p++) { + try { + if (plugins[p].test(val)) { + return plugins[p]; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + return null; +} +function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + const plugin = findPlugin(config.plugins, val); + if (plugin !== null) { + return printPlugin(plugin, val, config, indentation, depth, refs); + } + const basicResult = printBasicValue( + val, + config.printFunctionName, + config.escapeRegex, + config.escapeString + ); + if (basicResult !== null) { + return basicResult; + } + return printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ); +} +const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green' +}; +const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); + +// could be replaced by `satisfies` operator in the future: https://github.com/microsoft/TypeScript/issues/47920 +const toOptionsSubtype = options => options; +const DEFAULT_OPTIONS = toOptionsSubtype({ + callToJSON: true, + compareKeys: undefined, + escapeRegex: false, + escapeString: true, + highlight: false, + indent: 2, + maxDepth: Infinity, + maxWidth: Infinity, + min: false, + plugins: [], + printBasicPrototype: true, + printFunctionName: true, + theme: DEFAULT_THEME +}); +exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS; +function validateOptions(options) { + Object.keys(options).forEach(key => { + if (!Object.prototype.hasOwnProperty.call(DEFAULT_OPTIONS, key)) { + throw new Error(`pretty-format: Unknown option "${key}".`); + } + }); + if (options.min && options.indent !== undefined && options.indent !== 0) { + throw new Error( + 'pretty-format: Options "min" and "indent" cannot be used together.' + ); + } + if (options.theme !== undefined) { + if (options.theme === null) { + throw new Error('pretty-format: Option "theme" must not be null.'); + } + if (typeof options.theme !== 'object') { + throw new Error( + `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` + ); + } + } +} +const getColorsHighlight = options => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = + options.theme && options.theme[key] !== undefined + ? options.theme[key] + : DEFAULT_THEME[key]; + const color = value && _ansiStyles.default[value]; + if ( + color && + typeof color.close === 'string' && + typeof color.open === 'string' + ) { + colors[key] = color; + } else { + throw new Error( + `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` + ); + } + return colors; + }, Object.create(null)); +const getColorsEmpty = () => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: '', + open: '' + }; + return colors; + }, Object.create(null)); +const getPrintFunctionName = options => + options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName; +const getEscapeRegex = options => + options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex; +const getEscapeString = options => + options?.escapeString ?? DEFAULT_OPTIONS.escapeString; +const getConfig = options => ({ + callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, + colors: options?.highlight ? getColorsHighlight(options) : getColorsEmpty(), + compareKeys: + typeof options?.compareKeys === 'function' || options?.compareKeys === null + ? options.compareKeys + : DEFAULT_OPTIONS.compareKeys, + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: options?.min + ? '' + : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), + maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, + maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, + min: options?.min ?? DEFAULT_OPTIONS.min, + plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, + printBasicPrototype: options?.printBasicPrototype ?? true, + printFunctionName: getPrintFunctionName(options), + spacingInner: options?.min ? ' ' : '\n', + spacingOuter: options?.min ? '' : '\n' +}); +function createIndent(indent) { + return new Array(indent + 1).join(' '); +} + +/** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ +function format(val, options) { + if (options) { + validateOptions(options); + if (options.plugins) { + const plugin = findPlugin(options.plugins, val); + if (plugin !== null) { + return printPlugin(plugin, val, getConfig(options), '', 0, []); + } + } + } + const basicResult = printBasicValue( + val, + getPrintFunctionName(options), + getEscapeRegex(options), + getEscapeString(options) + ); + if (basicResult !== null) { + return basicResult; + } + return printComplexValue(val, getConfig(options), '', 0, []); +} +const plugins = { + AsymmetricMatcher: _AsymmetricMatcher.default, + DOMCollection: _DOMCollection.default, + DOMElement: _DOMElement.default, + Immutable: _Immutable.default, + ReactElement: _ReactElement.default, + ReactTestComponent: _ReactTestComponent.default +}; +exports.plugins = plugins; +var _default = format; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/AsymmetricMatcher.js b/web/node_modules/pretty-format/build/plugins/AsymmetricMatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..ef355f737b187efbdba0c10b71d2ef8b21b24482 --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/AsymmetricMatcher.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +var _collections = require('../collections'); +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const asymmetricMatcher = + typeof Symbol === 'function' && Symbol.for + ? Symbol.for('jest.asymmetricMatcher') + : 0x1357a5; +const SPACE = ' '; +const serialize = (val, config, indentation, depth, refs, printer) => { + const stringedValue = val.toString(); + if ( + stringedValue === 'ArrayContaining' || + stringedValue === 'ArrayNotContaining' + ) { + if (++depth > config.maxDepth) { + return `[${stringedValue}]`; + } + return `${stringedValue + SPACE}[${(0, _collections.printListItems)( + val.sample, + config, + indentation, + depth, + refs, + printer + )}]`; + } + if ( + stringedValue === 'ObjectContaining' || + stringedValue === 'ObjectNotContaining' + ) { + if (++depth > config.maxDepth) { + return `[${stringedValue}]`; + } + return `${stringedValue + SPACE}{${(0, _collections.printObjectProperties)( + val.sample, + config, + indentation, + depth, + refs, + printer + )}}`; + } + if ( + stringedValue === 'StringMatching' || + stringedValue === 'StringNotMatching' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + if ( + stringedValue === 'StringContaining' || + stringedValue === 'StringNotContaining' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + if (typeof val.toAsymmetricMatcher !== 'function') { + throw new Error( + `Asymmetric matcher ${val.constructor.name} does not implement toAsymmetricMatcher()` + ); + } + return val.toAsymmetricMatcher(); +}; +exports.serialize = serialize; +const test = val => val && val.$$typeof === asymmetricMatcher; +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/DOMCollection.js b/web/node_modules/pretty-format/build/plugins/DOMCollection.js new file mode 100644 index 0000000000000000000000000000000000000000..7b495b9a5d684d7f6c62c40f78d8ef57f1a49cdd --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/DOMCollection.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +var _collections = require('../collections'); +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const SPACE = ' '; +const OBJECT_NAMES = ['DOMStringMap', 'NamedNodeMap']; +const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; +const testName = name => + OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); +const test = val => + val && + val.constructor && + !!val.constructor.name && + testName(val.constructor.name); +exports.test = test; +const isNamedNodeMap = collection => + collection.constructor.name === 'NamedNodeMap'; +const serialize = (collection, config, indentation, depth, refs, printer) => { + const name = collection.constructor.name; + if (++depth > config.maxDepth) { + return `[${name}]`; + } + return ( + (config.min ? '' : name + SPACE) + + (OBJECT_NAMES.indexOf(name) !== -1 + ? `{${(0, _collections.printObjectProperties)( + isNamedNodeMap(collection) + ? Array.from(collection).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}) + : { + ...collection + }, + config, + indentation, + depth, + refs, + printer + )}}` + : `[${(0, _collections.printListItems)( + Array.from(collection), + config, + indentation, + depth, + refs, + printer + )}]`) + ); +}; +exports.serialize = serialize; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/DOMElement.js b/web/node_modules/pretty-format/build/plugins/DOMElement.js new file mode 100644 index 0000000000000000000000000000000000000000..9c834a6e229d07a63d262df627dd36e7020aaa3e --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/DOMElement.js @@ -0,0 +1,101 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +var _markup = require('./lib/markup'); +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const ELEMENT_NODE = 1; +const TEXT_NODE = 3; +const COMMENT_NODE = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; +const testHasAttribute = val => { + try { + return typeof val.hasAttribute === 'function' && val.hasAttribute('is'); + } catch { + return false; + } +}; +const testNode = val => { + const constructorName = val.constructor.name; + const {nodeType, tagName} = val; + const isCustomElement = + (typeof tagName === 'string' && tagName.includes('-')) || + testHasAttribute(val); + return ( + (nodeType === ELEMENT_NODE && + (ELEMENT_REGEXP.test(constructorName) || isCustomElement)) || + (nodeType === TEXT_NODE && constructorName === 'Text') || + (nodeType === COMMENT_NODE && constructorName === 'Comment') || + (nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment') + ); +}; +const test = val => val?.constructor?.name && testNode(val); +exports.test = test; +function nodeIsText(node) { + return node.nodeType === TEXT_NODE; +} +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; +} +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} +const serialize = (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return (0, _markup.printText)(node.data, config); + } + if (nodeIsComment(node)) { + return (0, _markup.printComment)(node.data, config); + } + const type = nodeIsFragment(node) + ? 'DocumentFragment' + : node.tagName.toLowerCase(); + if (++depth > config.maxDepth) { + return (0, _markup.printElementAsLeaf)(type, config); + } + return (0, _markup.printElement)( + type, + (0, _markup.printProps)( + nodeIsFragment(node) + ? [] + : Array.from(node.attributes, attr => attr.name).sort(), + nodeIsFragment(node) + ? {} + : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + Array.prototype.slice.call(node.childNodes || node.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); +}; +exports.serialize = serialize; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/Immutable.js b/web/node_modules/pretty-format/build/plugins/Immutable.js new file mode 100644 index 0000000000000000000000000000000000000000..14f56561dea6dfa7a0d9fa44b183b4563ff5fc94 --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/Immutable.js @@ -0,0 +1,217 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +var _collections = require('../collections'); +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// SENTINEL constants are from https://github.com/facebook/immutable-js +const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; +const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; +const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; +const IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; +const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; +const IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@'; // immutable v4 +const IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; +const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; +const IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; +const getImmutableName = name => `Immutable.${name}`; +const printAsLeaf = name => `[${name}]`; +const SPACE = ' '; +const LAZY = '…'; // Seq is lazy if it calls a method like filter + +const printImmutableEntries = ( + val, + config, + indentation, + depth, + refs, + printer, + type +) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : `${getImmutableName(type) + SPACE}{${(0, + _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + )}}`; + +// Record has an entries method because it is a collection in immutable v3. +// Return an iterator for Immutable Record from version v3 or v4. +function getRecordEntries(val) { + let i = 0; + return { + next() { + if (i < val._keys.length) { + const key = val._keys[i++]; + return { + done: false, + value: [key, val.get(key)] + }; + } + return { + done: true, + value: undefined + }; + } + }; +} +const printImmutableRecord = ( + val, + config, + indentation, + depth, + refs, + printer +) => { + // _name property is defined only for an Immutable Record instance + // which was constructed with a second optional descriptive name arg + const name = getImmutableName(val._name || 'Record'); + return ++depth > config.maxDepth + ? printAsLeaf(name) + : `${name + SPACE}{${(0, _collections.printIteratorEntries)( + getRecordEntries(val), + config, + indentation, + depth, + refs, + printer + )}}`; +}; +const printImmutableSeq = (val, config, indentation, depth, refs, printer) => { + const name = getImmutableName('Seq'); + if (++depth > config.maxDepth) { + return printAsLeaf(name); + } + if (val[IS_KEYED_SENTINEL]) { + return `${name + SPACE}{${ + // from Immutable collection of entries or from ECMAScript object + val._iter || val._object + ? (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY + }}`; + } + return `${name + SPACE}[${ + val._iter || + // from Immutable collection of values + val._array || + // from ECMAScript array + val._collection || + // from ECMAScript collection in immutable v4 + val._iterable // from ECMAScript collection in immutable v3 + ? (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY + }]`; +}; +const printImmutableValues = ( + val, + config, + indentation, + depth, + refs, + printer, + type +) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : `${getImmutableName(type) + SPACE}[${(0, + _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + )}]`; +const serialize = (val, config, indentation, depth, refs, printer) => { + if (val[IS_MAP_SENTINEL]) { + return printImmutableEntries( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedMap' : 'Map' + ); + } + if (val[IS_LIST_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'List' + ); + } + if (val[IS_SET_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedSet' : 'Set' + ); + } + if (val[IS_STACK_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'Stack' + ); + } + if (val[IS_SEQ_SENTINEL]) { + return printImmutableSeq(val, config, indentation, depth, refs, printer); + } + + // For compatibility with immutable v3 and v4, let record be the default. + return printImmutableRecord(val, config, indentation, depth, refs, printer); +}; + +// Explicitly comparing sentinel properties to true avoids false positive +// when mock identity-obj-proxy returns the key as the value for any key. +exports.serialize = serialize; +const test = val => + val && + (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/ReactElement.js b/web/node_modules/pretty-format/build/plugins/ReactElement.js new file mode 100644 index 0000000000000000000000000000000000000000..1db3bc7c338434a1dbf0059e344ae895db8367ba --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/ReactElement.js @@ -0,0 +1,143 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +var ReactIs = _interopRequireWildcard(require('react-is')); +var _markup = require('./lib/markup'); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (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; +} +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Given element.props.children, or subtree during recursive traversal, +// return flattened array of children. +const getChildren = (arg, children = []) => { + if (Array.isArray(arg)) { + arg.forEach(item => { + getChildren(item, children); + }); + } else if (arg != null && arg !== false) { + children.push(arg); + } + return children; +}; +const getType = element => { + const type = element.type; + if (typeof type === 'string') { + return type; + } + if (typeof type === 'function') { + return type.displayName || type.name || 'Unknown'; + } + if (ReactIs.isFragment(element)) { + return 'React.Fragment'; + } + if (ReactIs.isSuspense(element)) { + return 'React.Suspense'; + } + if (typeof type === 'object' && type !== null) { + if (ReactIs.isContextProvider(element)) { + return 'Context.Provider'; + } + if (ReactIs.isContextConsumer(element)) { + return 'Context.Consumer'; + } + if (ReactIs.isForwardRef(element)) { + if (type.displayName) { + return type.displayName; + } + const functionName = type.render.displayName || type.render.name || ''; + return functionName !== '' ? `ForwardRef(${functionName})` : 'ForwardRef'; + } + if (ReactIs.isMemo(element)) { + const functionName = + type.displayName || type.type.displayName || type.type.name || ''; + return functionName !== '' ? `Memo(${functionName})` : 'Memo'; + } + } + return 'UNDEFINED'; +}; +const getPropKeys = element => { + const {props} = element; + return Object.keys(props) + .filter(key => key !== 'children' && props[key] !== undefined) + .sort(); +}; +const serialize = (element, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(getType(element), config) + : (0, _markup.printElement)( + getType(element), + (0, _markup.printProps)( + getPropKeys(element), + element.props, + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + getChildren(element.props.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); +exports.serialize = serialize; +const test = val => val != null && ReactIs.isElement(val); +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/ReactTestComponent.js b/web/node_modules/pretty-format/build/plugins/ReactTestComponent.js new file mode 100644 index 0000000000000000000000000000000000000000..7207f2b90b4f3549587610b97bc28611bcfc7a75 --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/ReactTestComponent.js @@ -0,0 +1,66 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +var _markup = require('./lib/markup'); +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Child can be `number` in Stack renderer but not in Fiber renderer. + +const testSymbol = + typeof Symbol === 'function' && Symbol.for + ? Symbol.for('react.test.json') + : 0xea71357; +const getPropKeys = object => { + const {props} = object; + return props + ? Object.keys(props) + .filter(key => props[key] !== undefined) + .sort() + : []; +}; +const serialize = (object, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(object.type, config) + : (0, _markup.printElement)( + object.type, + object.props + ? (0, _markup.printProps)( + getPropKeys(object), + object.props, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + object.children + ? (0, _markup.printChildren)( + object.children, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + config, + indentation + ); +exports.serialize = serialize; +const test = val => val && val.$$typeof === testSymbol; +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/web/node_modules/pretty-format/build/plugins/lib/escapeHTML.js b/web/node_modules/pretty-format/build/plugins/lib/escapeHTML.js new file mode 100644 index 0000000000000000000000000000000000000000..8b454299b6706df83acd86dd04f7430b79418a27 --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/lib/escapeHTML.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = escapeHTML; +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function escapeHTML(str) { + return str.replace(//g, '>'); +} diff --git a/web/node_modules/pretty-format/build/plugins/lib/markup.js b/web/node_modules/pretty-format/build/plugins/lib/markup.js new file mode 100644 index 0000000000000000000000000000000000000000..dae3bc4ada911297e1d0f1ad2e8ea7083a81a649 --- /dev/null +++ b/web/node_modules/pretty-format/build/plugins/lib/markup.js @@ -0,0 +1,113 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printText = + exports.printProps = + exports.printElementAsLeaf = + exports.printElement = + exports.printComment = + exports.printChildren = + void 0; +var _escapeHTML = _interopRequireDefault(require('./escapeHTML')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Return empty string if keys is empty. +const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys + .map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = + config.spacingOuter + + indentationNext + + printed + + config.spacingOuter + + indentation; + } + printed = `{${printed}}`; + } + return `${ + config.spacingInner + + indentation + + colors.prop.open + + key + + colors.prop.close + }=${colors.value.open}${printed}${colors.value.close}`; + }) + .join(''); +}; + +// Return empty string if children is empty. +exports.printProps = printProps; +const printChildren = (children, config, indentation, depth, refs, printer) => + children + .map( + child => + config.spacingOuter + + indentation + + (typeof child === 'string' + ? printText(child, config) + : printer(child, config, indentation, depth, refs)) + ) + .join(''); +exports.printChildren = printChildren; +const printText = (text, config) => { + const contentColor = config.colors.content; + return ( + contentColor.open + (0, _escapeHTML.default)(text) + contentColor.close + ); +}; +exports.printText = printText; +const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return `${commentColor.open}${ + commentColor.close + }`; +}; + +// Separate the functions to format props, children, and element, +// so a plugin could override a particular function, if needed. +// Too bad, so sad: the traditional (but unnecessary) space +// in a self-closing tagColor requires a second test of printedProps. +exports.printComment = printComment; +const printElement = ( + type, + printedProps, + printedChildren, + config, + indentation +) => { + const tagColor = config.colors.tag; + return `${tagColor.open}<${type}${ + printedProps && + tagColor.close + + printedProps + + config.spacingOuter + + indentation + + tagColor.open + }${ + printedChildren + ? `>${tagColor.close}${printedChildren}${config.spacingOuter}${indentation}${tagColor.open}${tagColor.close}`; +}; +exports.printElement = printElement; +const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return `${tagColor.open}<${type}${tagColor.close} …${tagColor.open} />${tagColor.close}`; +}; +exports.printElementAsLeaf = printElementAsLeaf; diff --git a/web/node_modules/pretty-format/build/types.js b/web/node_modules/pretty-format/build/types.js new file mode 100644 index 0000000000000000000000000000000000000000..ad9a93a7c160f02945911772460eb8a1bcb003db --- /dev/null +++ b/web/node_modules/pretty-format/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/web/node_modules/pretty-format/package.json b/web/node_modules/pretty-format/package.json new file mode 100644 index 0000000000000000000000000000000000000000..23e5fc787fea9cdbb5d9ce7e7b921858a288864b --- /dev/null +++ b/web/node_modules/pretty-format/package.json @@ -0,0 +1,43 @@ +{ + "name": "pretty-format", + "version": "29.7.0", + "repository": { + "type": "git", + "url": "https://github.com/jestjs/jest.git", + "directory": "packages/pretty-format" + }, + "license": "MIT", + "description": "Stringify any JavaScript value.", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "author": "James Kyle ", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "devDependencies": { + "@types/react": "^17.0.3", + "@types/react-is": "^18.0.0", + "@types/react-test-renderer": "17.0.2", + "immutable": "^4.0.0", + "jest-util": "^29.7.0", + "react": "17.0.2", + "react-dom": "^17.0.1", + "react-test-renderer": "17.0.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4e56991693da7cd4c3730dc3579a1dd1403ee630" +} diff --git a/web/node_modules/react-is/LICENSE b/web/node_modules/react-is/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b96dcb0480a0b0be0727976e5202a1e7b23edc3f --- /dev/null +++ b/web/node_modules/react-is/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +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/web/node_modules/react-is/README.md b/web/node_modules/react-is/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d25597761817812537077127533a7bc6dbd0d3d8 --- /dev/null +++ b/web/node_modules/react-is/README.md @@ -0,0 +1,104 @@ +# `react-is` + +This package allows you to test arbitrary values and see if they're a particular React element type. + +## Installation + +```sh +# Yarn +yarn add react-is + +# NPM +npm install react-is +``` + +## Usage + +### Determining if a Component is Valid + +```js +import React from "react"; +import * as ReactIs from "react-is"; + +class ClassComponent extends React.Component { + render() { + return React.createElement("div"); + } +} + +const FunctionComponent = () => React.createElement("div"); + +const ForwardRefComponent = React.forwardRef((props, ref) => + React.createElement(Component, { forwardedRef: ref, ...props }) +); + +const Context = React.createContext(false); + +ReactIs.isValidElementType("div"); // true +ReactIs.isValidElementType(ClassComponent); // true +ReactIs.isValidElementType(FunctionComponent); // true +ReactIs.isValidElementType(ForwardRefComponent); // true +ReactIs.isValidElementType(Context.Provider); // true +ReactIs.isValidElementType(Context.Consumer); // true +ReactIs.isValidElementType(React.createFactory("div")); // true +``` + +### Determining an Element's Type + +#### Context + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +const ThemeContext = React.createContext("blue"); + +ReactIs.isContextConsumer(); // true +ReactIs.isContextProvider(); // true +ReactIs.typeOf() === ReactIs.ContextProvider; // true +ReactIs.typeOf() === ReactIs.ContextConsumer; // true +``` + +#### Element + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +ReactIs.isElement(
); // true +ReactIs.typeOf(
) === ReactIs.Element; // true +``` + +#### Fragment + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +ReactIs.isFragment(<>); // true +ReactIs.typeOf(<>) === ReactIs.Fragment; // true +``` + +#### Portal + +```js +import React from "react"; +import ReactDOM from "react-dom"; +import * as ReactIs from 'react-is'; + +const div = document.createElement("div"); +const portal = ReactDOM.createPortal(
, div); + +ReactIs.isPortal(portal); // true +ReactIs.typeOf(portal) === ReactIs.Portal; // true +``` + +#### StrictMode + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +ReactIs.isStrictMode(); // true +ReactIs.typeOf() === ReactIs.StrictMode; // true +``` diff --git a/web/node_modules/react-is/cjs/react-is.development.js b/web/node_modules/react-is/cjs/react-is.development.js new file mode 100644 index 0000000000000000000000000000000000000000..6ed9c03dad95bb29ade1da049387b2ce268dd754 --- /dev/null +++ b/web/node_modules/react-is/cjs/react-is.development.js @@ -0,0 +1,221 @@ +/** + * @license React + * react-is.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + +// ----------------------------------------------------------------------------- + +var enableScopeAPI = false; // Experimental Create Event Handle API. +var enableCacheElement = false; +var enableTransitionTracing = false; // No known bugs, but needs performance testing + +var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber +// stuff. Intended to enable React core members to more easily debug scheduling +// issues in DEV builds. + +var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + +var REACT_MODULE_REFERENCE; + +{ + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); +} + +function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; +} + +function typeOf(object) { + if (typeof object === 'object' && object !== null) { + var $$typeof = object.$$typeof; + + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + var type = object.type; + + switch (type) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + return type; + + default: + var $$typeofType = type && type.$$typeof; + + switch ($$typeofType) { + case REACT_SERVER_CONTEXT_TYPE: + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + case REACT_PROVIDER_TYPE: + return $$typeofType; + + default: + return $$typeof; + } + + } + + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + + return undefined; +} +var ContextConsumer = REACT_CONTEXT_TYPE; +var ContextProvider = REACT_PROVIDER_TYPE; +var Element = REACT_ELEMENT_TYPE; +var ForwardRef = REACT_FORWARD_REF_TYPE; +var Fragment = REACT_FRAGMENT_TYPE; +var Lazy = REACT_LAZY_TYPE; +var Memo = REACT_MEMO_TYPE; +var Portal = REACT_PORTAL_TYPE; +var Profiler = REACT_PROFILER_TYPE; +var StrictMode = REACT_STRICT_MODE_TYPE; +var Suspense = REACT_SUSPENSE_TYPE; +var SuspenseList = REACT_SUSPENSE_LIST_TYPE; +var hasWarnedAboutDeprecatedIsAsyncMode = false; +var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated + +function isAsyncMode(object) { + { + if (!hasWarnedAboutDeprecatedIsAsyncMode) { + hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; +} +function isConcurrentMode(object) { + { + if (!hasWarnedAboutDeprecatedIsConcurrentMode) { + hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; +} +function isContextConsumer(object) { + return typeOf(object) === REACT_CONTEXT_TYPE; +} +function isContextProvider(object) { + return typeOf(object) === REACT_PROVIDER_TYPE; +} +function isElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; +} +function isForwardRef(object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; +} +function isFragment(object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; +} +function isLazy(object) { + return typeOf(object) === REACT_LAZY_TYPE; +} +function isMemo(object) { + return typeOf(object) === REACT_MEMO_TYPE; +} +function isPortal(object) { + return typeOf(object) === REACT_PORTAL_TYPE; +} +function isProfiler(object) { + return typeOf(object) === REACT_PROFILER_TYPE; +} +function isStrictMode(object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; +} +function isSuspense(object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; +} +function isSuspenseList(object) { + return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; +} + +exports.ContextConsumer = ContextConsumer; +exports.ContextProvider = ContextProvider; +exports.Element = Element; +exports.ForwardRef = ForwardRef; +exports.Fragment = Fragment; +exports.Lazy = Lazy; +exports.Memo = Memo; +exports.Portal = Portal; +exports.Profiler = Profiler; +exports.StrictMode = StrictMode; +exports.Suspense = Suspense; +exports.SuspenseList = SuspenseList; +exports.isAsyncMode = isAsyncMode; +exports.isConcurrentMode = isConcurrentMode; +exports.isContextConsumer = isContextConsumer; +exports.isContextProvider = isContextProvider; +exports.isElement = isElement; +exports.isForwardRef = isForwardRef; +exports.isFragment = isFragment; +exports.isLazy = isLazy; +exports.isMemo = isMemo; +exports.isPortal = isPortal; +exports.isProfiler = isProfiler; +exports.isStrictMode = isStrictMode; +exports.isSuspense = isSuspense; +exports.isSuspenseList = isSuspenseList; +exports.isValidElementType = isValidElementType; +exports.typeOf = typeOf; + })(); +} diff --git a/web/node_modules/react-is/cjs/react-is.production.min.js b/web/node_modules/react-is/cjs/react-is.production.min.js new file mode 100644 index 0000000000000000000000000000000000000000..f2322cbb2f1f00b0aeedf91e99defedcc3dde281 --- /dev/null +++ b/web/node_modules/react-is/cjs/react-is.production.min.js @@ -0,0 +1,14 @@ +/** + * @license React + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var b=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference"); +function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}exports.ContextConsumer=h;exports.ContextProvider=g;exports.Element=b;exports.ForwardRef=l;exports.Fragment=d;exports.Lazy=q;exports.Memo=p;exports.Portal=c;exports.Profiler=f;exports.StrictMode=e;exports.Suspense=m; +exports.SuspenseList=n;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return v(a)===h};exports.isContextProvider=function(a){return v(a)===g};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return v(a)===l};exports.isFragment=function(a){return v(a)===d};exports.isLazy=function(a){return v(a)===q};exports.isMemo=function(a){return v(a)===p}; +exports.isPortal=function(a){return v(a)===c};exports.isProfiler=function(a){return v(a)===f};exports.isStrictMode=function(a){return v(a)===e};exports.isSuspense=function(a){return v(a)===m};exports.isSuspenseList=function(a){return v(a)===n}; +exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?!0:!1};exports.typeOf=v; diff --git a/web/node_modules/react-is/index.js b/web/node_modules/react-is/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3ae098d078776a29e40a87a5f98edd1f697594ea --- /dev/null +++ b/web/node_modules/react-is/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/react-is.production.min.js'); +} else { + module.exports = require('./cjs/react-is.development.js'); +} diff --git a/web/node_modules/react-is/package.json b/web/node_modules/react-is/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4cd3c3bcbadadcde7a3ca063585bdbbb7f92f59a --- /dev/null +++ b/web/node_modules/react-is/package.json @@ -0,0 +1,26 @@ +{ + "name": "react-is", + "version": "18.2.0", + "description": "Brand checking of React Elements.", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/facebook/react.git", + "directory": "packages/react-is" + }, + "keywords": [ + "react" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/facebook/react/issues" + }, + "homepage": "https://reactjs.org/", + "files": [ + "LICENSE", + "README.md", + "index.js", + "cjs/", + "umd/" + ] +} \ No newline at end of file diff --git a/web/node_modules/react-is/umd/react-is.development.js b/web/node_modules/react-is/umd/react-is.development.js new file mode 100644 index 0000000000000000000000000000000000000000..1257aef164e91e1fc7242ea39fbba9ff071dfa35 --- /dev/null +++ b/web/node_modules/react-is/umd/react-is.development.js @@ -0,0 +1,220 @@ +/** + * @license React + * react-is.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.ReactIs = {})); +}(this, (function (exports) { 'use strict'; + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + + // ----------------------------------------------------------------------------- + + var enableScopeAPI = false; // Experimental Create Event Handle API. + var enableCacheElement = false; + var enableTransitionTracing = false; // No known bugs, but needs performance testing + + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + // stuff. Intended to enable React core members to more easily debug scheduling + // issues in DEV builds. + + var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + + var REACT_MODULE_REFERENCE; + + { + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); + } + + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + + return false; + } + + function typeOf(object) { + if (typeof object === 'object' && object !== null) { + var $$typeof = object.$$typeof; + + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + var type = object.type; + + switch (type) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + return type; + + default: + var $$typeofType = type && type.$$typeof; + + switch ($$typeofType) { + case REACT_SERVER_CONTEXT_TYPE: + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + case REACT_PROVIDER_TYPE: + return $$typeofType; + + default: + return $$typeof; + } + + } + + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + + return undefined; + } + var ContextConsumer = REACT_CONTEXT_TYPE; + var ContextProvider = REACT_PROVIDER_TYPE; + var Element = REACT_ELEMENT_TYPE; + var ForwardRef = REACT_FORWARD_REF_TYPE; + var Fragment = REACT_FRAGMENT_TYPE; + var Lazy = REACT_LAZY_TYPE; + var Memo = REACT_MEMO_TYPE; + var Portal = REACT_PORTAL_TYPE; + var Profiler = REACT_PROFILER_TYPE; + var StrictMode = REACT_STRICT_MODE_TYPE; + var Suspense = REACT_SUSPENSE_TYPE; + var SuspenseList = REACT_SUSPENSE_LIST_TYPE; + var hasWarnedAboutDeprecatedIsAsyncMode = false; + var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated + + function isAsyncMode(object) { + { + if (!hasWarnedAboutDeprecatedIsAsyncMode) { + hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; + } + function isConcurrentMode(object) { + { + if (!hasWarnedAboutDeprecatedIsConcurrentMode) { + hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; + } + function isContextConsumer(object) { + return typeOf(object) === REACT_CONTEXT_TYPE; + } + function isContextProvider(object) { + return typeOf(object) === REACT_PROVIDER_TYPE; + } + function isElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + function isForwardRef(object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; + } + function isFragment(object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; + } + function isLazy(object) { + return typeOf(object) === REACT_LAZY_TYPE; + } + function isMemo(object) { + return typeOf(object) === REACT_MEMO_TYPE; + } + function isPortal(object) { + return typeOf(object) === REACT_PORTAL_TYPE; + } + function isProfiler(object) { + return typeOf(object) === REACT_PROFILER_TYPE; + } + function isStrictMode(object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; + } + function isSuspense(object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; + } + function isSuspenseList(object) { + return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; + } + + exports.ContextConsumer = ContextConsumer; + exports.ContextProvider = ContextProvider; + exports.Element = Element; + exports.ForwardRef = ForwardRef; + exports.Fragment = Fragment; + exports.Lazy = Lazy; + exports.Memo = Memo; + exports.Portal = Portal; + exports.Profiler = Profiler; + exports.StrictMode = StrictMode; + exports.Suspense = Suspense; + exports.SuspenseList = SuspenseList; + exports.isAsyncMode = isAsyncMode; + exports.isConcurrentMode = isConcurrentMode; + exports.isContextConsumer = isContextConsumer; + exports.isContextProvider = isContextProvider; + exports.isElement = isElement; + exports.isForwardRef = isForwardRef; + exports.isFragment = isFragment; + exports.isLazy = isLazy; + exports.isMemo = isMemo; + exports.isPortal = isPortal; + exports.isProfiler = isProfiler; + exports.isStrictMode = isStrictMode; + exports.isSuspense = isSuspense; + exports.isSuspenseList = isSuspenseList; + exports.isValidElementType = isValidElementType; + exports.typeOf = typeOf; + +}))); diff --git a/web/node_modules/react-is/umd/react-is.production.min.js b/web/node_modules/react-is/umd/react-is.production.min.js new file mode 100644 index 0000000000000000000000000000000000000000..84a9cdeed2cde028c78fd907deaa2264d2a261c6 --- /dev/null +++ b/web/node_modules/react-is/umd/react-is.production.min.js @@ -0,0 +1,15 @@ +/** + * @license React + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function(){'use strict';(function(b,c){"object"===typeof exports&&"undefined"!==typeof module?c(exports):"function"===typeof define&&define.amd?define(["exports"],c):(b=b||self,c(b.ReactIs={}))})(this,function(b){function c(a){if("object"===typeof a&&null!==a){var b=a.$$typeof;switch(b){case q:switch(a=a.type,a){case d:case e:case f:case g:case h:return a;default:switch(a=a&&a.$$typeof,a){case t:case k:case l:case m:case n:case p:return a;default:return b}}case r:return b}}}var q=Symbol.for("react.element"), +r=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),e=Symbol.for("react.profiler"),p=Symbol.for("react.provider"),k=Symbol.for("react.context"),t=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),n=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),u=Symbol.for("react.offscreen");var v=Symbol.for("react.module.reference");b.ContextConsumer=k;b.ContextProvider=p;b.Element= +q;b.ForwardRef=l;b.Fragment=d;b.Lazy=m;b.Memo=n;b.Portal=r;b.Profiler=e;b.StrictMode=f;b.Suspense=g;b.SuspenseList=h;b.isAsyncMode=function(a){return!1};b.isConcurrentMode=function(a){return!1};b.isContextConsumer=function(a){return c(a)===k};b.isContextProvider=function(a){return c(a)===p};b.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===q};b.isForwardRef=function(a){return c(a)===l};b.isFragment=function(a){return c(a)===d};b.isLazy=function(a){return c(a)===m};b.isMemo= +function(a){return c(a)===n};b.isPortal=function(a){return c(a)===r};b.isProfiler=function(a){return c(a)===e};b.isStrictMode=function(a){return c(a)===f};b.isSuspense=function(a){return c(a)===g};b.isSuspenseList=function(a){return c(a)===h};b.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===d||a===e||a===f||a===g||a===h||a===u||"object"===typeof a&&null!==a&&(a.$$typeof===m||a.$$typeof===n||a.$$typeof===p||a.$$typeof===k||a.$$typeof===l||a.$$typeof===v||void 0!== +a.getModuleId)?!0:!1};b.typeOf=c}); +})(); diff --git a/web/node_modules/rollup/LICENSE.md b/web/node_modules/rollup/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..7e714383737a142c70e2e48125e6770f5d33b5b2 --- /dev/null +++ b/web/node_modules/rollup/LICENSE.md @@ -0,0 +1,652 @@ +# Rollup core license +Rollup is released under the MIT license: + +The MIT License (MIT) + +Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# Licenses of bundled dependencies +The published Rollup artifact additionally contains code with the following licenses: +MIT, ISC + +# Bundled dependencies: +## @jridgewell/sourcemap-codec +License: MIT +By: Rich Harris +Repository: git+https://github.com/jridgewell/sourcemap-codec.git + +> The MIT License +> +> Copyright (c) 2015 Rich Harris +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## @rollup/pluginutils +License: MIT +By: Rich Harris +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## anymatch +License: ISC +By: Elan Shanker +Repository: https://github.com/micromatch/anymatch + +> The ISC License +> +> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## binary-extensions +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/binary-extensions + +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> 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. + +--------------------------------------- + +## builtin-modules +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/builtin-modules + +> 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. + +--------------------------------------- + +## chokidar +License: MIT +By: Paul Miller, Elan Shanker +Repository: git+https://github.com/paulmillr/chokidar.git + +> 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. + +--------------------------------------- + +## colorette +License: MIT +By: Jorge Bucaran +Repository: jorgebucaran/colorette + +> Copyright © Jorge Bucaran <> +> +> 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. + +--------------------------------------- + +## date-time +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/date-time + +> 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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> 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. + +--------------------------------------- + +## flru +License: MIT +By: Luke Edwards +Repository: lukeed/flru + +> MIT License +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## is-binary-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-binary-path + +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## is-reference +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/is-reference.git + +--------------------------------------- + +## locate-character +License: MIT +By: Rich Harris +Repository: git+https://gitlab.com/Rich-Harris/locate-character.git + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: https://github.com/rich-harris/magic-string + +> Copyright 2018 Rich Harris +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## normalize-path +License: MIT +By: Jon Schlinkert, Blaine Bublitz +Repository: jonschlinkert/normalize-path + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## parse-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/parse-ms + +> 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. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> 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. + +--------------------------------------- + +## pretty-bytes +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-bytes + +> 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. + +--------------------------------------- + +## pretty-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-ms + +> 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. + +--------------------------------------- + +## readdirp +License: MIT +By: Thorsten Lorenz, Paul Miller +Repository: git://github.com/paulmillr/readdirp.git + +> MIT License +> +> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## signal-exit +License: ISC +By: Ben Coe +Repository: https://github.com/tapjs/signal-exit.git + +> The ISC License +> +> Copyright (c) 2015-2023 Benjamin Coe, 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. + +--------------------------------------- + +## time-zone +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/time-zone + +> 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. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## yargs-parser +License: ISC +By: Ben Coe +Repository: https://github.com/yargs/yargs-parser.git + +> Copyright (c) 2016, 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/web/node_modules/rollup/README.md b/web/node_modules/rollup/README.md new file mode 100644 index 0000000000000000000000000000000000000000..721c96a9e3c90c383fcc17a6e701727a77fcfebb --- /dev/null +++ b/web/node_modules/rollup/README.md @@ -0,0 +1,133 @@ +

+ +

+ +

+ + npm version + + + node compatibility + + + install size + + + code coverage + + + backers + + + sponsors + + + license + + + Join the chat at https://is.gd/rollup_chat + +

+ +

Rollup

+ +## Overview + +Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today. + +## Quick Start Guide + +Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/command-line-interface/) with an optional configuration file or else through its [JavaScript API](https://rollupjs.org/javascript-api/). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/introduction/). + +### Commands + +These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js. + +For browsers: + +```bash +# compile to a +``` + +## Usage + +The primary export of `type-detect` is function that can serve as a replacement for `typeof`. The results of this function will be more specific than that of native `typeof`. + +```js +var type = require('type-detect'); +``` + +#### array + +```js +assert(type([]) === 'Array'); +assert(type(new Array()) === 'Array'); +``` + +#### regexp + +```js +assert(type(/a-z/gi) === 'RegExp'); +assert(type(new RegExp('a-z')) === 'RegExp'); +``` + +#### function + +```js +assert(type(function () {}) === 'function'); +``` + +#### arguments + +```js +(function () { + assert(type(arguments) === 'Arguments'); +})(); +``` + +#### date + +```js +assert(type(new Date) === 'Date'); +``` + +#### number + +```js +assert(type(1) === 'number'); +assert(type(1.234) === 'number'); +assert(type(-1) === 'number'); +assert(type(-1.234) === 'number'); +assert(type(Infinity) === 'number'); +assert(type(NaN) === 'number'); +assert(type(new Number(1)) === 'Number'); // note - the object version has a capital N +``` + +#### string + +```js +assert(type('hello world') === 'string'); +assert(type(new String('hello')) === 'String'); // note - the object version has a capital S +``` + +#### null + +```js +assert(type(null) === 'null'); +assert(type(undefined) !== 'null'); +``` + +#### undefined + +```js +assert(type(undefined) === 'undefined'); +assert(type(null) !== 'undefined'); +``` + +#### object + +```js +var Noop = function () {}; +assert(type({}) === 'Object'); +assert(type(Noop) !== 'Object'); +assert(type(new Noop) === 'Object'); +assert(type(new Object) === 'Object'); +``` + +#### ECMA6 Types + +All new ECMAScript 2015 objects are also supported, such as Promises and Symbols: + +```js +assert(type(new Map() === 'Map'); +assert(type(new WeakMap()) === 'WeakMap'); +assert(type(new Set()) === 'Set'); +assert(type(new WeakSet()) === 'WeakSet'); +assert(type(Symbol()) === 'symbol'); +assert(type(new Promise(callback) === 'Promise'); +assert(type(new Int8Array()) === 'Int8Array'); +assert(type(new Uint8Array()) === 'Uint8Array'); +assert(type(new UInt8ClampedArray()) === 'Uint8ClampedArray'); +assert(type(new Int16Array()) === 'Int16Array'); +assert(type(new Uint16Array()) === 'Uint16Array'); +assert(type(new Int32Array()) === 'Int32Array'); +assert(type(new UInt32Array()) === 'Uint32Array'); +assert(type(new Float32Array()) === 'Float32Array'); +assert(type(new Float64Array()) === 'Float64Array'); +assert(type(new ArrayBuffer()) === 'ArrayBuffer'); +assert(type(new DataView(arrayBuffer)) === 'DataView'); +``` + +Also, if you use `Symbol.toStringTag` to change an Objects return value of the `toString()` Method, `type()` will return this value, e.g: + +```js +var myObject = {}; +myObject[Symbol.toStringTag] = 'myCustomType'; +assert(type(myObject) === 'myCustomType'); +``` diff --git a/web/node_modules/type-detect/index.js b/web/node_modules/type-detect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..98a1e031cd270b5658cdfe2ed966e2e5c4c5f825 --- /dev/null +++ b/web/node_modules/type-detect/index.js @@ -0,0 +1,378 @@ +/* ! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ +const promiseExists = typeof Promise === 'function'; + +/* eslint-disable no-undef */ +const globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist + +const symbolExists = typeof Symbol !== 'undefined'; +const mapExists = typeof Map !== 'undefined'; +const setExists = typeof Set !== 'undefined'; +const weakMapExists = typeof WeakMap !== 'undefined'; +const weakSetExists = typeof WeakSet !== 'undefined'; +const dataViewExists = typeof DataView !== 'undefined'; +const symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; +const symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; +const setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; +const mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; +const setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); +const mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); +const arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; +const arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); +const stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; +const stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); +const toStringLeftSliceLength = 8; +const toStringRightSliceLength = -1; +/** + * ### typeOf (obj) + * + * Uses `Object.prototype.toString` to determine the type of an object, + * normalising behaviour across engine versions & well optimised. + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ +export default function typeDetect(obj) { + /* ! Speed optimisation + * Pre: + * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) + * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) + * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) + * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) + * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) + * Post: + * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) + * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) + * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) + * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) + * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) + */ + const typeofObj = typeof obj; + if (typeofObj !== 'object') { + return typeofObj; + } + + /* ! Speed optimisation + * Pre: + * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) + * Post: + * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) + */ + if (obj === null) { + return 'null'; + } + + /* ! Spec Conformance + * Test: `Object.prototype.toString.call(window)`` + * - Node === "[object global]" + * - Chrome === "[object global]" + * - Firefox === "[object Window]" + * - PhantomJS === "[object Window]" + * - Safari === "[object Window]" + * - IE 11 === "[object Window]" + * - IE Edge === "[object Window]" + * Test: `Object.prototype.toString.call(this)`` + * - Chrome Worker === "[object global]" + * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" + * - Safari Worker === "[object DedicatedWorkerGlobalScope]" + * - IE 11 Worker === "[object WorkerGlobalScope]" + * - IE Edge Worker === "[object WorkerGlobalScope]" + */ + if (obj === globalObject) { + return 'global'; + } + + /* ! Speed optimisation + * Pre: + * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) + * Post: + * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) + */ + if ( + Array.isArray(obj) && + (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) + ) { + return 'Array'; + } + + // Not caching existence of `window` and related properties due to potential + // for `window` to be unset before tests in quasi-browser environments. + if (typeof window === 'object' && window !== null) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/browsers.html#location) + * WhatWG HTML$7.7.3 - The `Location` interface + * Test: `Object.prototype.toString.call(window.location)`` + * - IE <=11 === "[object Object]" + * - IE Edge <=13 === "[object Object]" + */ + if (typeof window.location === 'object' && obj === window.location) { + return 'Location'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#document) + * WhatWG HTML$3.1.1 - The `Document` object + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * WhatWG HTML states: + * > For historical reasons, Window objects must also have a + * > writable, configurable, non-enumerable property named + * > HTMLDocument whose value is the Document interface object. + * Test: `Object.prototype.toString.call(document)`` + * - Chrome === "[object HTMLDocument]" + * - Firefox === "[object HTMLDocument]" + * - Safari === "[object HTMLDocument]" + * - IE <=10 === "[object Document]" + * - IE 11 === "[object HTMLDocument]" + * - IE Edge <=13 === "[object HTMLDocument]" + */ + if (typeof window.document === 'object' && obj === window.document) { + return 'Document'; + } + + if (typeof window.navigator === 'object') { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray + * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` + * - IE <=10 === "[object MSMimeTypesCollection]" + */ + if (typeof window.navigator.mimeTypes === 'object' && + obj === window.navigator.mimeTypes) { + return 'MimeTypeArray'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray + * Test: `Object.prototype.toString.call(navigator.plugins)`` + * - IE <=10 === "[object MSPluginsCollection]" + */ + if (typeof window.navigator.plugins === 'object' && + obj === window.navigator.plugins) { + return 'PluginArray'; + } + } + + if ((typeof window.HTMLElement === 'function' || + typeof window.HTMLElement === 'object') && + obj instanceof window.HTMLElement) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` + * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` + * - IE <=10 === "[object HTMLBlockElement]" + */ + if (obj.tagName === 'BLOCKQUOTE') { + return 'HTMLQuoteElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltabledatacellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('td')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TD') { + return 'HTMLTableDataCellElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltableheadercellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('th')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TH') { + return 'HTMLTableHeaderCellElement'; + } + } + } + + /* ! Speed optimisation + * Pre: + * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) + * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) + * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) + * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) + * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) + * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) + * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) + * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) + * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) + * Post: + * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) + * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) + * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) + * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) + * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) + * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) + * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) + * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) + * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) + */ + const stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]); + if (typeof stringTag === 'string') { + return stringTag; + } + + const objPrototype = Object.getPrototypeOf(obj); + /* ! Speed optimisation + * Pre: + * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) + * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) + * Post: + * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) + * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) + */ + if (objPrototype === RegExp.prototype) { + return 'RegExp'; + } + + /* ! Speed optimisation + * Pre: + * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) + * Post: + * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) + */ + if (objPrototype === Date.prototype) { + return 'Date'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) + * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": + * Test: `Object.prototype.toString.call(Promise.resolve())`` + * - Chrome <=47 === "[object Object]" + * - Edge <=20 === "[object Object]" + * - Firefox 29-Latest === "[object Promise]" + * - Safari 7.1-Latest === "[object Promise]" + */ + if (promiseExists && objPrototype === Promise.prototype) { + return 'Promise'; + } + + /* ! Speed optimisation + * Pre: + * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) + * Post: + * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) + */ + if (setExists && objPrototype === Set.prototype) { + return 'Set'; + } + + /* ! Speed optimisation + * Pre: + * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) + * Post: + * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) + */ + if (mapExists && objPrototype === Map.prototype) { + return 'Map'; + } + + /* ! Speed optimisation + * Pre: + * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) + * Post: + * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) + */ + if (weakSetExists && objPrototype === WeakSet.prototype) { + return 'WeakSet'; + } + + /* ! Speed optimisation + * Pre: + * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) + * Post: + * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) + */ + if (weakMapExists && objPrototype === WeakMap.prototype) { + return 'WeakMap'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) + * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": + * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` + * - Edge <=13 === "[object Object]" + */ + if (dataViewExists && objPrototype === DataView.prototype) { + return 'DataView'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) + * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": + * Test: `Object.prototype.toString.call(new Map().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (mapExists && objPrototype === mapIteratorPrototype) { + return 'Map Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) + * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": + * Test: `Object.prototype.toString.call(new Set().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (setExists && objPrototype === setIteratorPrototype) { + return 'Set Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) + * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": + * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { + return 'Array Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) + * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": + * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (stringIteratorExists && objPrototype === stringIteratorPrototype) { + return 'String Iterator'; + } + + /* ! Speed optimisation + * Pre: + * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) + * Post: + * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) + */ + if (objPrototype === null) { + return 'Object'; + } + + return Object + .prototype + .toString + .call(obj) + .slice(toStringLeftSliceLength, toStringRightSliceLength); +} diff --git a/web/node_modules/type-detect/package.json b/web/node_modules/type-detect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bebf2d865879fdb3f580ee539d3210cb1ca91901 --- /dev/null +++ b/web/node_modules/type-detect/package.json @@ -0,0 +1 @@ +{"name":"type-detect","description":"Improved typeof detection for node.js and the browser.","keywords":["type","typeof","types"],"license":"MIT","author":"Jake Luer (http://alogicalparadox.com)","contributors":["Keith Cirkel (https://github.com/keithamus)","David Losert (https://github.com/davelosert)","Aleksey Shvayka (https://github.com/shvaikalesh)","Lucas Fernandes da Costa (https://github.com/lucasfcosta)","Grant Snodgrass (https://github.com/meeber)","Jeremy Tice (https://github.com/jetpacmonkey)","Edward Betts (https://github.com/EdwardBetts)","dvlsg (https://github.com/dvlsg)","Amila Welihinda (https://github.com/amilajack)","Jake Champion (https://github.com/JakeChampion)","Miroslav Bajtoš (https://github.com/bajtos)"],"files":["index.js","type-detect.js"],"main":"./type-detect.js","repository":{"type":"git","url":"git+ssh://git@github.com/chaijs/type-detect.git"},"scripts":{"bench":"node bench","build":"rollup -c rollup.conf.js","commit-msg":"commitlint -x angular","lint":"eslint --ignore-path .gitignore .","prepare":"cross-env NODE_ENV=production npm run build","semantic-release":"semantic-release pre && npm publish && semantic-release post","pretest:node":"cross-env NODE_ENV=test npm run build","pretest:browser":"cross-env NODE_ENV=test npm run build","test":"npm run test:node && npm run test:browser","test:browser":"karma start --singleRun=true","test:node":"nyc mocha type-detect.test.js","posttest:node":"nyc report --report-dir \"coverage/node-$(node --version)\" --reporter=lcovonly && npm run upload-coverage","posttest:browser":"npm run upload-coverage","upload-coverage":"codecov"},"eslintConfig":{"env":{"es6":true},"extends":["strict/es6"],"globals":{"HTMLElement":false},"rules":{"complexity":0,"max-statements":0,"prefer-rest-params":0}},"devDependencies":{"@commitlint/cli":"^4.2.2","benchmark":"^2.1.0","buble":"^0.16.0","codecov":"^3.0.0","commitlint-config-angular":"^4.2.1","cross-env":"^5.1.1","eslint":"^4.10.0","eslint-config-strict":"^14.0.0","eslint-plugin-filenames":"^1.2.0","husky":"^0.14.3","karma":"^1.7.1","karma-chrome-launcher":"^2.2.0","karma-coverage":"^1.1.1","karma-detect-browsers":"^2.2.5","karma-edge-launcher":"^0.4.2","karma-firefox-launcher":"^1.0.1","karma-ie-launcher":"^1.0.0","karma-mocha":"^1.3.0","karma-opera-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-safaritechpreview-launcher":"0.0.6","karma-sauce-launcher":"^1.2.0","mocha":"^4.0.1","nyc":"^11.3.0","rollup":"^0.50.0","rollup-plugin-buble":"^0.16.0","rollup-plugin-commonjs":"^8.2.6","rollup-plugin-istanbul":"^1.1.0","rollup-plugin-node-resolve":"^3.0.0","semantic-release":"^8.2.0","simple-assert":"^1.0.0"},"engines":{"node":">=4"},"version":"4.0.8"} diff --git a/web/node_modules/type-detect/type-detect.js b/web/node_modules/type-detect/type-detect.js new file mode 100644 index 0000000000000000000000000000000000000000..2f55525258c7ce69ef928573f077294993bd7703 --- /dev/null +++ b/web/node_modules/type-detect/type-detect.js @@ -0,0 +1,388 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.typeDetect = factory()); +}(this, (function () { 'use strict'; + +/* ! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ +var promiseExists = typeof Promise === 'function'; + +/* eslint-disable no-undef */ +var globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist + +var symbolExists = typeof Symbol !== 'undefined'; +var mapExists = typeof Map !== 'undefined'; +var setExists = typeof Set !== 'undefined'; +var weakMapExists = typeof WeakMap !== 'undefined'; +var weakSetExists = typeof WeakSet !== 'undefined'; +var dataViewExists = typeof DataView !== 'undefined'; +var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; +var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; +var setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; +var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; +var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); +var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); +var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; +var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); +var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; +var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); +var toStringLeftSliceLength = 8; +var toStringRightSliceLength = -1; +/** + * ### typeOf (obj) + * + * Uses `Object.prototype.toString` to determine the type of an object, + * normalising behaviour across engine versions & well optimised. + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ +function typeDetect(obj) { + /* ! Speed optimisation + * Pre: + * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) + * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) + * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) + * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) + * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) + * Post: + * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) + * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) + * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) + * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) + * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) + */ + var typeofObj = typeof obj; + if (typeofObj !== 'object') { + return typeofObj; + } + + /* ! Speed optimisation + * Pre: + * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) + * Post: + * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) + */ + if (obj === null) { + return 'null'; + } + + /* ! Spec Conformance + * Test: `Object.prototype.toString.call(window)`` + * - Node === "[object global]" + * - Chrome === "[object global]" + * - Firefox === "[object Window]" + * - PhantomJS === "[object Window]" + * - Safari === "[object Window]" + * - IE 11 === "[object Window]" + * - IE Edge === "[object Window]" + * Test: `Object.prototype.toString.call(this)`` + * - Chrome Worker === "[object global]" + * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" + * - Safari Worker === "[object DedicatedWorkerGlobalScope]" + * - IE 11 Worker === "[object WorkerGlobalScope]" + * - IE Edge Worker === "[object WorkerGlobalScope]" + */ + if (obj === globalObject) { + return 'global'; + } + + /* ! Speed optimisation + * Pre: + * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) + * Post: + * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) + */ + if ( + Array.isArray(obj) && + (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) + ) { + return 'Array'; + } + + // Not caching existence of `window` and related properties due to potential + // for `window` to be unset before tests in quasi-browser environments. + if (typeof window === 'object' && window !== null) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/browsers.html#location) + * WhatWG HTML$7.7.3 - The `Location` interface + * Test: `Object.prototype.toString.call(window.location)`` + * - IE <=11 === "[object Object]" + * - IE Edge <=13 === "[object Object]" + */ + if (typeof window.location === 'object' && obj === window.location) { + return 'Location'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#document) + * WhatWG HTML$3.1.1 - The `Document` object + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * WhatWG HTML states: + * > For historical reasons, Window objects must also have a + * > writable, configurable, non-enumerable property named + * > HTMLDocument whose value is the Document interface object. + * Test: `Object.prototype.toString.call(document)`` + * - Chrome === "[object HTMLDocument]" + * - Firefox === "[object HTMLDocument]" + * - Safari === "[object HTMLDocument]" + * - IE <=10 === "[object Document]" + * - IE 11 === "[object HTMLDocument]" + * - IE Edge <=13 === "[object HTMLDocument]" + */ + if (typeof window.document === 'object' && obj === window.document) { + return 'Document'; + } + + if (typeof window.navigator === 'object') { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray + * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` + * - IE <=10 === "[object MSMimeTypesCollection]" + */ + if (typeof window.navigator.mimeTypes === 'object' && + obj === window.navigator.mimeTypes) { + return 'MimeTypeArray'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray + * Test: `Object.prototype.toString.call(navigator.plugins)`` + * - IE <=10 === "[object MSPluginsCollection]" + */ + if (typeof window.navigator.plugins === 'object' && + obj === window.navigator.plugins) { + return 'PluginArray'; + } + } + + if ((typeof window.HTMLElement === 'function' || + typeof window.HTMLElement === 'object') && + obj instanceof window.HTMLElement) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` + * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` + * - IE <=10 === "[object HTMLBlockElement]" + */ + if (obj.tagName === 'BLOCKQUOTE') { + return 'HTMLQuoteElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltabledatacellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('td')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TD') { + return 'HTMLTableDataCellElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltableheadercellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('th')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TH') { + return 'HTMLTableHeaderCellElement'; + } + } + } + + /* ! Speed optimisation + * Pre: + * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) + * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) + * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) + * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) + * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) + * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) + * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) + * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) + * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) + * Post: + * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) + * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) + * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) + * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) + * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) + * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) + * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) + * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) + * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) + */ + var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]); + if (typeof stringTag === 'string') { + return stringTag; + } + + var objPrototype = Object.getPrototypeOf(obj); + /* ! Speed optimisation + * Pre: + * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) + * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) + * Post: + * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) + * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) + */ + if (objPrototype === RegExp.prototype) { + return 'RegExp'; + } + + /* ! Speed optimisation + * Pre: + * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) + * Post: + * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) + */ + if (objPrototype === Date.prototype) { + return 'Date'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) + * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": + * Test: `Object.prototype.toString.call(Promise.resolve())`` + * - Chrome <=47 === "[object Object]" + * - Edge <=20 === "[object Object]" + * - Firefox 29-Latest === "[object Promise]" + * - Safari 7.1-Latest === "[object Promise]" + */ + if (promiseExists && objPrototype === Promise.prototype) { + return 'Promise'; + } + + /* ! Speed optimisation + * Pre: + * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) + * Post: + * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) + */ + if (setExists && objPrototype === Set.prototype) { + return 'Set'; + } + + /* ! Speed optimisation + * Pre: + * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) + * Post: + * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) + */ + if (mapExists && objPrototype === Map.prototype) { + return 'Map'; + } + + /* ! Speed optimisation + * Pre: + * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) + * Post: + * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) + */ + if (weakSetExists && objPrototype === WeakSet.prototype) { + return 'WeakSet'; + } + + /* ! Speed optimisation + * Pre: + * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) + * Post: + * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) + */ + if (weakMapExists && objPrototype === WeakMap.prototype) { + return 'WeakMap'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) + * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": + * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` + * - Edge <=13 === "[object Object]" + */ + if (dataViewExists && objPrototype === DataView.prototype) { + return 'DataView'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) + * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": + * Test: `Object.prototype.toString.call(new Map().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (mapExists && objPrototype === mapIteratorPrototype) { + return 'Map Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) + * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": + * Test: `Object.prototype.toString.call(new Set().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (setExists && objPrototype === setIteratorPrototype) { + return 'Set Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) + * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": + * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { + return 'Array Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) + * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": + * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (stringIteratorExists && objPrototype === stringIteratorPrototype) { + return 'String Iterator'; + } + + /* ! Speed optimisation + * Pre: + * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) + * Post: + * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) + */ + if (objPrototype === null) { + return 'Object'; + } + + return Object + .prototype + .toString + .call(obj) + .slice(toStringLeftSliceLength, toStringRightSliceLength); +} + +return typeDetect; + +}))); diff --git a/web/node_modules/ufo/LICENSE b/web/node_modules/ufo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e739abce461d8b2899aaec6529a4af24a417e0fc --- /dev/null +++ b/web/node_modules/ufo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pooya Parsa + +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/web/node_modules/ufo/README.md b/web/node_modules/ufo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f2a6c992980f018692d22ecb7a6fa1cdaf77f423 --- /dev/null +++ b/web/node_modules/ufo/README.md @@ -0,0 +1,436 @@ +# ufo + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![bundle][bundle-src]][bundle-href] +[![Codecov][codecov-src]][codecov-href] + +URL utils for humans. + +## Install + +Install using npm or your favourite package manager: + +Install package: + +```sh +# npm +npm install ufo + +# yarn +yarn add ufo + +# pnpm +pnpm install ufo + +# bun +bun install ufo +``` + +Import utils: + +```js +// ESM +import { normalizeURL, joinURL } from "ufo"; + +// CommonJS +const { normalizeURL, joinURL } = require("ufo"); + +// Deno +import { parseURL } from "https://unpkg.com/ufo/dist/index.mjs"; +``` + +# Utils + + + +## Encoding + +### `decode(text)` + +Decode text using `decodeURIComponent`. Returns the original text if it fails. + +### `decodePath(text)` + +Decode path section of URL (consistent with encodePath for slash encoding). + +### `decodeQueryKey(text)` + +Decodes query key (consistent with `encodeQueryKey` for plus encoding). + +### `decodeQueryValue(text)` + +Decode query value (consistent with encodeQueryValue for plus encoding). + +### `encode(text)` + +Encode characters that need to be encoded on the path, search and hash sections of the URL. + +### `encodeHash(text)` + +Encode characters that need to be encoded on the hash section of the URL. + +### `encodeHost(name)` + +Encodes hostname with punycode encoding. + +### `encodeParam(text)` + +Encode characters that need to be encoded on the path section of the URL as a param. This function encodes everything `encodePath` does plus the slash (`/`) character. + +### `encodePath(text)` + +Encode characters that need to be encoded on the path section of the URL. + +### `encodeQueryKey(text)` + +Encode characters that need to be encoded query values on the query section of the URL and also encodes the `=` character. + +### `encodeQueryValue(input)` + +Encode characters that need to be encoded query values on the query section of the URL. + +## Parsing + +### `parseAuth(input)` + +Takes a string of the form `username:password` and returns an object with the username and password decoded. + +### `parseFilename(input)` + +Parses a url and returns last segment in path as filename. + +If `{ strict: true }` is passed as the second argument, it will only return the last segment only if ending with an extension. + +**Example:** + +```js +// Result: filename.ext +parseFilename("http://example.com/path/to/filename.ext"); + +// Result: undefined +parseFilename("/path/to/.hidden-file", { strict: true }); +``` + +### `parseHost(input)` + +Takes a string, and returns an object with two properties: `hostname` and `port`. + +### `parsePath(input)` + +Splits the input string into three parts, and returns an object with those three parts. + +### `parseURL(input, defaultProto)` + +Takes a URL string and returns an object with the URL's `protocol`, `auth`, `host`, `pathname`, `search`, and `hash`. + +**Example:** + +```js +parseURL("http://foo.com/foo?test=123#token"); +// { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + +parseURL("foo.com/foo?test=123#token"); +// { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' } + +parseURL("foo.com/foo?test=123#token", "https://"); +// { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } +``` + +### `stringifyParsedURL(parsed)` + +Takes a `ParsedURL` object and returns the stringified URL. + +**Example:** + +```js +const obj = parseURL("http://foo.com/foo?test=123#token"); +obj.host = "bar.com"; + +stringifyParsedURL(obj); // "http://bar.com/foo?test=123#token" +``` + +## Qeury + +### `encodeQueryItem(key, value)` + +Encodes a pair of key and value into a url query string value. + +If the value is an array, it will be encoded as multiple key-value pairs with the same key. + +### `parseQuery(parametersString)` + +Parses and decodes a query string into an object. + +input can be a query string with or without the leading `?` + +### `stringifyQuery(query)` + +Stringfies and encodes a query object into a query string. + +## Utils + +### `cleanDoubleSlashes(input)` + +Removes double slashes from the URL. + +**Example:** + +```js +cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/" + +cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//"); +// Returns "http://example.com/analyze/http://localhost:3000/" +``` + +### `getQuery(input)` + +Parses and decods the query object of an input URL into an object. + +**Example:** + +```js +getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD"); +// { test: "123", unicode: "好" } +``` + +### `hasLeadingSlash(input)` + +Checks if the input has a leading slash. (e.g. `/foo`) + +### `hasTrailingSlash(input, respectQueryAndFragment)` + +Checks if the input has a trailing slash. + +### `isEmptyURL(url)` + +Checks if the input url is empty or `/`. + +### `isEqual(a, b, options)` + +Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences. + +You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options. +You can make encoding check strict by setting `{ encoding: true }` as options. + +**Example:** + +```js +isEqual("/foo", "foo"); // true +isEqual("foo/", "foo"); // true +isEqual("/foo bar", "/foo%20bar"); // true + +// Strict compare +isEqual("/foo", "foo", { leadingSlash: true }); // false +isEqual("foo/", "foo", { trailingSlash: true }); // false +isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false +``` + +### `isNonEmptyURL(url)` + +Checks if the input url is not empty nor `/`. + +### `isRelative(inputString)` + +Check if a path starts with `./` or `../`. + +**Example:** + +```js +isRelative("./foo"); // true +``` + +### `isSamePath(p1, p2)` + +Check two paths are equal or not. Trailing slash and encoding are normalized before comparison. + +**Example:** + +```js +isSamePath("/foo", "/foo/"); // true +``` + +### `isScriptProtocol(protocol)` + +Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols. + +### `joinURL(base)` + +Joins multiple URL segments into a single URL. + +**Example:** + +```js +joinURL("a", "/b", "/c"); // "a/b/c" +``` + +### `normalizeURL(input)` + +Normlizes inputed url: + +- Ensures url is properly encoded - Ensures pathname starts with slash - Preserves protocol/host if provided + +**Example:** + +```js +normalizeURL("test?query=123 123#hash, test"); +// Returns "test?query=123%20123#hash,%20test" + +normalizeURL("http://localhost:3000"); +// Returns "http://localhost:3000" +``` + +### `resolveURL(base)` + +Resolves multiple URL segments into a single URL. + +**Example:** + +```js +resolveURL("http://foo.com/foo?test=123#token", "bar", "baz"); +// Returns "http://foo.com/foo/bar/baz?test=123#token" +``` + +### `withBase(input, base)` + +Ensures the URL or pathname has a trailing slash. + +If input aleady start with base, it will not be added again. + +### `withFragment(input, hash)` + +Add/Replace the fragment section of the URL. + +**Example:** + +```js +withFragment("/foo", "bar"); // "/foo#bar" +withFragment("/foo#bar", "baz"); // "/foo#baz" +withFragment("/foo#bar", ""); // "/foo" +``` + +### `withHttp(input)` + +Adds or replaces url protocol to `http://`. + +**Example:** + +```js +withHttp("https://example.com"); // http://example.com +``` + +### `withHttps(input)` + +Adds or replaces url protocol to `https://`. + +**Example:** + +```js +withHttps("http://example.com"); // https://example.com +``` + +### `withLeadingSlash(input)` + +Ensures the URL or pathname has a leading slash. + +### `withoutBase(input, base)` + +Removes the base from the URL or pathname. + +If input does not start with base, it will not be removed. + +### `withoutFragment(input)` + +Removes the fragment section from the URL. + +**Example:** + +```js +withoutFragment("http://example.com/foo?q=123#bar") +// Returns "http://example.com/foo?q=123" +``` + +### `withoutLeadingSlash(input)` + +Removes leading slash from the URL or pathname. + +### `withoutTrailingSlash(input, respectQueryAndFragment)` + +Removes trailing slash from the URL or pathname. + +If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations. + +**Example:** + +```js +withoutTrailingSlash("/foo/"); // "/foo" + +withoutTrailingSlash("/path/?query=true", true); // "/path?query=true" +``` + +### `withProtocol(input, protocol)` + +Adds or Replaces protocol of the input URL. + +**Example:** + +```js +withProtocol("http://example.com", "ftp://"); // "ftp://example.com" +``` + +### `withQuery(input, query)` + +Add/Replace the query section of the URL. + +**Example:** + +```js +withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret" +``` + +### `withTrailingSlash(input, respectQueryAndFragment)` + +Ensures url ends with a trailing slash. + +If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation. + +**Example:** + +```js +withTrailingSlash("/foo"); // "/foo/" + +withTrailingSlash("/path?query=true", true); // "/path/?query=true" +``` + +### `hasProtocol(inputString, opts)` + + +### `withoutProtocol(input)` + +Removes the protocol from the input. + +**Example:** + +```js +withoutProtocol("http://example.com"); // "example.com" +``` + + + + +## License + +[MIT](./LICENSE) + +Special thanks to Eduardo San Martin Morote ([posva](https://github.com/posva)) for [encoding utilities](https://github.com/vuejs/vue-router-next/blob/v4.0.1/src/encoding.ts) + + + +[npm-version-src]: https://img.shields.io/npm/v/ufo?style=flat&colorA=18181B&colorB=F0DB4F +[npm-version-href]: https://npmjs.com/package/ufo +[npm-downloads-src]: https://img.shields.io/npm/dm/ufo?style=flat&colorA=18181B&colorB=F0DB4F +[npm-downloads-href]: https://npmjs.com/package/ufo +[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/ufo/main?style=flat&colorA=18181B&colorB=F0DB4F +[codecov-href]: https://codecov.io/gh/unjs/ufo +[bundle-src]: https://img.shields.io/bundlephobia/minzip/ufo?style=flat&colorA=18181B&colorB=F0DB4F +[bundle-href]: https://bundlephobia.com/result?p=ufo diff --git a/web/node_modules/ufo/dist/index.cjs b/web/node_modules/ufo/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..876cb176589a68eef9c41561de682253edc8abc1 --- /dev/null +++ b/web/node_modules/ufo/dist/index.cjs @@ -0,0 +1,627 @@ +'use strict'; + +const n = /[^\0-\x7E]/; +const t = /[\x2E\u3002\uFF0E\uFF61]/g; +const o = { + overflow: "Overflow Error", + "not-basic": "Illegal Input", + "invalid-input": "Invalid Input" +}; +const e = Math.floor; +const r = String.fromCharCode; +function s(n2) { + throw new RangeError(o[n2]); +} +const c = function(n2, t2) { + return n2 + 22 + 75 * (n2 < 26) - ((t2 != 0) << 5); +}; +const u = function(n2, t2, o2) { + let r2 = 0; + for (n2 = o2 ? e(n2 / 700) : n2 >> 1, n2 += e(n2 / t2); n2 > 455; r2 += 36) { + n2 = e(n2 / 35); + } + return e(r2 + 36 * n2 / (n2 + 38)); +}; +function toASCII(o2) { + return function(n2, o3) { + const e2 = n2.split("@"); + let r2 = ""; + e2.length > 1 && (r2 = e2[0] + "@", n2 = e2[1]); + const s2 = function(n3, t2) { + const o4 = []; + let e3 = n3.length; + for (; e3--; ) { + o4[e3] = t2(n3[e3]); + } + return o4; + }((n2 = n2.replace(t, ".")).split("."), o3).join("."); + return r2 + s2; + }(o2, function(t2) { + return n.test(t2) ? "xn--" + function(n2) { + const t3 = []; + const o3 = (n2 = function(n3) { + const t4 = []; + let o4 = 0; + const e2 = n3.length; + for (; o4 < e2; ) { + const r2 = n3.charCodeAt(o4++); + if (r2 >= 55296 && r2 <= 56319 && o4 < e2) { + const e3 = n3.charCodeAt(o4++); + (64512 & e3) == 56320 ? t4.push(((1023 & r2) << 10) + (1023 & e3) + 65536) : (t4.push(r2), o4--); + } else { + t4.push(r2); + } + } + return t4; + }(n2)).length; + let f = 128; + let i = 0; + let l = 72; + for (const o4 of n2) { + o4 < 128 && t3.push(r(o4)); + } + const h = t3.length; + let p = h; + for (h && t3.push("-"); p < o3; ) { + let o4 = 2147483647; + for (const t4 of n2) { + t4 >= f && t4 < o4 && (o4 = t4); + } + const a = p + 1; + o4 - f > e((2147483647 - i) / a) && s("overflow"), i += (o4 - f) * a, f = o4; + for (const o5 of n2) { + if (o5 < f && ++i > 2147483647 && s("overflow"), o5 == f) { + let n3 = i; + for (let o6 = 36; ; o6 += 36) { + const s2 = o6 <= l ? 1 : o6 >= l + 26 ? 26 : o6 - l; + if (n3 < s2) { + break; + } + const u2 = n3 - s2; + const f2 = 36 - s2; + t3.push(r(c(s2 + u2 % f2, 0))), n3 = e(u2 / f2); + } + t3.push(r(c(n3, 0))), l = u(i, a, p == h), i = 0, ++p; + } + } + ++i, ++f; + } + return t3.join(""); + }(t2) : t2; + }); +} + +const HASH_RE = /#/g; +const AMPERSAND_RE = /&/g; +const SLASH_RE = /\//g; +const EQUAL_RE = /=/g; +const IM_RE = /\?/g; +const PLUS_RE = /\+/g; +const ENC_CARET_RE = /%5e/gi; +const ENC_BACKTICK_RE = /%60/gi; +const ENC_CURLY_OPEN_RE = /%7b/gi; +const ENC_PIPE_RE = /%7c/gi; +const ENC_CURLY_CLOSE_RE = /%7d/gi; +const ENC_SPACE_RE = /%20/gi; +const ENC_SLASH_RE = /%2f/gi; +const ENC_ENC_SLASH_RE = /%252f/gi; +function encode(text) { + return encodeURI("" + text).replace(ENC_PIPE_RE, "|"); +} +function encodeHash(text) { + return encode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); +} +function encodeQueryValue(input) { + return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F"); +} +function encodeQueryKey(text) { + return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); +} +function encodePath(text) { + return encode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F").replace(AMPERSAND_RE, "%26").replace(PLUS_RE, "%2B"); +} +function encodeParam(text) { + return encodePath(text).replace(SLASH_RE, "%2F"); +} +function decode(text = "") { + try { + return decodeURIComponent("" + text); + } catch { + return "" + text; + } +} +function decodePath(text) { + return decode(text.replace(ENC_SLASH_RE, "%252F")); +} +function decodeQueryKey(text) { + return decode(text.replace(PLUS_RE, " ")); +} +function decodeQueryValue(text) { + return decode(text.replace(PLUS_RE, " ")); +} +function encodeHost(name = "") { + return toASCII(name); +} + +function parseQuery(parametersString = "") { + const object = {}; + if (parametersString[0] === "?") { + parametersString = parametersString.slice(1); + } + for (const parameter of parametersString.split("&")) { + const s = parameter.match(/([^=]+)=?(.*)/) || []; + if (s.length < 2) { + continue; + } + const key = decodeQueryKey(s[1]); + if (key === "__proto__" || key === "constructor") { + continue; + } + const value = decodeQueryValue(s[2] || ""); + if (object[key] === void 0) { + object[key] = value; + } else if (Array.isArray(object[key])) { + object[key].push(value); + } else { + object[key] = [object[key], value]; + } + } + return object; +} +function encodeQueryItem(key, value) { + if (typeof value === "number" || typeof value === "boolean") { + value = String(value); + } + if (!value) { + return encodeQueryKey(key); + } + if (Array.isArray(value)) { + return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"); + } + return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`; +} +function stringifyQuery(query) { + return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&"); +} + +const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/; +const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/; +const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/; +const PROTOCOL_SCRIPT_RE = /^[\s\0]*(blob|data|javascript|vbscript):$/i; +const TRAILING_SLASH_RE = /\/$|\/\?|\/#/; +const JOIN_LEADING_SLASH_RE = /^\.?\//; +function isRelative(inputString) { + return ["./", "../"].some((string_) => inputString.startsWith(string_)); +} +function hasProtocol(inputString, opts = {}) { + if (typeof opts === "boolean") { + opts = { acceptRelative: opts }; + } + if (opts.strict) { + return PROTOCOL_STRICT_REGEX.test(inputString); + } + return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false); +} +function isScriptProtocol(protocol) { + return !!protocol && PROTOCOL_SCRIPT_RE.test(protocol); +} +function hasTrailingSlash(input = "", respectQueryAndFragment) { + if (!respectQueryAndFragment) { + return input.endsWith("/"); + } + return TRAILING_SLASH_RE.test(input); +} +function withoutTrailingSlash(input = "", respectQueryAndFragment) { + if (!respectQueryAndFragment) { + return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/"; + } + if (!hasTrailingSlash(input, true)) { + return input || "/"; + } + let path = input; + let fragment = ""; + const fragmentIndex = input.indexOf("#"); + if (fragmentIndex >= 0) { + path = input.slice(0, fragmentIndex); + fragment = input.slice(fragmentIndex); + } + const [s0, ...s] = path.split("?"); + return (s0.slice(0, -1) || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment; +} +function withTrailingSlash(input = "", respectQueryAndFragment) { + if (!respectQueryAndFragment) { + return input.endsWith("/") ? input : input + "/"; + } + if (hasTrailingSlash(input, true)) { + return input || "/"; + } + let path = input; + let fragment = ""; + const fragmentIndex = input.indexOf("#"); + if (fragmentIndex >= 0) { + path = input.slice(0, fragmentIndex); + fragment = input.slice(fragmentIndex); + if (!path) { + return fragment; + } + } + const [s0, ...s] = path.split("?"); + return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment; +} +function hasLeadingSlash(input = "") { + return input.startsWith("/"); +} +function withoutLeadingSlash(input = "") { + return (hasLeadingSlash(input) ? input.slice(1) : input) || "/"; +} +function withLeadingSlash(input = "") { + return hasLeadingSlash(input) ? input : "/" + input; +} +function cleanDoubleSlashes(input = "") { + return input.split("://").map((string_) => string_.replace(/\/{2,}/g, "/")).join("://"); +} +function withBase(input, base) { + if (isEmptyURL(base) || hasProtocol(input)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (input.startsWith(_base)) { + return input; + } + return joinURL(_base, input); +} +function withoutBase(input, base) { + if (isEmptyURL(base)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (!input.startsWith(_base)) { + return input; + } + const trimmed = input.slice(_base.length); + return trimmed[0] === "/" ? trimmed : "/" + trimmed; +} +function withQuery(input, query) { + const parsed = parseURL(input); + const mergedQuery = { ...parseQuery(parsed.search), ...query }; + parsed.search = stringifyQuery(mergedQuery); + return stringifyParsedURL(parsed); +} +function getQuery(input) { + return parseQuery(parseURL(input).search); +} +function isEmptyURL(url) { + return !url || url === "/"; +} +function isNonEmptyURL(url) { + return url && url !== "/"; +} +function joinURL(base, ...input) { + let url = base || ""; + for (const segment of input.filter((url2) => isNonEmptyURL(url2))) { + if (url) { + const _segment = segment.replace(JOIN_LEADING_SLASH_RE, ""); + url = withTrailingSlash(url) + _segment; + } else { + url = segment; + } + } + return url; +} +function withHttp(input) { + return withProtocol(input, "http://"); +} +function withHttps(input) { + return withProtocol(input, "https://"); +} +function withoutProtocol(input) { + return withProtocol(input, ""); +} +function withProtocol(input, protocol) { + const match = input.match(PROTOCOL_REGEX); + if (!match) { + return protocol + input; + } + return protocol + input.slice(match[0].length); +} +function normalizeURL(input) { + const parsed = parseURL(input); + parsed.pathname = encodePath(decodePath(parsed.pathname)); + parsed.hash = encodeHash(decode(parsed.hash)); + parsed.host = encodeHost(decode(parsed.host)); + parsed.search = stringifyQuery(parseQuery(parsed.search)); + return stringifyParsedURL(parsed); +} +function resolveURL(base = "", ...inputs) { + if (typeof base !== "string") { + throw new TypeError( + `URL input should be string received ${typeof base} (${base})` + ); + } + const filteredInputs = inputs.filter((input) => isNonEmptyURL(input)); + if (filteredInputs.length === 0) { + return base; + } + const url = parseURL(base); + for (const inputSegment of filteredInputs) { + const urlSegment = parseURL(inputSegment); + if (urlSegment.pathname) { + url.pathname = withTrailingSlash(url.pathname) + withoutLeadingSlash(urlSegment.pathname); + } + if (urlSegment.hash && urlSegment.hash !== "#") { + url.hash = urlSegment.hash; + } + if (urlSegment.search && urlSegment.search !== "?") { + if (url.search && url.search !== "?") { + const queryString = stringifyQuery({ + ...parseQuery(url.search), + ...parseQuery(urlSegment.search) + }); + url.search = queryString.length > 0 ? "?" + queryString : ""; + } else { + url.search = urlSegment.search; + } + } + } + return stringifyParsedURL(url); +} +function isSamePath(p1, p2) { + return decode(withoutTrailingSlash(p1)) === decode(withoutTrailingSlash(p2)); +} +function isEqual(a, b, options = {}) { + if (!options.trailingSlash) { + a = withTrailingSlash(a); + b = withTrailingSlash(b); + } + if (!options.leadingSlash) { + a = withLeadingSlash(a); + b = withLeadingSlash(b); + } + if (!options.encoding) { + a = decode(a); + b = decode(b); + } + return a === b; +} +function withFragment(input, hash) { + if (!hash || hash === "#") { + return input; + } + const parsed = parseURL(input); + parsed.hash = hash === "" ? "" : "#" + encodeHash(hash); + return stringifyParsedURL(parsed); +} +function withoutFragment(input) { + return stringifyParsedURL({ ...parseURL(input), hash: "" }); +} + +const protocolRelative = Symbol.for("ufo:protocolRelative"); +function parseURL(input = "", defaultProto) { + const _specialProtoMatch = input.match( + /^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i + ); + if (_specialProtoMatch) { + const [, _proto, _pathname = ""] = _specialProtoMatch; + return { + protocol: _proto.toLowerCase(), + pathname: _pathname, + href: _proto + _pathname, + auth: "", + host: "", + search: "", + hash: "" + }; + } + if (!hasProtocol(input, { acceptRelative: true })) { + return defaultProto ? parseURL(defaultProto + input) : parsePath(input); + } + const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || []; + const [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || []; + const { pathname, search, hash } = parsePath( + path.replace(/\/(?=[A-Za-z]:)/, "") + ); + return { + protocol: protocol.toLowerCase(), + auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "", + host, + pathname, + search, + hash, + [protocolRelative]: !protocol + }; +} +function parsePath(input = "") { + const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1); + return { + pathname, + search, + hash + }; +} +function parseAuth(input = "") { + const [username, password] = input.split(":"); + return { + username: decode(username), + password: decode(password) + }; +} +function parseHost(input = "") { + const [hostname, port] = (input.match(/([^/:]*):?(\d+)?/) || []).splice(1); + return { + hostname: decode(hostname), + port + }; +} +function stringifyParsedURL(parsed) { + const pathname = parsed.pathname || ""; + const search = parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : ""; + const hash = parsed.hash || ""; + const auth = parsed.auth ? parsed.auth + "@" : ""; + const host = parsed.host || ""; + const proto = parsed.protocol || parsed[protocolRelative] ? (parsed.protocol || "") + "//" : ""; + return proto + auth + host + pathname + search + hash; +} +const FILENAME_STRICT_REGEX = /\/([^/]+\.[^/]+)$/; +const FILENAME_REGEX = /\/([^/]+)$/; +function parseFilename(input = "", { strict }) { + const { pathname } = parseURL(input); + const matches = strict ? pathname.match(FILENAME_STRICT_REGEX) : pathname.match(FILENAME_REGEX); + return matches ? matches[1] : void 0; +} + +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +class $URL { + constructor(input = "") { + __publicField(this, "protocol"); + __publicField(this, "host"); + __publicField(this, "auth"); + __publicField(this, "pathname"); + __publicField(this, "query", {}); + __publicField(this, "hash"); + if (typeof input !== "string") { + throw new TypeError( + `URL input should be string received ${typeof input} (${input})` + ); + } + const parsed = parseURL(input); + this.protocol = decode(parsed.protocol); + this.host = decode(parsed.host); + this.auth = decode(parsed.auth); + this.pathname = decodePath(parsed.pathname); + this.query = parseQuery(parsed.search); + this.hash = decode(parsed.hash); + } + get hostname() { + return parseHost(this.host).hostname; + } + get port() { + return parseHost(this.host).port || ""; + } + get username() { + return parseAuth(this.auth).username; + } + get password() { + return parseAuth(this.auth).password || ""; + } + get hasProtocol() { + return this.protocol.length; + } + get isAbsolute() { + return this.hasProtocol || this.pathname[0] === "/"; + } + get search() { + const q = stringifyQuery(this.query); + return q.length > 0 ? "?" + q : ""; + } + get searchParams() { + const p = new URLSearchParams(); + for (const name in this.query) { + const value = this.query[name]; + if (Array.isArray(value)) { + for (const v of value) { + p.append(name, v); + } + } else { + p.append( + name, + typeof value === "string" ? value : JSON.stringify(value) + ); + } + } + return p; + } + get origin() { + return (this.protocol ? this.protocol + "//" : "") + encodeHost(this.host); + } + get fullpath() { + return encodePath(this.pathname) + this.search + encodeHash(this.hash); + } + get encodedAuth() { + if (!this.auth) { + return ""; + } + const { username, password } = parseAuth(this.auth); + return encodeURIComponent(username) + (password ? ":" + encodeURIComponent(password) : ""); + } + get href() { + const auth = this.encodedAuth; + const originWithAuth = (this.protocol ? this.protocol + "//" : "") + (auth ? auth + "@" : "") + encodeHost(this.host); + return this.hasProtocol && this.isAbsolute ? originWithAuth + this.fullpath : this.fullpath; + } + append(url) { + if (url.hasProtocol) { + throw new Error("Cannot append a URL with protocol"); + } + Object.assign(this.query, url.query); + if (url.pathname) { + this.pathname = withTrailingSlash(this.pathname) + withoutLeadingSlash(url.pathname); + } + if (url.hash) { + this.hash = url.hash; + } + } + toJSON() { + return this.href; + } + toString() { + return this.href; + } +} +function createURL(input) { + return new $URL(input); +} + +exports.$URL = $URL; +exports.cleanDoubleSlashes = cleanDoubleSlashes; +exports.createURL = createURL; +exports.decode = decode; +exports.decodePath = decodePath; +exports.decodeQueryKey = decodeQueryKey; +exports.decodeQueryValue = decodeQueryValue; +exports.encode = encode; +exports.encodeHash = encodeHash; +exports.encodeHost = encodeHost; +exports.encodeParam = encodeParam; +exports.encodePath = encodePath; +exports.encodeQueryItem = encodeQueryItem; +exports.encodeQueryKey = encodeQueryKey; +exports.encodeQueryValue = encodeQueryValue; +exports.getQuery = getQuery; +exports.hasLeadingSlash = hasLeadingSlash; +exports.hasProtocol = hasProtocol; +exports.hasTrailingSlash = hasTrailingSlash; +exports.isEmptyURL = isEmptyURL; +exports.isEqual = isEqual; +exports.isNonEmptyURL = isNonEmptyURL; +exports.isRelative = isRelative; +exports.isSamePath = isSamePath; +exports.isScriptProtocol = isScriptProtocol; +exports.joinURL = joinURL; +exports.normalizeURL = normalizeURL; +exports.parseAuth = parseAuth; +exports.parseFilename = parseFilename; +exports.parseHost = parseHost; +exports.parsePath = parsePath; +exports.parseQuery = parseQuery; +exports.parseURL = parseURL; +exports.resolveURL = resolveURL; +exports.stringifyParsedURL = stringifyParsedURL; +exports.stringifyQuery = stringifyQuery; +exports.withBase = withBase; +exports.withFragment = withFragment; +exports.withHttp = withHttp; +exports.withHttps = withHttps; +exports.withLeadingSlash = withLeadingSlash; +exports.withProtocol = withProtocol; +exports.withQuery = withQuery; +exports.withTrailingSlash = withTrailingSlash; +exports.withoutBase = withoutBase; +exports.withoutFragment = withoutFragment; +exports.withoutLeadingSlash = withoutLeadingSlash; +exports.withoutProtocol = withoutProtocol; +exports.withoutTrailingSlash = withoutTrailingSlash; diff --git a/web/node_modules/ufo/dist/index.d.cts b/web/node_modules/ufo/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..08437aa6e53f367c3b171c09a193dc5f527199f4 --- /dev/null +++ b/web/node_modules/ufo/dist/index.d.cts @@ -0,0 +1,584 @@ +type QueryValue = string | number | undefined | null | boolean | Array | Record; +type QueryObject = Record; +type ParsedQuery = Record; +/** + * Parses and decodes a query string into an object. + * + * input can be a query string with or without the leading `?` + * + * @note + * The `__proto__` and `constructor` keys are ignored to prevent prototype pollution. + * + * @group qeury + */ +declare function parseQuery(parametersString?: string): T; +/** + * Encodes a pair of key and value into a url query string value. + * + * If the value is an array, it will be encoded as multiple key-value pairs with the same key. + * + * @group qeury + */ +declare function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string; +/** + * Stringfies and encodes a query object into a query string. + * + * @group qeury + */ +declare function stringifyQuery(query: QueryObject): string; + +/** + * Encode characters that need to be encoded on the path, search and hash + * sections of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encode(text: string | number): string; +/** + * Encode characters that need to be encoded on the hash section of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeHash(text: string): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL. + * + * @group encoding + * + * @param input - string to encode + * @returns encoded string + */ +declare function encodeQueryValue(input: QueryValue): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL and also encodes the `=` character. + * + * @group encoding + * + * @param text - string to encode + */ +declare function encodeQueryKey(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodePath(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL as a + * param. This function encodes everything `encodePath` does plus the + * slash (`/`) character. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeParam(text: string | number): string; +/** + * Decode text using `decodeURIComponent`. Returns the original text if it + * fails. + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decode(text?: string | number): string; +/** + * Decode path section of URL (consistent with encodePath for slash encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodePath(text: string): string; +/** + * Decodes query key (consistent with `encodeQueryKey` for plus encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryKey(text: string): string; +/** + * Decode query value (consistent with encodeQueryValue for plus encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryValue(text: string): string; +/** + * Encodes hostname with punycode encoding. + * + * @group encoding + */ +declare function encodeHost(name?: string): string; + +declare const protocolRelative: unique symbol; +interface ParsedURL { + protocol?: string; + host?: string; + auth?: string; + href?: string; + pathname: string; + hash: string; + search: string; + [protocolRelative]?: boolean; +} +interface ParsedAuth { + username: string; + password: string; +} +interface ParsedHost { + hostname: string; + port: string; +} +/** + * Takes a URL string and returns an object with the URL's `protocol`, `auth`, `host`, `pathname`, `search`, and `hash`. + * + * @example + * + * ```js + * parseURL("http://foo.com/foo?test=123#token"); + * // { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + * + * parseURL("foo.com/foo?test=123#token"); + * // { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' } + * + * parseURL("foo.com/foo?test=123#token", "https://"); + * // { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + * ``` + * + * @group parsing + * + * @param [input] - The URL to parse. + * @param [defaultProto] - The default protocol to use if the input doesn't have one. + * @returns A parsed URL object. + */ +declare function parseURL(input?: string, defaultProto?: string): ParsedURL; +/** + * Splits the input string into three parts, and returns an object with those three parts. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns An object with three properties: `pathname`, `search`, and `hash`. + */ +declare function parsePath(input?: string): ParsedURL; +/** + * Takes a string of the form `username:password` and returns an object with the username and + * password decoded. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns An object with two properties: username and password. + */ +declare function parseAuth(input?: string): ParsedAuth; +/** + * Takes a string, and returns an object with two properties: `hostname` and `port`. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns A function that takes a string and returns an object with two properties: `hostname` and + * `port`. + */ +declare function parseHost(input?: string): ParsedHost; +/** + * Takes a `ParsedURL` object and returns the stringified URL. + * + * @group parsing + * + * @example + * + * ```js + * const obj = parseURL("http://foo.com/foo?test=123#token"); + * obj.host = "bar.com"; + * + * stringifyParsedURL(obj); // "http://bar.com/foo?test=123#token" + * ``` + * + * @param [parsed] - The parsed URL + * @returns A stringified URL. + */ +declare function stringifyParsedURL(parsed: Partial): string; +/** + * Parses a url and returns last segment in path as filename. + * + * If `{ strict: true }` is passed as the second argument, it will only return the last segment only if ending with an extension. + * + * @group parsing + * + * @example + * + * ```js + * // Result: filename.ext + * parseFilename("http://example.com/path/to/filename.ext"); + * + * // Result: undefined + * parseFilename("/path/to/.hidden-file", { strict: true }); + * ``` + */ +declare function parseFilename(input: string, { strict }: { + strict: any; +}): string | undefined; + +/** + * @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)` + */ +declare class $URL implements URL { + protocol: string; + host: string; + auth: string; + pathname: string; + query: QueryObject; + hash: string; + constructor(input?: string); + get hostname(): string; + get port(): string; + get username(): string; + get password(): string; + get hasProtocol(): number; + get isAbsolute(): number | boolean; + get search(): string; + get searchParams(): URLSearchParams; + get origin(): string; + get fullpath(): string; + get encodedAuth(): string; + get href(): string; + append(url: $URL): void; + toJSON(): string; + toString(): string; +} +/** + * @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)` + */ +declare function createURL(input: string): $URL; + +/** + * Check if a path starts with `./` or `../`. + * + * @example + * ```js + * isRelative("./foo"); // true + * ``` + * + * @group utils + */ +declare function isRelative(inputString: string): boolean; +interface HasProtocolOptions { + acceptRelative?: boolean; + strict?: boolean; +} +/** + * Checks if the input has a protocol. + * + * You can use `{ acceptRelative: true }` to accept relative URLs as valid protocol. + * + * @group utils + */ +declare function hasProtocol(inputString: string, opts?: HasProtocolOptions): boolean; +/** @deprecated Same as { hasProtocol(inputString, { acceptRelative: true }) */ +declare function hasProtocol(inputString: string, acceptRelative: boolean): boolean; +/** + * Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols. + * + * @group utils + */ +declare function isScriptProtocol(protocol?: string): boolean; +/** + * Checks if the input has a trailing slash. + * + * @group utils + */ +declare function hasTrailingSlash(input?: string, respectQueryAndFragment?: boolean): boolean; +/** + * Removes trailing slash from the URL or pathname. + * + * If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations. + * + * @example + * + * ```js + * withoutTrailingSlash("/foo/"); // "/foo" + * + * withoutTrailingSlash("/path/?query=true", true); // "/path?query=true" + * ``` + * + * @group utils + */ +declare function withoutTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string; +/** + * Ensures url ends with a trailing slash. + * + * If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation. + * + * @example + * + * ```js + * withTrailingSlash("/foo"); // "/foo/" + * + * withTrailingSlash("/path?query=true", true); // "/path/?query=true" + * ``` + * + * @group utils + */ +declare function withTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string; +/** + * Checks if the input has a leading slash. (e.g. `/foo`) + * + * @group utils + */ +declare function hasLeadingSlash(input?: string): boolean; +/** + * Removes leading slash from the URL or pathname. + * + * @group utils + */ +declare function withoutLeadingSlash(input?: string): string; +/** + * Ensures the URL or pathname has a leading slash. + * + * @group utils + */ +declare function withLeadingSlash(input?: string): string; +/** + * Removes double slashes from the URL. + * + * @example + * + * ```js + * cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/" + * + * cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//"); + * // Returns "http://example.com/analyze/http://localhost:3000/" + * ``` + * + * @group utils + */ +declare function cleanDoubleSlashes(input?: string): string; +/** + * Ensures the URL or pathname has a trailing slash. + * + * If input aleady start with base, it will not be added again. + * + * @group utils + */ +declare function withBase(input: string, base: string): string; +/** + * Removes the base from the URL or pathname. + * + * If input does not start with base, it will not be removed. + * + * @group utils + */ +declare function withoutBase(input: string, base: string): string; +/** + * Add/Replace the query section of the URL. + * + * @example + * + * ```js + * withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret" + * ``` + * + * @group utils + */ +declare function withQuery(input: string, query: QueryObject): string; +/** + * Parses and decods the query object of an input URL into an object. + * + * @example + * + * ```js + * getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD"); + * // { test: "123", unicode: "好" } + * ``` + * @group utils + */ +declare function getQuery(input: string): T; +/** + * Checks if the input url is empty or `/`. + * + * @group utils + */ +declare function isEmptyURL(url: string): boolean; +/** + * Checks if the input url is not empty nor `/`. + * + * @group utils + */ +declare function isNonEmptyURL(url: string): boolean; +/** + * Joins multiple URL segments into a single URL. + * + * @example + * + * ```js + * joinURL("a", "/b", "/c"); // "a/b/c" + * ``` + * + * @group utils + */ +declare function joinURL(base: string, ...input: string[]): string; +/** + * Adds or replaces url protocol to `http://`. + * + * @example + * + * ```js + * withHttp("https://example.com"); // http://example.com + * ``` + * + * @group utils + */ +declare function withHttp(input: string): string; +/** + * Adds or replaces url protocol to `https://`. + * + * @example + * + * ```js + * withHttps("http://example.com"); // https://example.com + * ``` + * + * @group utils + */ +declare function withHttps(input: string): string; +/** + * Removes the protocol from the input. + * + * @example + * ```js + * withoutProtocol("http://example.com"); // "example.com" + * ``` + */ +declare function withoutProtocol(input: string): string; +/** + * Adds or Replaces protocol of the input URL. + * + * @example + * ```js + * withProtocol("http://example.com", "ftp://"); // "ftp://example.com" + * ``` + * + * @group utils + */ +declare function withProtocol(input: string, protocol: string): string; +/** + * Normlizes inputed url: + * + * - Ensures url is properly encoded + * - Ensures pathname starts with slash + * - Preserves protocol/host if provided + * + * @example + * + * ```js + * normalizeURL("test?query=123 123#hash, test"); + * // Returns "test?query=123%20123#hash,%20test" + * + * normalizeURL("http://localhost:3000"); + * // Returns "http://localhost:3000" + * ``` + * + * @group utils + */ +declare function normalizeURL(input: string): string; +/** + * Resolves multiple URL segments into a single URL. + * + * @example + * + * ```js + * resolveURL("http://foo.com/foo?test=123#token", "bar", "baz"); + * // Returns "http://foo.com/foo/bar/baz?test=123#token" + * ``` + * + * @group utils + */ +declare function resolveURL(base?: string, ...inputs: string[]): string; +/** + * Check two paths are equal or not. Trailing slash and encoding are normalized before comparison. + * + * @example + * ```js + * isSamePath("/foo", "/foo/"); // true + * ``` + * + * @group utils + */ +declare function isSamePath(p1: string, p2: string): boolean; +interface CompareURLOptions { + trailingSlash?: boolean; + leadingSlash?: boolean; + encoding?: boolean; +} +/** + * Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences. + * + * You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options. + * + * You can make encoding check strict by setting `{ encoding: true }` as options. + * + * @example + * + * ```js + * isEqual("/foo", "foo"); // true + * isEqual("foo/", "foo"); // true + * isEqual("/foo bar", "/foo%20bar"); // true + * + * // Strict compare + * isEqual("/foo", "foo", { leadingSlash: true }); // false + * isEqual("foo/", "foo", { trailingSlash: true }); // false + * isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false + * ``` + * + * @group utils + */ +declare function isEqual(a: string, b: string, options?: CompareURLOptions): boolean; +/** + * Add/Replace the fragment section of the URL. + * + * @example + * + * ```js + * withFragment("/foo", "bar"); // "/foo#bar" + * withFragment("/foo#bar", "baz"); // "/foo#baz" + * withFragment("/foo#bar", ""); // "/foo" + * ``` + * + * @group utils + */ +declare function withFragment(input: string, hash: string): string; +/** + * Removes the fragment section from the URL. + * + * @example + * + * ```js + * withoutFragment("http://example.com/foo?q=123#bar") + * // Returns "http://example.com/foo?q=123" + * ``` + * + * @group utils + */ +declare function withoutFragment(input: string): string; + +export { $URL, type HasProtocolOptions, type ParsedAuth, type ParsedHost, type ParsedQuery, type ParsedURL, type QueryObject, type QueryValue, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryKey, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, isScriptProtocol, joinURL, normalizeURL, parseAuth, parseFilename, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withFragment, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutFragment, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash }; diff --git a/web/node_modules/ufo/dist/index.d.mts b/web/node_modules/ufo/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..08437aa6e53f367c3b171c09a193dc5f527199f4 --- /dev/null +++ b/web/node_modules/ufo/dist/index.d.mts @@ -0,0 +1,584 @@ +type QueryValue = string | number | undefined | null | boolean | Array | Record; +type QueryObject = Record; +type ParsedQuery = Record; +/** + * Parses and decodes a query string into an object. + * + * input can be a query string with or without the leading `?` + * + * @note + * The `__proto__` and `constructor` keys are ignored to prevent prototype pollution. + * + * @group qeury + */ +declare function parseQuery(parametersString?: string): T; +/** + * Encodes a pair of key and value into a url query string value. + * + * If the value is an array, it will be encoded as multiple key-value pairs with the same key. + * + * @group qeury + */ +declare function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string; +/** + * Stringfies and encodes a query object into a query string. + * + * @group qeury + */ +declare function stringifyQuery(query: QueryObject): string; + +/** + * Encode characters that need to be encoded on the path, search and hash + * sections of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encode(text: string | number): string; +/** + * Encode characters that need to be encoded on the hash section of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeHash(text: string): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL. + * + * @group encoding + * + * @param input - string to encode + * @returns encoded string + */ +declare function encodeQueryValue(input: QueryValue): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL and also encodes the `=` character. + * + * @group encoding + * + * @param text - string to encode + */ +declare function encodeQueryKey(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodePath(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL as a + * param. This function encodes everything `encodePath` does plus the + * slash (`/`) character. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeParam(text: string | number): string; +/** + * Decode text using `decodeURIComponent`. Returns the original text if it + * fails. + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decode(text?: string | number): string; +/** + * Decode path section of URL (consistent with encodePath for slash encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodePath(text: string): string; +/** + * Decodes query key (consistent with `encodeQueryKey` for plus encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryKey(text: string): string; +/** + * Decode query value (consistent with encodeQueryValue for plus encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryValue(text: string): string; +/** + * Encodes hostname with punycode encoding. + * + * @group encoding + */ +declare function encodeHost(name?: string): string; + +declare const protocolRelative: unique symbol; +interface ParsedURL { + protocol?: string; + host?: string; + auth?: string; + href?: string; + pathname: string; + hash: string; + search: string; + [protocolRelative]?: boolean; +} +interface ParsedAuth { + username: string; + password: string; +} +interface ParsedHost { + hostname: string; + port: string; +} +/** + * Takes a URL string and returns an object with the URL's `protocol`, `auth`, `host`, `pathname`, `search`, and `hash`. + * + * @example + * + * ```js + * parseURL("http://foo.com/foo?test=123#token"); + * // { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + * + * parseURL("foo.com/foo?test=123#token"); + * // { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' } + * + * parseURL("foo.com/foo?test=123#token", "https://"); + * // { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + * ``` + * + * @group parsing + * + * @param [input] - The URL to parse. + * @param [defaultProto] - The default protocol to use if the input doesn't have one. + * @returns A parsed URL object. + */ +declare function parseURL(input?: string, defaultProto?: string): ParsedURL; +/** + * Splits the input string into three parts, and returns an object with those three parts. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns An object with three properties: `pathname`, `search`, and `hash`. + */ +declare function parsePath(input?: string): ParsedURL; +/** + * Takes a string of the form `username:password` and returns an object with the username and + * password decoded. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns An object with two properties: username and password. + */ +declare function parseAuth(input?: string): ParsedAuth; +/** + * Takes a string, and returns an object with two properties: `hostname` and `port`. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns A function that takes a string and returns an object with two properties: `hostname` and + * `port`. + */ +declare function parseHost(input?: string): ParsedHost; +/** + * Takes a `ParsedURL` object and returns the stringified URL. + * + * @group parsing + * + * @example + * + * ```js + * const obj = parseURL("http://foo.com/foo?test=123#token"); + * obj.host = "bar.com"; + * + * stringifyParsedURL(obj); // "http://bar.com/foo?test=123#token" + * ``` + * + * @param [parsed] - The parsed URL + * @returns A stringified URL. + */ +declare function stringifyParsedURL(parsed: Partial): string; +/** + * Parses a url and returns last segment in path as filename. + * + * If `{ strict: true }` is passed as the second argument, it will only return the last segment only if ending with an extension. + * + * @group parsing + * + * @example + * + * ```js + * // Result: filename.ext + * parseFilename("http://example.com/path/to/filename.ext"); + * + * // Result: undefined + * parseFilename("/path/to/.hidden-file", { strict: true }); + * ``` + */ +declare function parseFilename(input: string, { strict }: { + strict: any; +}): string | undefined; + +/** + * @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)` + */ +declare class $URL implements URL { + protocol: string; + host: string; + auth: string; + pathname: string; + query: QueryObject; + hash: string; + constructor(input?: string); + get hostname(): string; + get port(): string; + get username(): string; + get password(): string; + get hasProtocol(): number; + get isAbsolute(): number | boolean; + get search(): string; + get searchParams(): URLSearchParams; + get origin(): string; + get fullpath(): string; + get encodedAuth(): string; + get href(): string; + append(url: $URL): void; + toJSON(): string; + toString(): string; +} +/** + * @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)` + */ +declare function createURL(input: string): $URL; + +/** + * Check if a path starts with `./` or `../`. + * + * @example + * ```js + * isRelative("./foo"); // true + * ``` + * + * @group utils + */ +declare function isRelative(inputString: string): boolean; +interface HasProtocolOptions { + acceptRelative?: boolean; + strict?: boolean; +} +/** + * Checks if the input has a protocol. + * + * You can use `{ acceptRelative: true }` to accept relative URLs as valid protocol. + * + * @group utils + */ +declare function hasProtocol(inputString: string, opts?: HasProtocolOptions): boolean; +/** @deprecated Same as { hasProtocol(inputString, { acceptRelative: true }) */ +declare function hasProtocol(inputString: string, acceptRelative: boolean): boolean; +/** + * Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols. + * + * @group utils + */ +declare function isScriptProtocol(protocol?: string): boolean; +/** + * Checks if the input has a trailing slash. + * + * @group utils + */ +declare function hasTrailingSlash(input?: string, respectQueryAndFragment?: boolean): boolean; +/** + * Removes trailing slash from the URL or pathname. + * + * If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations. + * + * @example + * + * ```js + * withoutTrailingSlash("/foo/"); // "/foo" + * + * withoutTrailingSlash("/path/?query=true", true); // "/path?query=true" + * ``` + * + * @group utils + */ +declare function withoutTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string; +/** + * Ensures url ends with a trailing slash. + * + * If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation. + * + * @example + * + * ```js + * withTrailingSlash("/foo"); // "/foo/" + * + * withTrailingSlash("/path?query=true", true); // "/path/?query=true" + * ``` + * + * @group utils + */ +declare function withTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string; +/** + * Checks if the input has a leading slash. (e.g. `/foo`) + * + * @group utils + */ +declare function hasLeadingSlash(input?: string): boolean; +/** + * Removes leading slash from the URL or pathname. + * + * @group utils + */ +declare function withoutLeadingSlash(input?: string): string; +/** + * Ensures the URL or pathname has a leading slash. + * + * @group utils + */ +declare function withLeadingSlash(input?: string): string; +/** + * Removes double slashes from the URL. + * + * @example + * + * ```js + * cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/" + * + * cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//"); + * // Returns "http://example.com/analyze/http://localhost:3000/" + * ``` + * + * @group utils + */ +declare function cleanDoubleSlashes(input?: string): string; +/** + * Ensures the URL or pathname has a trailing slash. + * + * If input aleady start with base, it will not be added again. + * + * @group utils + */ +declare function withBase(input: string, base: string): string; +/** + * Removes the base from the URL or pathname. + * + * If input does not start with base, it will not be removed. + * + * @group utils + */ +declare function withoutBase(input: string, base: string): string; +/** + * Add/Replace the query section of the URL. + * + * @example + * + * ```js + * withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret" + * ``` + * + * @group utils + */ +declare function withQuery(input: string, query: QueryObject): string; +/** + * Parses and decods the query object of an input URL into an object. + * + * @example + * + * ```js + * getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD"); + * // { test: "123", unicode: "好" } + * ``` + * @group utils + */ +declare function getQuery(input: string): T; +/** + * Checks if the input url is empty or `/`. + * + * @group utils + */ +declare function isEmptyURL(url: string): boolean; +/** + * Checks if the input url is not empty nor `/`. + * + * @group utils + */ +declare function isNonEmptyURL(url: string): boolean; +/** + * Joins multiple URL segments into a single URL. + * + * @example + * + * ```js + * joinURL("a", "/b", "/c"); // "a/b/c" + * ``` + * + * @group utils + */ +declare function joinURL(base: string, ...input: string[]): string; +/** + * Adds or replaces url protocol to `http://`. + * + * @example + * + * ```js + * withHttp("https://example.com"); // http://example.com + * ``` + * + * @group utils + */ +declare function withHttp(input: string): string; +/** + * Adds or replaces url protocol to `https://`. + * + * @example + * + * ```js + * withHttps("http://example.com"); // https://example.com + * ``` + * + * @group utils + */ +declare function withHttps(input: string): string; +/** + * Removes the protocol from the input. + * + * @example + * ```js + * withoutProtocol("http://example.com"); // "example.com" + * ``` + */ +declare function withoutProtocol(input: string): string; +/** + * Adds or Replaces protocol of the input URL. + * + * @example + * ```js + * withProtocol("http://example.com", "ftp://"); // "ftp://example.com" + * ``` + * + * @group utils + */ +declare function withProtocol(input: string, protocol: string): string; +/** + * Normlizes inputed url: + * + * - Ensures url is properly encoded + * - Ensures pathname starts with slash + * - Preserves protocol/host if provided + * + * @example + * + * ```js + * normalizeURL("test?query=123 123#hash, test"); + * // Returns "test?query=123%20123#hash,%20test" + * + * normalizeURL("http://localhost:3000"); + * // Returns "http://localhost:3000" + * ``` + * + * @group utils + */ +declare function normalizeURL(input: string): string; +/** + * Resolves multiple URL segments into a single URL. + * + * @example + * + * ```js + * resolveURL("http://foo.com/foo?test=123#token", "bar", "baz"); + * // Returns "http://foo.com/foo/bar/baz?test=123#token" + * ``` + * + * @group utils + */ +declare function resolveURL(base?: string, ...inputs: string[]): string; +/** + * Check two paths are equal or not. Trailing slash and encoding are normalized before comparison. + * + * @example + * ```js + * isSamePath("/foo", "/foo/"); // true + * ``` + * + * @group utils + */ +declare function isSamePath(p1: string, p2: string): boolean; +interface CompareURLOptions { + trailingSlash?: boolean; + leadingSlash?: boolean; + encoding?: boolean; +} +/** + * Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences. + * + * You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options. + * + * You can make encoding check strict by setting `{ encoding: true }` as options. + * + * @example + * + * ```js + * isEqual("/foo", "foo"); // true + * isEqual("foo/", "foo"); // true + * isEqual("/foo bar", "/foo%20bar"); // true + * + * // Strict compare + * isEqual("/foo", "foo", { leadingSlash: true }); // false + * isEqual("foo/", "foo", { trailingSlash: true }); // false + * isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false + * ``` + * + * @group utils + */ +declare function isEqual(a: string, b: string, options?: CompareURLOptions): boolean; +/** + * Add/Replace the fragment section of the URL. + * + * @example + * + * ```js + * withFragment("/foo", "bar"); // "/foo#bar" + * withFragment("/foo#bar", "baz"); // "/foo#baz" + * withFragment("/foo#bar", ""); // "/foo" + * ``` + * + * @group utils + */ +declare function withFragment(input: string, hash: string): string; +/** + * Removes the fragment section from the URL. + * + * @example + * + * ```js + * withoutFragment("http://example.com/foo?q=123#bar") + * // Returns "http://example.com/foo?q=123" + * ``` + * + * @group utils + */ +declare function withoutFragment(input: string): string; + +export { $URL, type HasProtocolOptions, type ParsedAuth, type ParsedHost, type ParsedQuery, type ParsedURL, type QueryObject, type QueryValue, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryKey, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, isScriptProtocol, joinURL, normalizeURL, parseAuth, parseFilename, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withFragment, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutFragment, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash }; diff --git a/web/node_modules/ufo/dist/index.d.ts b/web/node_modules/ufo/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..08437aa6e53f367c3b171c09a193dc5f527199f4 --- /dev/null +++ b/web/node_modules/ufo/dist/index.d.ts @@ -0,0 +1,584 @@ +type QueryValue = string | number | undefined | null | boolean | Array | Record; +type QueryObject = Record; +type ParsedQuery = Record; +/** + * Parses and decodes a query string into an object. + * + * input can be a query string with or without the leading `?` + * + * @note + * The `__proto__` and `constructor` keys are ignored to prevent prototype pollution. + * + * @group qeury + */ +declare function parseQuery(parametersString?: string): T; +/** + * Encodes a pair of key and value into a url query string value. + * + * If the value is an array, it will be encoded as multiple key-value pairs with the same key. + * + * @group qeury + */ +declare function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string; +/** + * Stringfies and encodes a query object into a query string. + * + * @group qeury + */ +declare function stringifyQuery(query: QueryObject): string; + +/** + * Encode characters that need to be encoded on the path, search and hash + * sections of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encode(text: string | number): string; +/** + * Encode characters that need to be encoded on the hash section of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeHash(text: string): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL. + * + * @group encoding + * + * @param input - string to encode + * @returns encoded string + */ +declare function encodeQueryValue(input: QueryValue): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL and also encodes the `=` character. + * + * @group encoding + * + * @param text - string to encode + */ +declare function encodeQueryKey(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodePath(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL as a + * param. This function encodes everything `encodePath` does plus the + * slash (`/`) character. + * + * @group encoding + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeParam(text: string | number): string; +/** + * Decode text using `decodeURIComponent`. Returns the original text if it + * fails. + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decode(text?: string | number): string; +/** + * Decode path section of URL (consistent with encodePath for slash encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodePath(text: string): string; +/** + * Decodes query key (consistent with `encodeQueryKey` for plus encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryKey(text: string): string; +/** + * Decode query value (consistent with encodeQueryValue for plus encoding). + * + * @group encoding + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryValue(text: string): string; +/** + * Encodes hostname with punycode encoding. + * + * @group encoding + */ +declare function encodeHost(name?: string): string; + +declare const protocolRelative: unique symbol; +interface ParsedURL { + protocol?: string; + host?: string; + auth?: string; + href?: string; + pathname: string; + hash: string; + search: string; + [protocolRelative]?: boolean; +} +interface ParsedAuth { + username: string; + password: string; +} +interface ParsedHost { + hostname: string; + port: string; +} +/** + * Takes a URL string and returns an object with the URL's `protocol`, `auth`, `host`, `pathname`, `search`, and `hash`. + * + * @example + * + * ```js + * parseURL("http://foo.com/foo?test=123#token"); + * // { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + * + * parseURL("foo.com/foo?test=123#token"); + * // { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' } + * + * parseURL("foo.com/foo?test=123#token", "https://"); + * // { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } + * ``` + * + * @group parsing + * + * @param [input] - The URL to parse. + * @param [defaultProto] - The default protocol to use if the input doesn't have one. + * @returns A parsed URL object. + */ +declare function parseURL(input?: string, defaultProto?: string): ParsedURL; +/** + * Splits the input string into three parts, and returns an object with those three parts. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns An object with three properties: `pathname`, `search`, and `hash`. + */ +declare function parsePath(input?: string): ParsedURL; +/** + * Takes a string of the form `username:password` and returns an object with the username and + * password decoded. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns An object with two properties: username and password. + */ +declare function parseAuth(input?: string): ParsedAuth; +/** + * Takes a string, and returns an object with two properties: `hostname` and `port`. + * + * @group parsing + * + * @param [input] - The URL to parse. + * @returns A function that takes a string and returns an object with two properties: `hostname` and + * `port`. + */ +declare function parseHost(input?: string): ParsedHost; +/** + * Takes a `ParsedURL` object and returns the stringified URL. + * + * @group parsing + * + * @example + * + * ```js + * const obj = parseURL("http://foo.com/foo?test=123#token"); + * obj.host = "bar.com"; + * + * stringifyParsedURL(obj); // "http://bar.com/foo?test=123#token" + * ``` + * + * @param [parsed] - The parsed URL + * @returns A stringified URL. + */ +declare function stringifyParsedURL(parsed: Partial): string; +/** + * Parses a url and returns last segment in path as filename. + * + * If `{ strict: true }` is passed as the second argument, it will only return the last segment only if ending with an extension. + * + * @group parsing + * + * @example + * + * ```js + * // Result: filename.ext + * parseFilename("http://example.com/path/to/filename.ext"); + * + * // Result: undefined + * parseFilename("/path/to/.hidden-file", { strict: true }); + * ``` + */ +declare function parseFilename(input: string, { strict }: { + strict: any; +}): string | undefined; + +/** + * @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)` + */ +declare class $URL implements URL { + protocol: string; + host: string; + auth: string; + pathname: string; + query: QueryObject; + hash: string; + constructor(input?: string); + get hostname(): string; + get port(): string; + get username(): string; + get password(): string; + get hasProtocol(): number; + get isAbsolute(): number | boolean; + get search(): string; + get searchParams(): URLSearchParams; + get origin(): string; + get fullpath(): string; + get encodedAuth(): string; + get href(): string; + append(url: $URL): void; + toJSON(): string; + toString(): string; +} +/** + * @deprecated use native URL with `new URL(input)` or `ufo.parseURL(input)` + */ +declare function createURL(input: string): $URL; + +/** + * Check if a path starts with `./` or `../`. + * + * @example + * ```js + * isRelative("./foo"); // true + * ``` + * + * @group utils + */ +declare function isRelative(inputString: string): boolean; +interface HasProtocolOptions { + acceptRelative?: boolean; + strict?: boolean; +} +/** + * Checks if the input has a protocol. + * + * You can use `{ acceptRelative: true }` to accept relative URLs as valid protocol. + * + * @group utils + */ +declare function hasProtocol(inputString: string, opts?: HasProtocolOptions): boolean; +/** @deprecated Same as { hasProtocol(inputString, { acceptRelative: true }) */ +declare function hasProtocol(inputString: string, acceptRelative: boolean): boolean; +/** + * Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols. + * + * @group utils + */ +declare function isScriptProtocol(protocol?: string): boolean; +/** + * Checks if the input has a trailing slash. + * + * @group utils + */ +declare function hasTrailingSlash(input?: string, respectQueryAndFragment?: boolean): boolean; +/** + * Removes trailing slash from the URL or pathname. + * + * If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations. + * + * @example + * + * ```js + * withoutTrailingSlash("/foo/"); // "/foo" + * + * withoutTrailingSlash("/path/?query=true", true); // "/path?query=true" + * ``` + * + * @group utils + */ +declare function withoutTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string; +/** + * Ensures url ends with a trailing slash. + * + * If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation. + * + * @example + * + * ```js + * withTrailingSlash("/foo"); // "/foo/" + * + * withTrailingSlash("/path?query=true", true); // "/path/?query=true" + * ``` + * + * @group utils + */ +declare function withTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string; +/** + * Checks if the input has a leading slash. (e.g. `/foo`) + * + * @group utils + */ +declare function hasLeadingSlash(input?: string): boolean; +/** + * Removes leading slash from the URL or pathname. + * + * @group utils + */ +declare function withoutLeadingSlash(input?: string): string; +/** + * Ensures the URL or pathname has a leading slash. + * + * @group utils + */ +declare function withLeadingSlash(input?: string): string; +/** + * Removes double slashes from the URL. + * + * @example + * + * ```js + * cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/" + * + * cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//"); + * // Returns "http://example.com/analyze/http://localhost:3000/" + * ``` + * + * @group utils + */ +declare function cleanDoubleSlashes(input?: string): string; +/** + * Ensures the URL or pathname has a trailing slash. + * + * If input aleady start with base, it will not be added again. + * + * @group utils + */ +declare function withBase(input: string, base: string): string; +/** + * Removes the base from the URL or pathname. + * + * If input does not start with base, it will not be removed. + * + * @group utils + */ +declare function withoutBase(input: string, base: string): string; +/** + * Add/Replace the query section of the URL. + * + * @example + * + * ```js + * withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret" + * ``` + * + * @group utils + */ +declare function withQuery(input: string, query: QueryObject): string; +/** + * Parses and decods the query object of an input URL into an object. + * + * @example + * + * ```js + * getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD"); + * // { test: "123", unicode: "好" } + * ``` + * @group utils + */ +declare function getQuery(input: string): T; +/** + * Checks if the input url is empty or `/`. + * + * @group utils + */ +declare function isEmptyURL(url: string): boolean; +/** + * Checks if the input url is not empty nor `/`. + * + * @group utils + */ +declare function isNonEmptyURL(url: string): boolean; +/** + * Joins multiple URL segments into a single URL. + * + * @example + * + * ```js + * joinURL("a", "/b", "/c"); // "a/b/c" + * ``` + * + * @group utils + */ +declare function joinURL(base: string, ...input: string[]): string; +/** + * Adds or replaces url protocol to `http://`. + * + * @example + * + * ```js + * withHttp("https://example.com"); // http://example.com + * ``` + * + * @group utils + */ +declare function withHttp(input: string): string; +/** + * Adds or replaces url protocol to `https://`. + * + * @example + * + * ```js + * withHttps("http://example.com"); // https://example.com + * ``` + * + * @group utils + */ +declare function withHttps(input: string): string; +/** + * Removes the protocol from the input. + * + * @example + * ```js + * withoutProtocol("http://example.com"); // "example.com" + * ``` + */ +declare function withoutProtocol(input: string): string; +/** + * Adds or Replaces protocol of the input URL. + * + * @example + * ```js + * withProtocol("http://example.com", "ftp://"); // "ftp://example.com" + * ``` + * + * @group utils + */ +declare function withProtocol(input: string, protocol: string): string; +/** + * Normlizes inputed url: + * + * - Ensures url is properly encoded + * - Ensures pathname starts with slash + * - Preserves protocol/host if provided + * + * @example + * + * ```js + * normalizeURL("test?query=123 123#hash, test"); + * // Returns "test?query=123%20123#hash,%20test" + * + * normalizeURL("http://localhost:3000"); + * // Returns "http://localhost:3000" + * ``` + * + * @group utils + */ +declare function normalizeURL(input: string): string; +/** + * Resolves multiple URL segments into a single URL. + * + * @example + * + * ```js + * resolveURL("http://foo.com/foo?test=123#token", "bar", "baz"); + * // Returns "http://foo.com/foo/bar/baz?test=123#token" + * ``` + * + * @group utils + */ +declare function resolveURL(base?: string, ...inputs: string[]): string; +/** + * Check two paths are equal or not. Trailing slash and encoding are normalized before comparison. + * + * @example + * ```js + * isSamePath("/foo", "/foo/"); // true + * ``` + * + * @group utils + */ +declare function isSamePath(p1: string, p2: string): boolean; +interface CompareURLOptions { + trailingSlash?: boolean; + leadingSlash?: boolean; + encoding?: boolean; +} +/** + * Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences. + * + * You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options. + * + * You can make encoding check strict by setting `{ encoding: true }` as options. + * + * @example + * + * ```js + * isEqual("/foo", "foo"); // true + * isEqual("foo/", "foo"); // true + * isEqual("/foo bar", "/foo%20bar"); // true + * + * // Strict compare + * isEqual("/foo", "foo", { leadingSlash: true }); // false + * isEqual("foo/", "foo", { trailingSlash: true }); // false + * isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false + * ``` + * + * @group utils + */ +declare function isEqual(a: string, b: string, options?: CompareURLOptions): boolean; +/** + * Add/Replace the fragment section of the URL. + * + * @example + * + * ```js + * withFragment("/foo", "bar"); // "/foo#bar" + * withFragment("/foo#bar", "baz"); // "/foo#baz" + * withFragment("/foo#bar", ""); // "/foo" + * ``` + * + * @group utils + */ +declare function withFragment(input: string, hash: string): string; +/** + * Removes the fragment section from the URL. + * + * @example + * + * ```js + * withoutFragment("http://example.com/foo?q=123#bar") + * // Returns "http://example.com/foo?q=123" + * ``` + * + * @group utils + */ +declare function withoutFragment(input: string): string; + +export { $URL, type HasProtocolOptions, type ParsedAuth, type ParsedHost, type ParsedQuery, type ParsedURL, type QueryObject, type QueryValue, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryKey, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, isScriptProtocol, joinURL, normalizeURL, parseAuth, parseFilename, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withFragment, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutFragment, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash }; diff --git a/web/node_modules/ufo/dist/index.mjs b/web/node_modules/ufo/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cde831948d3f897a391763e16cf4900913f78135 --- /dev/null +++ b/web/node_modules/ufo/dist/index.mjs @@ -0,0 +1,577 @@ +const n = /[^\0-\x7E]/; +const t = /[\x2E\u3002\uFF0E\uFF61]/g; +const o = { + overflow: "Overflow Error", + "not-basic": "Illegal Input", + "invalid-input": "Invalid Input" +}; +const e = Math.floor; +const r = String.fromCharCode; +function s(n2) { + throw new RangeError(o[n2]); +} +const c = function(n2, t2) { + return n2 + 22 + 75 * (n2 < 26) - ((t2 != 0) << 5); +}; +const u = function(n2, t2, o2) { + let r2 = 0; + for (n2 = o2 ? e(n2 / 700) : n2 >> 1, n2 += e(n2 / t2); n2 > 455; r2 += 36) { + n2 = e(n2 / 35); + } + return e(r2 + 36 * n2 / (n2 + 38)); +}; +function toASCII(o2) { + return function(n2, o3) { + const e2 = n2.split("@"); + let r2 = ""; + e2.length > 1 && (r2 = e2[0] + "@", n2 = e2[1]); + const s2 = function(n3, t2) { + const o4 = []; + let e3 = n3.length; + for (; e3--; ) { + o4[e3] = t2(n3[e3]); + } + return o4; + }((n2 = n2.replace(t, ".")).split("."), o3).join("."); + return r2 + s2; + }(o2, function(t2) { + return n.test(t2) ? "xn--" + function(n2) { + const t3 = []; + const o3 = (n2 = function(n3) { + const t4 = []; + let o4 = 0; + const e2 = n3.length; + for (; o4 < e2; ) { + const r2 = n3.charCodeAt(o4++); + if (r2 >= 55296 && r2 <= 56319 && o4 < e2) { + const e3 = n3.charCodeAt(o4++); + (64512 & e3) == 56320 ? t4.push(((1023 & r2) << 10) + (1023 & e3) + 65536) : (t4.push(r2), o4--); + } else { + t4.push(r2); + } + } + return t4; + }(n2)).length; + let f = 128; + let i = 0; + let l = 72; + for (const o4 of n2) { + o4 < 128 && t3.push(r(o4)); + } + const h = t3.length; + let p = h; + for (h && t3.push("-"); p < o3; ) { + let o4 = 2147483647; + for (const t4 of n2) { + t4 >= f && t4 < o4 && (o4 = t4); + } + const a = p + 1; + o4 - f > e((2147483647 - i) / a) && s("overflow"), i += (o4 - f) * a, f = o4; + for (const o5 of n2) { + if (o5 < f && ++i > 2147483647 && s("overflow"), o5 == f) { + let n3 = i; + for (let o6 = 36; ; o6 += 36) { + const s2 = o6 <= l ? 1 : o6 >= l + 26 ? 26 : o6 - l; + if (n3 < s2) { + break; + } + const u2 = n3 - s2; + const f2 = 36 - s2; + t3.push(r(c(s2 + u2 % f2, 0))), n3 = e(u2 / f2); + } + t3.push(r(c(n3, 0))), l = u(i, a, p == h), i = 0, ++p; + } + } + ++i, ++f; + } + return t3.join(""); + }(t2) : t2; + }); +} + +const HASH_RE = /#/g; +const AMPERSAND_RE = /&/g; +const SLASH_RE = /\//g; +const EQUAL_RE = /=/g; +const IM_RE = /\?/g; +const PLUS_RE = /\+/g; +const ENC_CARET_RE = /%5e/gi; +const ENC_BACKTICK_RE = /%60/gi; +const ENC_CURLY_OPEN_RE = /%7b/gi; +const ENC_PIPE_RE = /%7c/gi; +const ENC_CURLY_CLOSE_RE = /%7d/gi; +const ENC_SPACE_RE = /%20/gi; +const ENC_SLASH_RE = /%2f/gi; +const ENC_ENC_SLASH_RE = /%252f/gi; +function encode(text) { + return encodeURI("" + text).replace(ENC_PIPE_RE, "|"); +} +function encodeHash(text) { + return encode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); +} +function encodeQueryValue(input) { + return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F"); +} +function encodeQueryKey(text) { + return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); +} +function encodePath(text) { + return encode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F").replace(AMPERSAND_RE, "%26").replace(PLUS_RE, "%2B"); +} +function encodeParam(text) { + return encodePath(text).replace(SLASH_RE, "%2F"); +} +function decode(text = "") { + try { + return decodeURIComponent("" + text); + } catch { + return "" + text; + } +} +function decodePath(text) { + return decode(text.replace(ENC_SLASH_RE, "%252F")); +} +function decodeQueryKey(text) { + return decode(text.replace(PLUS_RE, " ")); +} +function decodeQueryValue(text) { + return decode(text.replace(PLUS_RE, " ")); +} +function encodeHost(name = "") { + return toASCII(name); +} + +function parseQuery(parametersString = "") { + const object = {}; + if (parametersString[0] === "?") { + parametersString = parametersString.slice(1); + } + for (const parameter of parametersString.split("&")) { + const s = parameter.match(/([^=]+)=?(.*)/) || []; + if (s.length < 2) { + continue; + } + const key = decodeQueryKey(s[1]); + if (key === "__proto__" || key === "constructor") { + continue; + } + const value = decodeQueryValue(s[2] || ""); + if (object[key] === void 0) { + object[key] = value; + } else if (Array.isArray(object[key])) { + object[key].push(value); + } else { + object[key] = [object[key], value]; + } + } + return object; +} +function encodeQueryItem(key, value) { + if (typeof value === "number" || typeof value === "boolean") { + value = String(value); + } + if (!value) { + return encodeQueryKey(key); + } + if (Array.isArray(value)) { + return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"); + } + return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`; +} +function stringifyQuery(query) { + return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&"); +} + +const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/; +const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/; +const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/; +const PROTOCOL_SCRIPT_RE = /^[\s\0]*(blob|data|javascript|vbscript):$/i; +const TRAILING_SLASH_RE = /\/$|\/\?|\/#/; +const JOIN_LEADING_SLASH_RE = /^\.?\//; +function isRelative(inputString) { + return ["./", "../"].some((string_) => inputString.startsWith(string_)); +} +function hasProtocol(inputString, opts = {}) { + if (typeof opts === "boolean") { + opts = { acceptRelative: opts }; + } + if (opts.strict) { + return PROTOCOL_STRICT_REGEX.test(inputString); + } + return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false); +} +function isScriptProtocol(protocol) { + return !!protocol && PROTOCOL_SCRIPT_RE.test(protocol); +} +function hasTrailingSlash(input = "", respectQueryAndFragment) { + if (!respectQueryAndFragment) { + return input.endsWith("/"); + } + return TRAILING_SLASH_RE.test(input); +} +function withoutTrailingSlash(input = "", respectQueryAndFragment) { + if (!respectQueryAndFragment) { + return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/"; + } + if (!hasTrailingSlash(input, true)) { + return input || "/"; + } + let path = input; + let fragment = ""; + const fragmentIndex = input.indexOf("#"); + if (fragmentIndex >= 0) { + path = input.slice(0, fragmentIndex); + fragment = input.slice(fragmentIndex); + } + const [s0, ...s] = path.split("?"); + return (s0.slice(0, -1) || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment; +} +function withTrailingSlash(input = "", respectQueryAndFragment) { + if (!respectQueryAndFragment) { + return input.endsWith("/") ? input : input + "/"; + } + if (hasTrailingSlash(input, true)) { + return input || "/"; + } + let path = input; + let fragment = ""; + const fragmentIndex = input.indexOf("#"); + if (fragmentIndex >= 0) { + path = input.slice(0, fragmentIndex); + fragment = input.slice(fragmentIndex); + if (!path) { + return fragment; + } + } + const [s0, ...s] = path.split("?"); + return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment; +} +function hasLeadingSlash(input = "") { + return input.startsWith("/"); +} +function withoutLeadingSlash(input = "") { + return (hasLeadingSlash(input) ? input.slice(1) : input) || "/"; +} +function withLeadingSlash(input = "") { + return hasLeadingSlash(input) ? input : "/" + input; +} +function cleanDoubleSlashes(input = "") { + return input.split("://").map((string_) => string_.replace(/\/{2,}/g, "/")).join("://"); +} +function withBase(input, base) { + if (isEmptyURL(base) || hasProtocol(input)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (input.startsWith(_base)) { + return input; + } + return joinURL(_base, input); +} +function withoutBase(input, base) { + if (isEmptyURL(base)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (!input.startsWith(_base)) { + return input; + } + const trimmed = input.slice(_base.length); + return trimmed[0] === "/" ? trimmed : "/" + trimmed; +} +function withQuery(input, query) { + const parsed = parseURL(input); + const mergedQuery = { ...parseQuery(parsed.search), ...query }; + parsed.search = stringifyQuery(mergedQuery); + return stringifyParsedURL(parsed); +} +function getQuery(input) { + return parseQuery(parseURL(input).search); +} +function isEmptyURL(url) { + return !url || url === "/"; +} +function isNonEmptyURL(url) { + return url && url !== "/"; +} +function joinURL(base, ...input) { + let url = base || ""; + for (const segment of input.filter((url2) => isNonEmptyURL(url2))) { + if (url) { + const _segment = segment.replace(JOIN_LEADING_SLASH_RE, ""); + url = withTrailingSlash(url) + _segment; + } else { + url = segment; + } + } + return url; +} +function withHttp(input) { + return withProtocol(input, "http://"); +} +function withHttps(input) { + return withProtocol(input, "https://"); +} +function withoutProtocol(input) { + return withProtocol(input, ""); +} +function withProtocol(input, protocol) { + const match = input.match(PROTOCOL_REGEX); + if (!match) { + return protocol + input; + } + return protocol + input.slice(match[0].length); +} +function normalizeURL(input) { + const parsed = parseURL(input); + parsed.pathname = encodePath(decodePath(parsed.pathname)); + parsed.hash = encodeHash(decode(parsed.hash)); + parsed.host = encodeHost(decode(parsed.host)); + parsed.search = stringifyQuery(parseQuery(parsed.search)); + return stringifyParsedURL(parsed); +} +function resolveURL(base = "", ...inputs) { + if (typeof base !== "string") { + throw new TypeError( + `URL input should be string received ${typeof base} (${base})` + ); + } + const filteredInputs = inputs.filter((input) => isNonEmptyURL(input)); + if (filteredInputs.length === 0) { + return base; + } + const url = parseURL(base); + for (const inputSegment of filteredInputs) { + const urlSegment = parseURL(inputSegment); + if (urlSegment.pathname) { + url.pathname = withTrailingSlash(url.pathname) + withoutLeadingSlash(urlSegment.pathname); + } + if (urlSegment.hash && urlSegment.hash !== "#") { + url.hash = urlSegment.hash; + } + if (urlSegment.search && urlSegment.search !== "?") { + if (url.search && url.search !== "?") { + const queryString = stringifyQuery({ + ...parseQuery(url.search), + ...parseQuery(urlSegment.search) + }); + url.search = queryString.length > 0 ? "?" + queryString : ""; + } else { + url.search = urlSegment.search; + } + } + } + return stringifyParsedURL(url); +} +function isSamePath(p1, p2) { + return decode(withoutTrailingSlash(p1)) === decode(withoutTrailingSlash(p2)); +} +function isEqual(a, b, options = {}) { + if (!options.trailingSlash) { + a = withTrailingSlash(a); + b = withTrailingSlash(b); + } + if (!options.leadingSlash) { + a = withLeadingSlash(a); + b = withLeadingSlash(b); + } + if (!options.encoding) { + a = decode(a); + b = decode(b); + } + return a === b; +} +function withFragment(input, hash) { + if (!hash || hash === "#") { + return input; + } + const parsed = parseURL(input); + parsed.hash = hash === "" ? "" : "#" + encodeHash(hash); + return stringifyParsedURL(parsed); +} +function withoutFragment(input) { + return stringifyParsedURL({ ...parseURL(input), hash: "" }); +} + +const protocolRelative = Symbol.for("ufo:protocolRelative"); +function parseURL(input = "", defaultProto) { + const _specialProtoMatch = input.match( + /^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i + ); + if (_specialProtoMatch) { + const [, _proto, _pathname = ""] = _specialProtoMatch; + return { + protocol: _proto.toLowerCase(), + pathname: _pathname, + href: _proto + _pathname, + auth: "", + host: "", + search: "", + hash: "" + }; + } + if (!hasProtocol(input, { acceptRelative: true })) { + return defaultProto ? parseURL(defaultProto + input) : parsePath(input); + } + const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || []; + const [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || []; + const { pathname, search, hash } = parsePath( + path.replace(/\/(?=[A-Za-z]:)/, "") + ); + return { + protocol: protocol.toLowerCase(), + auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "", + host, + pathname, + search, + hash, + [protocolRelative]: !protocol + }; +} +function parsePath(input = "") { + const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1); + return { + pathname, + search, + hash + }; +} +function parseAuth(input = "") { + const [username, password] = input.split(":"); + return { + username: decode(username), + password: decode(password) + }; +} +function parseHost(input = "") { + const [hostname, port] = (input.match(/([^/:]*):?(\d+)?/) || []).splice(1); + return { + hostname: decode(hostname), + port + }; +} +function stringifyParsedURL(parsed) { + const pathname = parsed.pathname || ""; + const search = parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : ""; + const hash = parsed.hash || ""; + const auth = parsed.auth ? parsed.auth + "@" : ""; + const host = parsed.host || ""; + const proto = parsed.protocol || parsed[protocolRelative] ? (parsed.protocol || "") + "//" : ""; + return proto + auth + host + pathname + search + hash; +} +const FILENAME_STRICT_REGEX = /\/([^/]+\.[^/]+)$/; +const FILENAME_REGEX = /\/([^/]+)$/; +function parseFilename(input = "", { strict }) { + const { pathname } = parseURL(input); + const matches = strict ? pathname.match(FILENAME_STRICT_REGEX) : pathname.match(FILENAME_REGEX); + return matches ? matches[1] : void 0; +} + +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +class $URL { + constructor(input = "") { + __publicField(this, "protocol"); + __publicField(this, "host"); + __publicField(this, "auth"); + __publicField(this, "pathname"); + __publicField(this, "query", {}); + __publicField(this, "hash"); + if (typeof input !== "string") { + throw new TypeError( + `URL input should be string received ${typeof input} (${input})` + ); + } + const parsed = parseURL(input); + this.protocol = decode(parsed.protocol); + this.host = decode(parsed.host); + this.auth = decode(parsed.auth); + this.pathname = decodePath(parsed.pathname); + this.query = parseQuery(parsed.search); + this.hash = decode(parsed.hash); + } + get hostname() { + return parseHost(this.host).hostname; + } + get port() { + return parseHost(this.host).port || ""; + } + get username() { + return parseAuth(this.auth).username; + } + get password() { + return parseAuth(this.auth).password || ""; + } + get hasProtocol() { + return this.protocol.length; + } + get isAbsolute() { + return this.hasProtocol || this.pathname[0] === "/"; + } + get search() { + const q = stringifyQuery(this.query); + return q.length > 0 ? "?" + q : ""; + } + get searchParams() { + const p = new URLSearchParams(); + for (const name in this.query) { + const value = this.query[name]; + if (Array.isArray(value)) { + for (const v of value) { + p.append(name, v); + } + } else { + p.append( + name, + typeof value === "string" ? value : JSON.stringify(value) + ); + } + } + return p; + } + get origin() { + return (this.protocol ? this.protocol + "//" : "") + encodeHost(this.host); + } + get fullpath() { + return encodePath(this.pathname) + this.search + encodeHash(this.hash); + } + get encodedAuth() { + if (!this.auth) { + return ""; + } + const { username, password } = parseAuth(this.auth); + return encodeURIComponent(username) + (password ? ":" + encodeURIComponent(password) : ""); + } + get href() { + const auth = this.encodedAuth; + const originWithAuth = (this.protocol ? this.protocol + "//" : "") + (auth ? auth + "@" : "") + encodeHost(this.host); + return this.hasProtocol && this.isAbsolute ? originWithAuth + this.fullpath : this.fullpath; + } + append(url) { + if (url.hasProtocol) { + throw new Error("Cannot append a URL with protocol"); + } + Object.assign(this.query, url.query); + if (url.pathname) { + this.pathname = withTrailingSlash(this.pathname) + withoutLeadingSlash(url.pathname); + } + if (url.hash) { + this.hash = url.hash; + } + } + toJSON() { + return this.href; + } + toString() { + return this.href; + } +} +function createURL(input) { + return new $URL(input); +} + +export { $URL, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryKey, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, isScriptProtocol, joinURL, normalizeURL, parseAuth, parseFilename, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withFragment, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutFragment, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash }; diff --git a/web/node_modules/ufo/package.json b/web/node_modules/ufo/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1d66c3244e616770b60abedc7e2f84da68eff6cf --- /dev/null +++ b/web/node_modules/ufo/package.json @@ -0,0 +1,47 @@ +{ + "name": "ufo", + "version": "1.4.0", + "description": "URL utils for humans", + "repository": "unjs/ufo", + "license": "MIT", + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.cjs", + "import": "./dist/index.mjs" + }, + "./*": "./*" + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "automd && unbuild", + "automd": "automd", + "dev": "vitest", + "lint": "eslint --ext .ts . && prettier -c src test", + "lint:fix": "eslint --fix --ext .ts . && prettier -w src test", + "prepack": "pnpm build", + "release": "pnpm test && changelogen --release && npm publish && git push --follow-tags", + "test": "pnpm lint && vitest run --typecheck" + }, + "devDependencies": { + "@types/node": "^20.11.16", + "@vitest/coverage-v8": "^1.2.2", + "automd": "^0.1.1", + "changelogen": "^0.5.5", + "eslint": "^8.56.0", + "eslint-config-unjs": "^0.2.1", + "jiti": "^1.21.0", + "prettier": "^3.2.5", + "typescript": "^5.3.3", + "unbuild": "^2.0.0", + "untyped": "^1.4.2", + "vitest": "^1.2.2" + }, + "packageManager": "pnpm@8.15.1" +} \ No newline at end of file diff --git a/web/node_modules/vite-node/LICENSE b/web/node_modules/vite-node/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ae481fdb8ea5d7ab1dac9e5138d77cd80fbfb8c --- /dev/null +++ b/web/node_modules/vite-node/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present Vitest Team + +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/web/node_modules/vite-node/README.md b/web/node_modules/vite-node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00340f677a7f92fcb55d62936740b6c0cfda5cf8 --- /dev/null +++ b/web/node_modules/vite-node/README.md @@ -0,0 +1,186 @@ +

+ +

+ +

+vite-node +

+

+Vite as Node runtime.
The engine that powers Vitest and Nuxt 3 Dev SSR. +

+

+ +

+ +## Features + +- On-demand evaluation +- Vite's pipeline, plugins, resolve, aliasing +- Out-of-box ESM & TypeScript support +- Respect `vite.config.ts` +- Hot module replacement (HMR) +- Separate server/client architecture +- Top-level `await` +- Shims for `__dirname` and `__filename` in ESM +- Access to native node modules like `fs`, `path`, etc. + +## CLI Usage + +Run JS/TS file on Node.js using Vite's resolvers and transformers. + +```bash +npx vite-node index.ts +``` + +Options: + +```bash +npx vite-node -h +``` + +### Options via CLI + +[All `ViteNodeServer` options](https://github.com/vitest-dev/vitest/blob/main/packages/vite-node/src/types.ts#L92-L111) are supported by the CLI. They may be defined through the dot syntax, as shown below: + +```bash +npx vite-node --options.deps.inline="module-name" --options.deps.external="/module-regexp/" index.ts +``` + +Note that for options supporting RegExps, strings passed to the CLI must start _and_ end with a `/`; + +### Hashbang + +If you prefer to write scripts that don't need to be passed into Vite Node, you can declare it in the [hashbang](https://bash.cyberciti.biz/guide/Shebang). + +Simply add `#!/usr/bin/env vite-node --script` at the top of your file: + +_file.ts_ +```ts +#!/usr/bin/env vite-node --script + +console.log('argv:', process.argv.slice(2)) +``` + +And make the file executable: +```sh +chmod +x ./file.ts +``` + +Now, you can run the file without passing it into Vite Node: +```sh +$ ./file.ts hello +argv: [ 'hello' ] +``` + +Note that when using the `--script` option, Vite Node forwards every argument and option to the script to execute, even the one supported by Vite Node itself. + +## Programmatic Usage + +In Vite Node, the server and runner (client) are separated, so you can integrate them in different contexts (workers, cross-process, or remote) if needed. The demo below shows a simple example of having both (server and runner) running in the same context + +```ts +import { createServer } from 'vite' +import { ViteNodeServer } from 'vite-node/server' +import { ViteNodeRunner } from 'vite-node/client' +import { installSourcemapsSupport } from 'vite-node/source-map' + +// create vite server +const server = await createServer({ + optimizeDeps: { + // It's recommended to disable deps optimization + disabled: true, + }, +}) +// this is need to initialize the plugins +await server.pluginContainer.buildStart({}) + +// create vite-node server +const node = new ViteNodeServer(server) + +// fixes stacktraces in Errors +installSourcemapsSupport({ + getSourceMap: source => node.getSourceMap(source), +}) + +// create vite-node runner +const runner = new ViteNodeRunner({ + root: server.config.root, + base: server.config.base, + // when having the server and runner in a different context, + // you will need to handle the communication between them + // and pass to this function + fetchModule(id) { + return node.fetchModule(id) + }, + resolveId(id, importer) { + return node.resolveId(id, importer) + }, +}) + +// execute the file +await runner.executeFile('./example.ts') + +// close the vite server +await server.close() +``` + +## Debugging + +### Debug Transformation + +Sometimes you might want to inspect the transformed code to investigate issues. You can set environment variable `VITE_NODE_DEBUG_DUMP=true` to let vite-node write the transformed result of each module under `.vite-node/dump`. + +If you want to debug by modifying the dumped code, you can change the value of `VITE_NODE_DEBUG_DUMP` to `load` and search for the dumped files and use them for executing. + +```bash +VITE_NODE_DEBUG_DUMP=load vite-node example.ts +``` + +Or programmatically: + +```js +import { ViteNodeServer } from 'vite-node/server' + +const server = new ViteNodeServer(viteServer, { + debug: { + dumpModules: true, + loadDumppedModules: true, + } +}) +``` + +### Debug Execution + +If the process gets stuck, it might be because there are unresolvable circular dependencies. You can set `VITE_NODE_DEBUG_RUNNER=true` for vite-node to warn about this. + +```bash +VITE_NODE_DEBUG_RUNNER=true vite-node example.ts +``` + +Or programmatically: + +```js +import { ViteNodeRunner } from 'vite-node/client' + +const runner = new ViteNodeRunner({ + debug: true +}) +``` + +## Credits + +Based on [@pi0](https://github.com/pi0)'s brilliant idea of having a Vite server as the on-demand transforming service for [Nuxt's Vite SSR](https://github.com/nuxt/vite/pull/201). + +Thanks [@brillout](https://github.com/brillout) for kindly sharing this package name. + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu) diff --git a/web/node_modules/vite-node/dist/chunk-hmr.cjs b/web/node_modules/vite-node/dist/chunk-hmr.cjs new file mode 100644 index 0000000000000000000000000000000000000000..5d1e77209bcf1716232ef7d118690db3ba748ed1 --- /dev/null +++ b/web/node_modules/vite-node/dist/chunk-hmr.cjs @@ -0,0 +1,260 @@ +'use strict'; + +var node_events = require('node:events'); +var c = require('picocolors'); +var createDebug = require('debug'); +var utils = require('./utils.cjs'); + +function createHmrEmitter() { + const emitter = new node_events.EventEmitter(); + return emitter; +} +function viteNodeHmrPlugin() { + const emitter = createHmrEmitter(); + return { + name: "vite-node:hmr", + config() { + if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) { + return { + server: { + watch: { + useFsEvents: false, + usePolling: false + } + } + }; + } + }, + configureServer(server) { + const _send = server.ws.send; + server.emitter = emitter; + server.ws.send = function(payload) { + _send(payload); + emitter.emit("message", payload); + }; + if (process.env.VITE_TEST_WATCHER_DEBUG) { + server.watcher.on("ready", () => { + console.log("[debug] watcher is ready"); + }); + } + } + }; +} + +const debugHmr = createDebug("vite-node:hmr"); +const cache = /* @__PURE__ */ new WeakMap(); +function getCache(runner) { + if (!cache.has(runner)) { + cache.set(runner, { + hotModulesMap: /* @__PURE__ */ new Map(), + dataMap: /* @__PURE__ */ new Map(), + disposeMap: /* @__PURE__ */ new Map(), + pruneMap: /* @__PURE__ */ new Map(), + customListenersMap: /* @__PURE__ */ new Map(), + ctxToListenersMap: /* @__PURE__ */ new Map(), + messageBuffer: [], + isFirstUpdate: false, + pending: false, + queued: [] + }); + } + return cache.get(runner); +} +function sendMessageBuffer(runner, emitter) { + const maps = getCache(runner); + maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg)); + maps.messageBuffer.length = 0; +} +async function reload(runner, files) { + Array.from(runner.moduleCache.keys()).forEach((fsPath) => { + if (!fsPath.includes("node_modules")) + runner.moduleCache.delete(fsPath); + }); + return Promise.all(files.map((file) => runner.executeId(file))); +} +async function notifyListeners(runner, event, data) { + const maps = getCache(runner); + const cbs = maps.customListenersMap.get(event); + if (cbs) + await Promise.all(cbs.map((cb) => cb(data))); +} +async function queueUpdate(runner, p) { + const maps = getCache(runner); + maps.queued.push(p); + if (!maps.pending) { + maps.pending = true; + await Promise.resolve(); + maps.pending = false; + const loading = [...maps.queued]; + maps.queued = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } +} +async function fetchUpdate(runner, { path, acceptedPath }) { + path = utils.normalizeRequestId(path); + acceptedPath = utils.normalizeRequestId(acceptedPath); + const maps = getCache(runner); + const mod = maps.hotModulesMap.get(path); + if (!mod) { + return; + } + const isSelfUpdate = path === acceptedPath; + let fetchedModule; + const qualifiedCallbacks = mod.callbacks.filter( + ({ deps }) => deps.includes(acceptedPath) + ); + if (isSelfUpdate || qualifiedCallbacks.length > 0) { + const disposer = maps.disposeMap.get(acceptedPath); + if (disposer) + await disposer(maps.dataMap.get(acceptedPath)); + try { + [fetchedModule] = await reload(runner, [acceptedPath]); + } catch (e) { + warnFailedFetch(e, acceptedPath); + } + } + return () => { + for (const { deps, fn } of qualifiedCallbacks) + fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)); + const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; + console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`); + }; +} +function warnFailedFetch(err, path) { + if (!err.message.match("fetch")) + console.error(err); + console.error( + `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)` + ); +} +async function handleMessage(runner, emitter, files, payload) { + const maps = getCache(runner); + switch (payload.type) { + case "connected": + sendMessageBuffer(runner, emitter); + break; + case "update": + await notifyListeners(runner, "vite:beforeUpdate", payload); + await Promise.all(payload.updates.map((update) => { + if (update.type === "js-update") + return queueUpdate(runner, fetchUpdate(runner, update)); + console.error(`${c.cyan("[vite-node]")} no support css hmr.}`); + return null; + })); + await notifyListeners(runner, "vite:afterUpdate", payload); + break; + case "full-reload": + await notifyListeners(runner, "vite:beforeFullReload", payload); + maps.customListenersMap.delete("vite:beforeFullReload"); + await reload(runner, files); + break; + case "custom": + await notifyListeners(runner, payload.event, payload.data); + break; + case "prune": + await notifyListeners(runner, "vite:beforePrune", payload); + payload.paths.forEach((path) => { + const fn = maps.pruneMap.get(path); + if (fn) + fn(maps.dataMap.get(path)); + }); + break; + case "error": { + await notifyListeners(runner, "vite:error", payload); + const err = payload.err; + console.error(`${c.cyan("[vite-node]")} Internal Server Error +${err.message} +${err.stack}`); + break; + } + } +} +function createHotContext(runner, emitter, files, ownerPath) { + debugHmr("createHotContext", ownerPath); + const maps = getCache(runner); + if (!maps.dataMap.has(ownerPath)) + maps.dataMap.set(ownerPath, {}); + const mod = maps.hotModulesMap.get(ownerPath); + if (mod) + mod.callbacks = []; + const newListeners = /* @__PURE__ */ new Map(); + maps.ctxToListenersMap.set(ownerPath, newListeners); + function acceptDeps(deps, callback = () => { + }) { + const mod2 = maps.hotModulesMap.get(ownerPath) || { + id: ownerPath, + callbacks: [] + }; + mod2.callbacks.push({ + deps, + fn: callback + }); + maps.hotModulesMap.set(ownerPath, mod2); + } + const hot = { + get data() { + return maps.dataMap.get(ownerPath); + }, + acceptExports(_, callback) { + acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2))); + }, + accept(deps, callback) { + if (typeof deps === "function" || !deps) { + acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2)); + } else if (typeof deps === "string") { + acceptDeps([deps], ([mod2]) => callback && callback(mod2)); + } else if (Array.isArray(deps)) { + acceptDeps(deps, callback); + } else { + throw new TypeError("invalid hot.accept() usage."); + } + }, + dispose(cb) { + maps.disposeMap.set(ownerPath, cb); + }, + prune(cb) { + maps.pruneMap.set(ownerPath, cb); + }, + invalidate() { + notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 }); + return reload(runner, files); + }, + on(event, cb) { + const addToMap = (map) => { + const existing = map.get(event) || []; + existing.push(cb); + map.set(event, existing); + }; + addToMap(maps.customListenersMap); + addToMap(newListeners); + }, + off(event, cb) { + const removeFromMap = (map) => { + const existing = map.get(event); + if (existing === void 0) + return; + const pruned = existing.filter((l) => l !== cb); + if (pruned.length === 0) { + map.delete(event); + return; + } + map.set(event, pruned); + }; + removeFromMap(maps.customListenersMap); + removeFromMap(newListeners); + }, + send(event, data) { + maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data })); + sendMessageBuffer(runner, emitter); + } + }; + return hot; +} + +exports.createHmrEmitter = createHmrEmitter; +exports.createHotContext = createHotContext; +exports.getCache = getCache; +exports.handleMessage = handleMessage; +exports.reload = reload; +exports.sendMessageBuffer = sendMessageBuffer; +exports.viteNodeHmrPlugin = viteNodeHmrPlugin; diff --git a/web/node_modules/vite-node/dist/chunk-hmr.mjs b/web/node_modules/vite-node/dist/chunk-hmr.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a3e531a2d3ac9fff89e0dbaca4ef11374d78a180 --- /dev/null +++ b/web/node_modules/vite-node/dist/chunk-hmr.mjs @@ -0,0 +1,252 @@ +import { EventEmitter } from 'node:events'; +import c from 'picocolors'; +import createDebug from 'debug'; +import { normalizeRequestId } from './utils.mjs'; + +function createHmrEmitter() { + const emitter = new EventEmitter(); + return emitter; +} +function viteNodeHmrPlugin() { + const emitter = createHmrEmitter(); + return { + name: "vite-node:hmr", + config() { + if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) { + return { + server: { + watch: { + useFsEvents: false, + usePolling: false + } + } + }; + } + }, + configureServer(server) { + const _send = server.ws.send; + server.emitter = emitter; + server.ws.send = function(payload) { + _send(payload); + emitter.emit("message", payload); + }; + if (process.env.VITE_TEST_WATCHER_DEBUG) { + server.watcher.on("ready", () => { + console.log("[debug] watcher is ready"); + }); + } + } + }; +} + +const debugHmr = createDebug("vite-node:hmr"); +const cache = /* @__PURE__ */ new WeakMap(); +function getCache(runner) { + if (!cache.has(runner)) { + cache.set(runner, { + hotModulesMap: /* @__PURE__ */ new Map(), + dataMap: /* @__PURE__ */ new Map(), + disposeMap: /* @__PURE__ */ new Map(), + pruneMap: /* @__PURE__ */ new Map(), + customListenersMap: /* @__PURE__ */ new Map(), + ctxToListenersMap: /* @__PURE__ */ new Map(), + messageBuffer: [], + isFirstUpdate: false, + pending: false, + queued: [] + }); + } + return cache.get(runner); +} +function sendMessageBuffer(runner, emitter) { + const maps = getCache(runner); + maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg)); + maps.messageBuffer.length = 0; +} +async function reload(runner, files) { + Array.from(runner.moduleCache.keys()).forEach((fsPath) => { + if (!fsPath.includes("node_modules")) + runner.moduleCache.delete(fsPath); + }); + return Promise.all(files.map((file) => runner.executeId(file))); +} +async function notifyListeners(runner, event, data) { + const maps = getCache(runner); + const cbs = maps.customListenersMap.get(event); + if (cbs) + await Promise.all(cbs.map((cb) => cb(data))); +} +async function queueUpdate(runner, p) { + const maps = getCache(runner); + maps.queued.push(p); + if (!maps.pending) { + maps.pending = true; + await Promise.resolve(); + maps.pending = false; + const loading = [...maps.queued]; + maps.queued = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } +} +async function fetchUpdate(runner, { path, acceptedPath }) { + path = normalizeRequestId(path); + acceptedPath = normalizeRequestId(acceptedPath); + const maps = getCache(runner); + const mod = maps.hotModulesMap.get(path); + if (!mod) { + return; + } + const isSelfUpdate = path === acceptedPath; + let fetchedModule; + const qualifiedCallbacks = mod.callbacks.filter( + ({ deps }) => deps.includes(acceptedPath) + ); + if (isSelfUpdate || qualifiedCallbacks.length > 0) { + const disposer = maps.disposeMap.get(acceptedPath); + if (disposer) + await disposer(maps.dataMap.get(acceptedPath)); + try { + [fetchedModule] = await reload(runner, [acceptedPath]); + } catch (e) { + warnFailedFetch(e, acceptedPath); + } + } + return () => { + for (const { deps, fn } of qualifiedCallbacks) + fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)); + const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; + console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`); + }; +} +function warnFailedFetch(err, path) { + if (!err.message.match("fetch")) + console.error(err); + console.error( + `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)` + ); +} +async function handleMessage(runner, emitter, files, payload) { + const maps = getCache(runner); + switch (payload.type) { + case "connected": + sendMessageBuffer(runner, emitter); + break; + case "update": + await notifyListeners(runner, "vite:beforeUpdate", payload); + await Promise.all(payload.updates.map((update) => { + if (update.type === "js-update") + return queueUpdate(runner, fetchUpdate(runner, update)); + console.error(`${c.cyan("[vite-node]")} no support css hmr.}`); + return null; + })); + await notifyListeners(runner, "vite:afterUpdate", payload); + break; + case "full-reload": + await notifyListeners(runner, "vite:beforeFullReload", payload); + maps.customListenersMap.delete("vite:beforeFullReload"); + await reload(runner, files); + break; + case "custom": + await notifyListeners(runner, payload.event, payload.data); + break; + case "prune": + await notifyListeners(runner, "vite:beforePrune", payload); + payload.paths.forEach((path) => { + const fn = maps.pruneMap.get(path); + if (fn) + fn(maps.dataMap.get(path)); + }); + break; + case "error": { + await notifyListeners(runner, "vite:error", payload); + const err = payload.err; + console.error(`${c.cyan("[vite-node]")} Internal Server Error +${err.message} +${err.stack}`); + break; + } + } +} +function createHotContext(runner, emitter, files, ownerPath) { + debugHmr("createHotContext", ownerPath); + const maps = getCache(runner); + if (!maps.dataMap.has(ownerPath)) + maps.dataMap.set(ownerPath, {}); + const mod = maps.hotModulesMap.get(ownerPath); + if (mod) + mod.callbacks = []; + const newListeners = /* @__PURE__ */ new Map(); + maps.ctxToListenersMap.set(ownerPath, newListeners); + function acceptDeps(deps, callback = () => { + }) { + const mod2 = maps.hotModulesMap.get(ownerPath) || { + id: ownerPath, + callbacks: [] + }; + mod2.callbacks.push({ + deps, + fn: callback + }); + maps.hotModulesMap.set(ownerPath, mod2); + } + const hot = { + get data() { + return maps.dataMap.get(ownerPath); + }, + acceptExports(_, callback) { + acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2))); + }, + accept(deps, callback) { + if (typeof deps === "function" || !deps) { + acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2)); + } else if (typeof deps === "string") { + acceptDeps([deps], ([mod2]) => callback && callback(mod2)); + } else if (Array.isArray(deps)) { + acceptDeps(deps, callback); + } else { + throw new TypeError("invalid hot.accept() usage."); + } + }, + dispose(cb) { + maps.disposeMap.set(ownerPath, cb); + }, + prune(cb) { + maps.pruneMap.set(ownerPath, cb); + }, + invalidate() { + notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 }); + return reload(runner, files); + }, + on(event, cb) { + const addToMap = (map) => { + const existing = map.get(event) || []; + existing.push(cb); + map.set(event, existing); + }; + addToMap(maps.customListenersMap); + addToMap(newListeners); + }, + off(event, cb) { + const removeFromMap = (map) => { + const existing = map.get(event); + if (existing === void 0) + return; + const pruned = existing.filter((l) => l !== cb); + if (pruned.length === 0) { + map.delete(event); + return; + } + map.set(event, pruned); + }; + removeFromMap(maps.customListenersMap); + removeFromMap(newListeners); + }, + send(event, data) { + maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data })); + sendMessageBuffer(runner, emitter); + } + }; + return hot; +} + +export { createHotContext as a, createHmrEmitter as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v }; diff --git a/web/node_modules/vite-node/dist/cli.cjs b/web/node_modules/vite-node/dist/cli.cjs new file mode 100644 index 0000000000000000000000000000000000000000..af03f080a55bdfe0530cfd376cf0b89ce3cfccbe --- /dev/null +++ b/web/node_modules/vite-node/dist/cli.cjs @@ -0,0 +1,126 @@ +'use strict'; + +var path = require('node:path'); +var cac = require('cac'); +var c = require('picocolors'); +var vite = require('vite'); +var server = require('./server.cjs'); +var client = require('./client.cjs'); +var utils = require('./utils.cjs'); +var sourceMap = require('./source-map.cjs'); +var hmr = require('./chunk-hmr.cjs'); +require('node:perf_hooks'); +require('node:fs'); +require('node:assert'); +require('pathe'); +require('debug'); +require('./constants.cjs'); +require('node:module'); +require('node:url'); +require('node:vm'); +require('node:events'); + +var version = "1.3.1"; + +const cli = cac("vite-node"); +cli.option("-r, --root ", "Use specified root directory").option("-c, --config ", "Use specified config file").option("-m, --mode ", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options ", "Use specified Vite server options").option("-v, --version", "Output the version number").option("-h, --help", "Display help for command"); +cli.command("[...files]").allowUnknownOptions().action(run); +cli.parse(process.argv, { run: false }); +if (cli.args.length === 0) { + cli.runMatchedCommand(); +} else { + const i = cli.rawArgs.indexOf(cli.args[0]) + 1; + const scriptArgs = cli.rawArgs.slice(i).filter((it) => it !== "--"); + const executeArgs = [...cli.rawArgs.slice(0, i), "--", ...scriptArgs]; + cli.parse(executeArgs); +} +async function run(files, options = {}) { + var _a; + if (options.script) { + files = [files[0]]; + options = {}; + process.argv = [process.argv[0], path.resolve(files[0]), ...process.argv.slice(2).filter((arg) => arg !== "--script" && arg !== files[0])]; + } else { + process.argv = [...process.argv.slice(0, 2), ...options["--"] || []]; + } + if (options.version) { + cli.version(version); + cli.outputVersion(); + process.exit(0); + } + if (options.help) { + cli.version(version).outputHelp(); + process.exit(0); + } + if (!files.length) { + console.error(c.red("No files specified.")); + cli.version(version).outputHelp(); + process.exit(1); + } + const serverOptions = options.options ? parseServerOptions(options.options) : {}; + const server$1 = await vite.createServer({ + logLevel: "error", + configFile: options.config, + root: options.root, + mode: options.mode, + server: { + hmr: !!options.watch + }, + plugins: [ + options.watch && hmr.viteNodeHmrPlugin() + ] + }); + await server$1.pluginContainer.buildStart({}); + const node = new server.ViteNodeServer(server$1, serverOptions); + sourceMap.installSourcemapsSupport({ + getSourceMap: (source) => node.getSourceMap(source) + }); + const runner = new client.ViteNodeRunner({ + root: server$1.config.root, + base: server$1.config.base, + fetchModule(id) { + return node.fetchModule(id); + }, + resolveId(id, importer) { + return node.resolveId(id, importer); + }, + createHotContext(runner2, url) { + return hmr.createHotContext(runner2, server$1.emitter, files, url); + } + }); + await runner.executeId("/@vite/env"); + for (const file of files) + await runner.executeFile(file); + if (!options.watch) + await server$1.close(); + (_a = server$1.emitter) == null ? void 0 : _a.on("message", (payload) => { + hmr.handleMessage(runner, server$1.emitter, files, payload); + }); + if (options.watch) { + process.on("uncaughtException", (err) => { + console.error(c.red("[vite-node] Failed to execute file: \n"), err); + }); + } +} +function parseServerOptions(serverOptions) { + var _a, _b, _c, _d, _e, _f, _g; + const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : utils.toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline); + return { + ...serverOptions, + deps: { + ...serverOptions.deps, + inline: inlineOptions !== true ? inlineOptions.map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }) : true, + external: utils.toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }), + moduleDirectories: ((_d = serverOptions.deps) == null ? void 0 : _d.moduleDirectories) ? utils.toArray((_e = serverOptions.deps) == null ? void 0 : _e.moduleDirectories) : void 0 + }, + transformMode: { + ...serverOptions.transformMode, + ssr: utils.toArray((_f = serverOptions.transformMode) == null ? void 0 : _f.ssr).map((dep) => new RegExp(dep)), + web: utils.toArray((_g = serverOptions.transformMode) == null ? void 0 : _g.web).map((dep) => new RegExp(dep)) + } + }; +} diff --git a/web/node_modules/vite-node/dist/cli.d.ts b/web/node_modules/vite-node/dist/cli.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6deb371d48cffdd19e9c83127cf424d37e6e0de9 --- /dev/null +++ b/web/node_modules/vite-node/dist/cli.d.ts @@ -0,0 +1,21 @@ +import { V as ViteNodeServerOptions } from './index-WT31LSgS.js'; +import './trace-mapping.d-xyIfZtPm.js'; + +interface CliOptions { + 'root'?: string; + 'script'?: boolean; + 'config'?: string; + 'mode'?: string; + 'watch'?: boolean; + 'options'?: ViteNodeServerOptionsCLI; + 'version'?: boolean; + 'help'?: boolean; + '--'?: string[]; +} +type Optional = T | undefined; +type ComputeViteNodeServerOptionsCLI> = { + [K in keyof T]: T[K] extends Optional ? string | string[] : T[K] extends Optional<(string | RegExp)[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[] | true> ? string | string[] | true : T[K] extends Optional> ? ComputeViteNodeServerOptionsCLI : T[K]; +}; +type ViteNodeServerOptionsCLI = ComputeViteNodeServerOptionsCLI; + +export type { CliOptions, ViteNodeServerOptionsCLI }; diff --git a/web/node_modules/vite-node/dist/cli.mjs b/web/node_modules/vite-node/dist/cli.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d6d41c3d0e1e274eb3f8918bf159dcf1dbc8258 --- /dev/null +++ b/web/node_modules/vite-node/dist/cli.mjs @@ -0,0 +1,124 @@ +import { resolve } from 'node:path'; +import cac from 'cac'; +import c from 'picocolors'; +import { createServer } from 'vite'; +import { ViteNodeServer } from './server.mjs'; +import { ViteNodeRunner } from './client.mjs'; +import { toArray } from './utils.mjs'; +import { installSourcemapsSupport } from './source-map.mjs'; +import { v as viteNodeHmrPlugin, a as createHotContext, h as handleMessage } from './chunk-hmr.mjs'; +import 'node:perf_hooks'; +import 'node:fs'; +import 'node:assert'; +import 'pathe'; +import 'debug'; +import './constants.mjs'; +import 'node:module'; +import 'node:url'; +import 'node:vm'; +import 'node:events'; + +var version = "1.3.1"; + +const cli = cac("vite-node"); +cli.option("-r, --root ", "Use specified root directory").option("-c, --config ", "Use specified config file").option("-m, --mode ", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options ", "Use specified Vite server options").option("-v, --version", "Output the version number").option("-h, --help", "Display help for command"); +cli.command("[...files]").allowUnknownOptions().action(run); +cli.parse(process.argv, { run: false }); +if (cli.args.length === 0) { + cli.runMatchedCommand(); +} else { + const i = cli.rawArgs.indexOf(cli.args[0]) + 1; + const scriptArgs = cli.rawArgs.slice(i).filter((it) => it !== "--"); + const executeArgs = [...cli.rawArgs.slice(0, i), "--", ...scriptArgs]; + cli.parse(executeArgs); +} +async function run(files, options = {}) { + var _a; + if (options.script) { + files = [files[0]]; + options = {}; + process.argv = [process.argv[0], resolve(files[0]), ...process.argv.slice(2).filter((arg) => arg !== "--script" && arg !== files[0])]; + } else { + process.argv = [...process.argv.slice(0, 2), ...options["--"] || []]; + } + if (options.version) { + cli.version(version); + cli.outputVersion(); + process.exit(0); + } + if (options.help) { + cli.version(version).outputHelp(); + process.exit(0); + } + if (!files.length) { + console.error(c.red("No files specified.")); + cli.version(version).outputHelp(); + process.exit(1); + } + const serverOptions = options.options ? parseServerOptions(options.options) : {}; + const server = await createServer({ + logLevel: "error", + configFile: options.config, + root: options.root, + mode: options.mode, + server: { + hmr: !!options.watch + }, + plugins: [ + options.watch && viteNodeHmrPlugin() + ] + }); + await server.pluginContainer.buildStart({}); + const node = new ViteNodeServer(server, serverOptions); + installSourcemapsSupport({ + getSourceMap: (source) => node.getSourceMap(source) + }); + const runner = new ViteNodeRunner({ + root: server.config.root, + base: server.config.base, + fetchModule(id) { + return node.fetchModule(id); + }, + resolveId(id, importer) { + return node.resolveId(id, importer); + }, + createHotContext(runner2, url) { + return createHotContext(runner2, server.emitter, files, url); + } + }); + await runner.executeId("/@vite/env"); + for (const file of files) + await runner.executeFile(file); + if (!options.watch) + await server.close(); + (_a = server.emitter) == null ? void 0 : _a.on("message", (payload) => { + handleMessage(runner, server.emitter, files, payload); + }); + if (options.watch) { + process.on("uncaughtException", (err) => { + console.error(c.red("[vite-node] Failed to execute file: \n"), err); + }); + } +} +function parseServerOptions(serverOptions) { + var _a, _b, _c, _d, _e, _f, _g; + const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline); + return { + ...serverOptions, + deps: { + ...serverOptions.deps, + inline: inlineOptions !== true ? inlineOptions.map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }) : true, + external: toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }), + moduleDirectories: ((_d = serverOptions.deps) == null ? void 0 : _d.moduleDirectories) ? toArray((_e = serverOptions.deps) == null ? void 0 : _e.moduleDirectories) : void 0 + }, + transformMode: { + ...serverOptions.transformMode, + ssr: toArray((_f = serverOptions.transformMode) == null ? void 0 : _f.ssr).map((dep) => new RegExp(dep)), + web: toArray((_g = serverOptions.transformMode) == null ? void 0 : _g.web).map((dep) => new RegExp(dep)) + } + }; +} diff --git a/web/node_modules/vite-node/dist/client.cjs b/web/node_modules/vite-node/dist/client.cjs new file mode 100644 index 0000000000000000000000000000000000000000..f5774d1ae7dbb049732d8efdec4384fef5058842 --- /dev/null +++ b/web/node_modules/vite-node/dist/client.cjs @@ -0,0 +1,454 @@ +'use strict'; + +var node_module = require('node:module'); +var path = require('node:path'); +var node_url = require('node:url'); +var vm = require('node:vm'); +var pathe = require('pathe'); +var createDebug = require('debug'); +var utils = require('./utils.cjs'); +var sourceMap = require('./source-map.cjs'); +require('node:fs'); + +const { setTimeout, clearTimeout } = globalThis; +const debugExecute = createDebug("vite-node:client:execute"); +const debugNative = createDebug("vite-node:client:native"); +const clientStub = { + injectQuery: (id) => id, + createHotContext: () => { + return { + accept: () => { + }, + prune: () => { + }, + dispose: () => { + }, + decline: () => { + }, + invalidate: () => { + }, + on: () => { + }, + send: () => { + } + }; + }, + updateStyle: () => { + }, + removeStyle: () => { + } +}; +const env = utils.createImportMetaEnvProxy(); +const DEFAULT_REQUEST_STUBS = { + "/@vite/client": clientStub, + "@vite/client": clientStub +}; +class ModuleCacheMap extends Map { + normalizePath(fsPath) { + return utils.normalizeModuleId(fsPath); + } + /** + * Assign partial data to the map + */ + update(fsPath, mod) { + fsPath = this.normalizePath(fsPath); + if (!super.has(fsPath)) + this.setByModuleId(fsPath, mod); + else + Object.assign(super.get(fsPath), mod); + return this; + } + setByModuleId(modulePath, mod) { + return super.set(modulePath, mod); + } + set(fsPath, mod) { + return this.setByModuleId(this.normalizePath(fsPath), mod); + } + getByModuleId(modulePath) { + if (!super.has(modulePath)) + this.setByModuleId(modulePath, {}); + const mod = super.get(modulePath); + if (!mod.imports) { + Object.assign(mod, { + imports: /* @__PURE__ */ new Set(), + importers: /* @__PURE__ */ new Set() + }); + } + return mod; + } + get(fsPath) { + return this.getByModuleId(this.normalizePath(fsPath)); + } + deleteByModuleId(modulePath) { + return super.delete(modulePath); + } + delete(fsPath) { + return this.deleteByModuleId(this.normalizePath(fsPath)); + } + invalidateModule(mod) { + var _a, _b; + delete mod.evaluated; + delete mod.resolving; + delete mod.promise; + delete mod.exports; + (_a = mod.importers) == null ? void 0 : _a.clear(); + (_b = mod.imports) == null ? void 0 : _b.clear(); + return true; + } + /** + * Invalidate modules that dependent on the given modules, up to the main entry + */ + invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const mod = super.get(id); + if (mod == null ? void 0 : mod.importers) + this.invalidateDepTree(mod.importers, invalidated); + super.delete(id); + } + return invalidated; + } + /** + * Invalidate dependency modules of the given modules, down to the bottom-level dependencies + */ + invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const subIds = Array.from(super.entries()).filter(([, mod]) => { + var _a; + return (_a = mod.importers) == null ? void 0 : _a.has(id); + }).map(([key]) => key); + subIds.length && this.invalidateSubDepTree(subIds, invalidated); + super.delete(id); + } + return invalidated; + } + /** + * Return parsed source map based on inlined source map of the module + */ + getSourceMap(id) { + const cache = this.get(id); + if (cache.map) + return cache.map; + const map = cache.code && sourceMap.extractSourceMap(cache.code); + if (map) { + cache.map = map; + return map; + } + return null; + } +} +class ViteNodeRunner { + constructor(options) { + this.options = options; + this.root = options.root ?? process.cwd(); + this.moduleCache = options.moduleCache ?? new ModuleCacheMap(); + this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false); + } + root; + debug; + /** + * Holds the cache of modules + * Keys of the map are filepaths, or plain package names + */ + moduleCache; + async executeFile(file) { + const url = `/@fs/${utils.slash(pathe.resolve(file))}`; + return await this.cachedRequest(url, url, []); + } + async executeId(rawId) { + const [id, url] = await this.resolveUrl(rawId); + return await this.cachedRequest(id, url, []); + } + /** @internal */ + async cachedRequest(id, fsPath, callstack) { + const importee = callstack[callstack.length - 1]; + const mod = this.moduleCache.get(fsPath); + const { imports, importers } = mod; + if (importee) + importers.add(importee); + const getStack = () => `stack: +${[...callstack, fsPath].reverse().map((p) => ` - ${p}`).join("\n")}`; + if (callstack.includes(fsPath) || Array.from(imports.values()).some((i) => importers.has(i))) { + if (mod.exports) + return mod.exports; + } + let debugTimer; + if (this.debug) + debugTimer = setTimeout(() => console.warn(`[vite-node] module ${fsPath} takes over 2s to load. +${getStack()}`), 2e3); + try { + if (mod.promise) + return await mod.promise; + const promise = this.directRequest(id, fsPath, callstack); + Object.assign(mod, { promise, evaluated: false }); + return await promise; + } finally { + mod.evaluated = true; + if (debugTimer) + clearTimeout(debugTimer); + } + } + shouldResolveId(id, _importee) { + return !utils.isInternalRequest(id) && !utils.isNodeBuiltin(id) && !id.startsWith("data:"); + } + async _resolveUrl(id, importer) { + var _a, _b; + const dep = utils.normalizeRequestId(id, this.options.base); + if (!this.shouldResolveId(dep)) + return [dep, dep]; + const { path, exists } = utils.toFilePath(dep, this.root); + if (!this.options.resolveId || exists) + return [dep, path]; + const resolved = await this.options.resolveId(dep, importer); + if ((_b = (_a = resolved == null ? void 0 : resolved.meta) == null ? void 0 : _a["vite:alias"]) == null ? void 0 : _b.noResolved) { + const error = new Error( + `Cannot find module '${id}'${importer ? ` imported from '${importer}'` : ""}. + +- If you rely on tsconfig.json's "paths" to resolve modules, please install "vite-tsconfig-paths" plugin to handle module resolution. +- Make sure you don't have relative aliases in your Vitest config. Use absolute paths instead. Read more: https://vitest.dev/guide/common-errors` + ); + Object.defineProperty(error, "code", { value: "ERR_MODULE_NOT_FOUND", enumerable: true }); + Object.defineProperty(error, Symbol.for("vitest.error.not_found.data"), { value: { id: dep, importer }, enumerable: false }); + throw error; + } + const resolvedId = resolved ? utils.normalizeRequestId(resolved.id, this.options.base) : dep; + return [resolvedId, resolvedId]; + } + async resolveUrl(id, importee) { + const resolveKey = `resolve:${id}`; + this.moduleCache.setByModuleId(resolveKey, { resolving: true }); + try { + return await this._resolveUrl(id, importee); + } finally { + this.moduleCache.deleteByModuleId(resolveKey); + } + } + /** @internal */ + async dependencyRequest(id, fsPath, callstack) { + return await this.cachedRequest(id, fsPath, callstack); + } + /** @internal */ + async directRequest(id, fsPath, _callstack) { + const moduleId = utils.normalizeModuleId(fsPath); + const callstack = [..._callstack, moduleId]; + const mod = this.moduleCache.getByModuleId(moduleId); + const request = async (dep) => { + const [id2, depFsPath] = await this.resolveUrl(String(dep), fsPath); + const depMod = this.moduleCache.getByModuleId(depFsPath); + depMod.importers.add(moduleId); + mod.imports.add(depFsPath); + return this.dependencyRequest(id2, depFsPath, callstack); + }; + const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS; + if (id in requestStubs) + return requestStubs[id]; + let { code: transformed, externalize } = await this.options.fetchModule(id); + if (externalize) { + debugNative(externalize); + const exports2 = await this.interopedImport(externalize); + mod.exports = exports2; + return exports2; + } + if (transformed == null) + throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`); + const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = this.getContextPrimitives(); + const modulePath = utils.cleanUrl(moduleId); + const href = node_url.pathToFileURL(modulePath).href; + const __filename = node_url.fileURLToPath(href); + const __dirname = path.dirname(__filename); + const meta = { + url: href, + env, + filename: __filename, + dirname: __dirname + }; + const exports = Object2.create(null); + Object2.defineProperty(exports, Symbol2.toStringTag, { + value: "Module", + enumerable: false, + configurable: false + }); + const SYMBOL_NOT_DEFINED = Symbol2("not defined"); + let moduleExports = SYMBOL_NOT_DEFINED; + const cjsExports = new Proxy(exports, { + get: (target, p, receiver) => { + if (Reflect2.has(target, p)) + return Reflect2.get(target, p, receiver); + return Reflect2.get(Object2.prototype, p, receiver); + }, + getPrototypeOf: () => Object2.prototype, + set: (_, p, value) => { + if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) { + exportAll(cjsExports, value); + exports.default = value; + return true; + } + if (!Reflect2.has(exports, "default")) + exports.default = {}; + if (moduleExports !== SYMBOL_NOT_DEFINED && utils.isPrimitive(moduleExports)) { + defineExport(exports, p, () => void 0); + return true; + } + if (!utils.isPrimitive(exports.default)) + exports.default[p] = value; + if (p !== "default") + defineExport(exports, p, () => value); + return true; + } + }); + Object2.assign(mod, { code: transformed, exports }); + const moduleProxy = { + set exports(value) { + exportAll(cjsExports, value); + exports.default = value; + moduleExports = value; + }, + get exports() { + return cjsExports; + } + }; + let hotContext; + if (this.options.createHotContext) { + Object2.defineProperty(meta, "hot", { + enumerable: true, + get: () => { + var _a, _b; + hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId)); + return hotContext; + }, + set: (value) => { + hotContext = value; + } + }); + } + const context = this.prepareContext({ + // esm transformed by Vite + __vite_ssr_import__: request, + __vite_ssr_dynamic_import__: request, + __vite_ssr_exports__: exports, + __vite_ssr_exportAll__: (obj) => exportAll(exports, obj), + __vite_ssr_import_meta__: meta, + // cjs compact + require: node_module.createRequire(href), + exports: cjsExports, + module: moduleProxy, + __filename, + __dirname + }); + debugExecute(__filename); + if (transformed[0] === "#") + transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length)); + await this.runModule(context, transformed); + return exports; + } + getContextPrimitives() { + return { Object, Reflect, Symbol }; + } + async runModule(context, transformed) { + const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`; + const code = `${codeDefinition}${transformed} +}}`; + const options = { + filename: context.__filename, + lineOffset: 0, + columnOffset: -codeDefinition.length + }; + const fn = vm.runInThisContext(code, options); + await fn(...Object.values(context)); + } + prepareContext(context) { + return context; + } + /** + * Define if a module should be interop-ed + * This function mostly for the ability to override by subclass + */ + shouldInterop(path, mod) { + if (this.options.interopDefault === false) + return false; + return !path.endsWith(".mjs") && "default" in mod; + } + importExternalModule(path) { + return import(path); + } + /** + * Import a module and interop it + */ + async interopedImport(path) { + const importedModule = await this.importExternalModule(path); + if (!this.shouldInterop(path, importedModule)) + return importedModule; + const { mod, defaultExport } = interopModule(importedModule); + return new Proxy(mod, { + get(mod2, prop) { + if (prop === "default") + return defaultExport; + return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]); + }, + has(mod2, prop) { + if (prop === "default") + return defaultExport !== void 0; + return prop in mod2 || defaultExport && prop in defaultExport; + }, + getOwnPropertyDescriptor(mod2, prop) { + const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop); + if (descriptor) + return descriptor; + if (prop === "default" && defaultExport !== void 0) { + return { + value: defaultExport, + enumerable: true, + configurable: true + }; + } + } + }); + } +} +function interopModule(mod) { + if (utils.isPrimitive(mod)) { + return { + mod: { default: mod }, + defaultExport: mod + }; + } + let defaultExport = "default" in mod ? mod.default : mod; + if (!utils.isPrimitive(defaultExport) && "__esModule" in defaultExport) { + mod = defaultExport; + if ("default" in defaultExport) + defaultExport = defaultExport.default; + } + return { mod, defaultExport }; +} +function defineExport(exports, key, value) { + Object.defineProperty(exports, key, { + enumerable: true, + configurable: true, + get: value + }); +} +function exportAll(exports, sourceModule) { + if (exports === sourceModule) + return; + if (utils.isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) + return; + for (const key in sourceModule) { + if (key !== "default") { + try { + defineExport(exports, key, () => sourceModule[key]); + } catch (_err) { + } + } + } +} + +exports.DEFAULT_REQUEST_STUBS = DEFAULT_REQUEST_STUBS; +exports.ModuleCacheMap = ModuleCacheMap; +exports.ViteNodeRunner = ViteNodeRunner; diff --git a/web/node_modules/vite-node/dist/client.d.ts b/web/node_modules/vite-node/dist/client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84a03751bce582291783d28b544275851de50c11 --- /dev/null +++ b/web/node_modules/vite-node/dist/client.d.ts @@ -0,0 +1,2 @@ +export { e as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, a as ViteNodeRunner } from './index-WT31LSgS.js'; +import './trace-mapping.d-xyIfZtPm.js'; diff --git a/web/node_modules/vite-node/dist/client.mjs b/web/node_modules/vite-node/dist/client.mjs new file mode 100644 index 0000000000000000000000000000000000000000..545f6627ab665e125701262ea3ee3fbfcf1a1b09 --- /dev/null +++ b/web/node_modules/vite-node/dist/client.mjs @@ -0,0 +1,450 @@ +import { createRequire } from 'node:module'; +import { dirname } from 'node:path'; +import { pathToFileURL, fileURLToPath } from 'node:url'; +import vm from 'node:vm'; +import { resolve } from 'pathe'; +import createDebug from 'debug'; +import { createImportMetaEnvProxy, normalizeModuleId, slash, isInternalRequest, isNodeBuiltin, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs'; +import { extractSourceMap } from './source-map.mjs'; +import 'node:fs'; + +const { setTimeout, clearTimeout } = globalThis; +const debugExecute = createDebug("vite-node:client:execute"); +const debugNative = createDebug("vite-node:client:native"); +const clientStub = { + injectQuery: (id) => id, + createHotContext: () => { + return { + accept: () => { + }, + prune: () => { + }, + dispose: () => { + }, + decline: () => { + }, + invalidate: () => { + }, + on: () => { + }, + send: () => { + } + }; + }, + updateStyle: () => { + }, + removeStyle: () => { + } +}; +const env = createImportMetaEnvProxy(); +const DEFAULT_REQUEST_STUBS = { + "/@vite/client": clientStub, + "@vite/client": clientStub +}; +class ModuleCacheMap extends Map { + normalizePath(fsPath) { + return normalizeModuleId(fsPath); + } + /** + * Assign partial data to the map + */ + update(fsPath, mod) { + fsPath = this.normalizePath(fsPath); + if (!super.has(fsPath)) + this.setByModuleId(fsPath, mod); + else + Object.assign(super.get(fsPath), mod); + return this; + } + setByModuleId(modulePath, mod) { + return super.set(modulePath, mod); + } + set(fsPath, mod) { + return this.setByModuleId(this.normalizePath(fsPath), mod); + } + getByModuleId(modulePath) { + if (!super.has(modulePath)) + this.setByModuleId(modulePath, {}); + const mod = super.get(modulePath); + if (!mod.imports) { + Object.assign(mod, { + imports: /* @__PURE__ */ new Set(), + importers: /* @__PURE__ */ new Set() + }); + } + return mod; + } + get(fsPath) { + return this.getByModuleId(this.normalizePath(fsPath)); + } + deleteByModuleId(modulePath) { + return super.delete(modulePath); + } + delete(fsPath) { + return this.deleteByModuleId(this.normalizePath(fsPath)); + } + invalidateModule(mod) { + var _a, _b; + delete mod.evaluated; + delete mod.resolving; + delete mod.promise; + delete mod.exports; + (_a = mod.importers) == null ? void 0 : _a.clear(); + (_b = mod.imports) == null ? void 0 : _b.clear(); + return true; + } + /** + * Invalidate modules that dependent on the given modules, up to the main entry + */ + invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const mod = super.get(id); + if (mod == null ? void 0 : mod.importers) + this.invalidateDepTree(mod.importers, invalidated); + super.delete(id); + } + return invalidated; + } + /** + * Invalidate dependency modules of the given modules, down to the bottom-level dependencies + */ + invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const subIds = Array.from(super.entries()).filter(([, mod]) => { + var _a; + return (_a = mod.importers) == null ? void 0 : _a.has(id); + }).map(([key]) => key); + subIds.length && this.invalidateSubDepTree(subIds, invalidated); + super.delete(id); + } + return invalidated; + } + /** + * Return parsed source map based on inlined source map of the module + */ + getSourceMap(id) { + const cache = this.get(id); + if (cache.map) + return cache.map; + const map = cache.code && extractSourceMap(cache.code); + if (map) { + cache.map = map; + return map; + } + return null; + } +} +class ViteNodeRunner { + constructor(options) { + this.options = options; + this.root = options.root ?? process.cwd(); + this.moduleCache = options.moduleCache ?? new ModuleCacheMap(); + this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false); + } + root; + debug; + /** + * Holds the cache of modules + * Keys of the map are filepaths, or plain package names + */ + moduleCache; + async executeFile(file) { + const url = `/@fs/${slash(resolve(file))}`; + return await this.cachedRequest(url, url, []); + } + async executeId(rawId) { + const [id, url] = await this.resolveUrl(rawId); + return await this.cachedRequest(id, url, []); + } + /** @internal */ + async cachedRequest(id, fsPath, callstack) { + const importee = callstack[callstack.length - 1]; + const mod = this.moduleCache.get(fsPath); + const { imports, importers } = mod; + if (importee) + importers.add(importee); + const getStack = () => `stack: +${[...callstack, fsPath].reverse().map((p) => ` - ${p}`).join("\n")}`; + if (callstack.includes(fsPath) || Array.from(imports.values()).some((i) => importers.has(i))) { + if (mod.exports) + return mod.exports; + } + let debugTimer; + if (this.debug) + debugTimer = setTimeout(() => console.warn(`[vite-node] module ${fsPath} takes over 2s to load. +${getStack()}`), 2e3); + try { + if (mod.promise) + return await mod.promise; + const promise = this.directRequest(id, fsPath, callstack); + Object.assign(mod, { promise, evaluated: false }); + return await promise; + } finally { + mod.evaluated = true; + if (debugTimer) + clearTimeout(debugTimer); + } + } + shouldResolveId(id, _importee) { + return !isInternalRequest(id) && !isNodeBuiltin(id) && !id.startsWith("data:"); + } + async _resolveUrl(id, importer) { + var _a, _b; + const dep = normalizeRequestId(id, this.options.base); + if (!this.shouldResolveId(dep)) + return [dep, dep]; + const { path, exists } = toFilePath(dep, this.root); + if (!this.options.resolveId || exists) + return [dep, path]; + const resolved = await this.options.resolveId(dep, importer); + if ((_b = (_a = resolved == null ? void 0 : resolved.meta) == null ? void 0 : _a["vite:alias"]) == null ? void 0 : _b.noResolved) { + const error = new Error( + `Cannot find module '${id}'${importer ? ` imported from '${importer}'` : ""}. + +- If you rely on tsconfig.json's "paths" to resolve modules, please install "vite-tsconfig-paths" plugin to handle module resolution. +- Make sure you don't have relative aliases in your Vitest config. Use absolute paths instead. Read more: https://vitest.dev/guide/common-errors` + ); + Object.defineProperty(error, "code", { value: "ERR_MODULE_NOT_FOUND", enumerable: true }); + Object.defineProperty(error, Symbol.for("vitest.error.not_found.data"), { value: { id: dep, importer }, enumerable: false }); + throw error; + } + const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : dep; + return [resolvedId, resolvedId]; + } + async resolveUrl(id, importee) { + const resolveKey = `resolve:${id}`; + this.moduleCache.setByModuleId(resolveKey, { resolving: true }); + try { + return await this._resolveUrl(id, importee); + } finally { + this.moduleCache.deleteByModuleId(resolveKey); + } + } + /** @internal */ + async dependencyRequest(id, fsPath, callstack) { + return await this.cachedRequest(id, fsPath, callstack); + } + /** @internal */ + async directRequest(id, fsPath, _callstack) { + const moduleId = normalizeModuleId(fsPath); + const callstack = [..._callstack, moduleId]; + const mod = this.moduleCache.getByModuleId(moduleId); + const request = async (dep) => { + const [id2, depFsPath] = await this.resolveUrl(String(dep), fsPath); + const depMod = this.moduleCache.getByModuleId(depFsPath); + depMod.importers.add(moduleId); + mod.imports.add(depFsPath); + return this.dependencyRequest(id2, depFsPath, callstack); + }; + const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS; + if (id in requestStubs) + return requestStubs[id]; + let { code: transformed, externalize } = await this.options.fetchModule(id); + if (externalize) { + debugNative(externalize); + const exports2 = await this.interopedImport(externalize); + mod.exports = exports2; + return exports2; + } + if (transformed == null) + throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`); + const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = this.getContextPrimitives(); + const modulePath = cleanUrl(moduleId); + const href = pathToFileURL(modulePath).href; + const __filename = fileURLToPath(href); + const __dirname = dirname(__filename); + const meta = { + url: href, + env, + filename: __filename, + dirname: __dirname + }; + const exports = Object2.create(null); + Object2.defineProperty(exports, Symbol2.toStringTag, { + value: "Module", + enumerable: false, + configurable: false + }); + const SYMBOL_NOT_DEFINED = Symbol2("not defined"); + let moduleExports = SYMBOL_NOT_DEFINED; + const cjsExports = new Proxy(exports, { + get: (target, p, receiver) => { + if (Reflect2.has(target, p)) + return Reflect2.get(target, p, receiver); + return Reflect2.get(Object2.prototype, p, receiver); + }, + getPrototypeOf: () => Object2.prototype, + set: (_, p, value) => { + if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) { + exportAll(cjsExports, value); + exports.default = value; + return true; + } + if (!Reflect2.has(exports, "default")) + exports.default = {}; + if (moduleExports !== SYMBOL_NOT_DEFINED && isPrimitive(moduleExports)) { + defineExport(exports, p, () => void 0); + return true; + } + if (!isPrimitive(exports.default)) + exports.default[p] = value; + if (p !== "default") + defineExport(exports, p, () => value); + return true; + } + }); + Object2.assign(mod, { code: transformed, exports }); + const moduleProxy = { + set exports(value) { + exportAll(cjsExports, value); + exports.default = value; + moduleExports = value; + }, + get exports() { + return cjsExports; + } + }; + let hotContext; + if (this.options.createHotContext) { + Object2.defineProperty(meta, "hot", { + enumerable: true, + get: () => { + var _a, _b; + hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId)); + return hotContext; + }, + set: (value) => { + hotContext = value; + } + }); + } + const context = this.prepareContext({ + // esm transformed by Vite + __vite_ssr_import__: request, + __vite_ssr_dynamic_import__: request, + __vite_ssr_exports__: exports, + __vite_ssr_exportAll__: (obj) => exportAll(exports, obj), + __vite_ssr_import_meta__: meta, + // cjs compact + require: createRequire(href), + exports: cjsExports, + module: moduleProxy, + __filename, + __dirname + }); + debugExecute(__filename); + if (transformed[0] === "#") + transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length)); + await this.runModule(context, transformed); + return exports; + } + getContextPrimitives() { + return { Object, Reflect, Symbol }; + } + async runModule(context, transformed) { + const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`; + const code = `${codeDefinition}${transformed} +}}`; + const options = { + filename: context.__filename, + lineOffset: 0, + columnOffset: -codeDefinition.length + }; + const fn = vm.runInThisContext(code, options); + await fn(...Object.values(context)); + } + prepareContext(context) { + return context; + } + /** + * Define if a module should be interop-ed + * This function mostly for the ability to override by subclass + */ + shouldInterop(path, mod) { + if (this.options.interopDefault === false) + return false; + return !path.endsWith(".mjs") && "default" in mod; + } + importExternalModule(path) { + return import(path); + } + /** + * Import a module and interop it + */ + async interopedImport(path) { + const importedModule = await this.importExternalModule(path); + if (!this.shouldInterop(path, importedModule)) + return importedModule; + const { mod, defaultExport } = interopModule(importedModule); + return new Proxy(mod, { + get(mod2, prop) { + if (prop === "default") + return defaultExport; + return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]); + }, + has(mod2, prop) { + if (prop === "default") + return defaultExport !== void 0; + return prop in mod2 || defaultExport && prop in defaultExport; + }, + getOwnPropertyDescriptor(mod2, prop) { + const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop); + if (descriptor) + return descriptor; + if (prop === "default" && defaultExport !== void 0) { + return { + value: defaultExport, + enumerable: true, + configurable: true + }; + } + } + }); + } +} +function interopModule(mod) { + if (isPrimitive(mod)) { + return { + mod: { default: mod }, + defaultExport: mod + }; + } + let defaultExport = "default" in mod ? mod.default : mod; + if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) { + mod = defaultExport; + if ("default" in defaultExport) + defaultExport = defaultExport.default; + } + return { mod, defaultExport }; +} +function defineExport(exports, key, value) { + Object.defineProperty(exports, key, { + enumerable: true, + configurable: true, + get: value + }); +} +function exportAll(exports, sourceModule) { + if (exports === sourceModule) + return; + if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) + return; + for (const key in sourceModule) { + if (key !== "default") { + try { + defineExport(exports, key, () => sourceModule[key]); + } catch (_err) { + } + } + } +} + +export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner }; diff --git a/web/node_modules/vite-node/dist/constants.cjs b/web/node_modules/vite-node/dist/constants.cjs new file mode 100644 index 0000000000000000000000000000000000000000..92721ad0bc0885b54d094d8952fe7346ff5b5c55 --- /dev/null +++ b/web/node_modules/vite-node/dist/constants.cjs @@ -0,0 +1,39 @@ +'use strict'; + +const KNOWN_ASSET_TYPES = [ + // images + "apng", + "png", + "jpe?g", + "jfif", + "pjpeg", + "pjp", + "gif", + "svg", + "ico", + "webp", + "avif", + // media + "mp4", + "webm", + "ogg", + "mp3", + "wav", + "flac", + "aac", + // fonts + "woff2?", + "eot", + "ttf", + "otf", + // other + "webmanifest", + "pdf", + "txt" +]; +const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`); +const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; + +exports.CSS_LANGS_RE = CSS_LANGS_RE; +exports.KNOWN_ASSET_RE = KNOWN_ASSET_RE; +exports.KNOWN_ASSET_TYPES = KNOWN_ASSET_TYPES; diff --git a/web/node_modules/vite-node/dist/constants.d.ts b/web/node_modules/vite-node/dist/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..201b69a968b810033b39a622f0d8c56e012d5f15 --- /dev/null +++ b/web/node_modules/vite-node/dist/constants.d.ts @@ -0,0 +1,5 @@ +declare const KNOWN_ASSET_TYPES: string[]; +declare const KNOWN_ASSET_RE: RegExp; +declare const CSS_LANGS_RE: RegExp; + +export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES }; diff --git a/web/node_modules/vite-node/dist/constants.mjs b/web/node_modules/vite-node/dist/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6eb2401c38e867cbcf42a282bb81054ca6d8d71c --- /dev/null +++ b/web/node_modules/vite-node/dist/constants.mjs @@ -0,0 +1,35 @@ +const KNOWN_ASSET_TYPES = [ + // images + "apng", + "png", + "jpe?g", + "jfif", + "pjpeg", + "pjp", + "gif", + "svg", + "ico", + "webp", + "avif", + // media + "mp4", + "webm", + "ogg", + "mp3", + "wav", + "flac", + "aac", + // fonts + "woff2?", + "eot", + "ttf", + "otf", + // other + "webmanifest", + "pdf", + "txt" +]; +const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`); +const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; + +export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES }; diff --git a/web/node_modules/vite-node/dist/hmr.cjs b/web/node_modules/vite-node/dist/hmr.cjs new file mode 100644 index 0000000000000000000000000000000000000000..547d365594ec71bf2eff565d782ec41e5e141def --- /dev/null +++ b/web/node_modules/vite-node/dist/hmr.cjs @@ -0,0 +1,21 @@ +'use strict'; + +var hmr = require('./chunk-hmr.cjs'); +require('node:events'); +require('picocolors'); +require('debug'); +require('./utils.cjs'); +require('node:url'); +require('node:module'); +require('node:fs'); +require('pathe'); + + + +exports.createHmrEmitter = hmr.createHmrEmitter; +exports.createHotContext = hmr.createHotContext; +exports.getCache = hmr.getCache; +exports.handleMessage = hmr.handleMessage; +exports.reload = hmr.reload; +exports.sendMessageBuffer = hmr.sendMessageBuffer; +exports.viteNodeHmrPlugin = hmr.viteNodeHmrPlugin; diff --git a/web/node_modules/vite-node/dist/hmr.d.ts b/web/node_modules/vite-node/dist/hmr.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9bbb3877cab8c616d337d5b0d07f6300822e786 --- /dev/null +++ b/web/node_modules/vite-node/dist/hmr.d.ts @@ -0,0 +1,54 @@ +import { EventEmitter } from 'node:events'; +import { HMRPayload, Plugin } from 'vite'; +import { C as CustomEventMap, a as ViteNodeRunner, H as HMRPayload$1, b as HotContext } from './index-WT31LSgS.js'; +import './trace-mapping.d-xyIfZtPm.js'; + +type EventType = string | symbol; +type Handler = (event: T) => void; +interface Emitter> { + on: (type: Key, handler: Handler) => void; + off: (type: Key, handler?: Handler) => void; + emit: ((type: Key, event: Events[Key]) => void) & ((type: undefined extends Events[Key] ? Key : never) => void); +} +type HMREmitter = Emitter<{ + message: HMRPayload; +}> & EventEmitter; +declare module 'vite' { + interface ViteDevServer { + emitter: HMREmitter; + } +} +declare function createHmrEmitter(): HMREmitter; +declare function viteNodeHmrPlugin(): Plugin; + +type ModuleNamespace = Record & { + [Symbol.toStringTag]: 'Module'; +}; +type InferCustomEventPayload = T extends keyof CustomEventMap ? CustomEventMap[T] : any; +interface HotModule { + id: string; + callbacks: HotCallback[]; +} +interface HotCallback { + deps: string[]; + fn: (modules: (ModuleNamespace | undefined)[]) => void; +} +interface CacheData { + hotModulesMap: Map; + dataMap: Map; + disposeMap: Map void | Promise>; + pruneMap: Map void | Promise>; + customListenersMap: Map void)[]>; + ctxToListenersMap: Map void)[]>>; + messageBuffer: string[]; + isFirstUpdate: boolean; + pending: boolean; + queued: Promise<(() => void) | undefined>[]; +} +declare function getCache(runner: ViteNodeRunner): CacheData; +declare function sendMessageBuffer(runner: ViteNodeRunner, emitter: HMREmitter): void; +declare function reload(runner: ViteNodeRunner, files: string[]): Promise; +declare function handleMessage(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], payload: HMRPayload$1): Promise; +declare function createHotContext(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], ownerPath: string): HotContext; + +export { type Emitter, type EventType, type HMREmitter, type Handler, type HotCallback, type HotModule, type InferCustomEventPayload, type ModuleNamespace, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin }; diff --git a/web/node_modules/vite-node/dist/hmr.mjs b/web/node_modules/vite-node/dist/hmr.mjs new file mode 100644 index 0000000000000000000000000000000000000000..de61e71e4c7c236fb9bb265cecf69e1fa863af31 --- /dev/null +++ b/web/node_modules/vite-node/dist/hmr.mjs @@ -0,0 +1,9 @@ +export { c as createHmrEmitter, a as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs'; +import 'node:events'; +import 'picocolors'; +import 'debug'; +import './utils.mjs'; +import 'node:url'; +import 'node:module'; +import 'node:fs'; +import 'pathe'; diff --git a/web/node_modules/vite-node/dist/index-WT31LSgS.d.ts b/web/node_modules/vite-node/dist/index-WT31LSgS.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b34055b290be22472b0620a297749ee2dcbc7db3 --- /dev/null +++ b/web/node_modules/vite-node/dist/index-WT31LSgS.d.ts @@ -0,0 +1,302 @@ +import { E as EncodedSourceMap } from './trace-mapping.d-xyIfZtPm.js'; + +type HMRPayload = + | ConnectedPayload + | UpdatePayload + | FullReloadPayload + | CustomPayload + | ErrorPayload + | PrunePayload + +interface ConnectedPayload { + type: 'connected' +} + +interface UpdatePayload { + type: 'update' + updates: Update[] +} + +interface Update { + type: 'js-update' | 'css-update' + path: string + acceptedPath: string + timestamp: number + /** + * @experimental internal + */ + explicitImportRequired?: boolean | undefined +} + +interface PrunePayload { + type: 'prune' + paths: string[] +} + +interface FullReloadPayload { + type: 'full-reload' + path?: string +} + +interface CustomPayload { + type: 'custom' + event: string + data?: any +} + +interface ErrorPayload { + type: 'error' + err: { + [name: string]: any + message: string + stack: string + id?: string + frame?: string + plugin?: string + pluginCode?: string + loc?: { + file?: string + line: number + column: number + } + } +} + +interface CustomEventMap { + 'vite:beforeUpdate': UpdatePayload + 'vite:afterUpdate': UpdatePayload + 'vite:beforePrune': PrunePayload + 'vite:beforeFullReload': FullReloadPayload + 'vite:error': ErrorPayload + 'vite:invalidate': InvalidatePayload + 'vite:ws:connect': WebSocketConnectionPayload + 'vite:ws:disconnect': WebSocketConnectionPayload +} + +interface WebSocketConnectionPayload { + /** + * @experimental + * We expose this instance experimentally to see potential usage. + * This might be removed in the future if we didn't find reasonable use cases. + * If you find this useful, please open an issue with details so we can discuss and make it stable API. + */ + webSocket: WebSocket +} + +interface InvalidatePayload { + path: string + message: string | undefined +} + +type InferCustomEventPayload = + T extends keyof CustomEventMap ? CustomEventMap[T] : any + +type ModuleNamespace = Record & { + [Symbol.toStringTag]: 'Module' +} + +interface ViteHotContext { + readonly data: any + + accept(): void + accept(cb: (mod: ModuleNamespace | undefined) => void): void + accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void + accept( + deps: readonly string[], + cb: (mods: Array) => void, + ): void + + acceptExports( + exportNames: string | readonly string[], + cb?: (mod: ModuleNamespace | undefined) => void, + ): void + + dispose(cb: (data: any) => void): void + prune(cb: (data: any) => void): void + invalidate(message?: string): void + + on( + event: T, + cb: (payload: InferCustomEventPayload) => void, + ): void + off( + event: T, + cb: (payload: InferCustomEventPayload) => void, + ): void + send(event: T, data?: InferCustomEventPayload): void +} + +declare const DEFAULT_REQUEST_STUBS: Record>; +declare class ModuleCacheMap extends Map { + normalizePath(fsPath: string): string; + /** + * Assign partial data to the map + */ + update(fsPath: string, mod: ModuleCache): this; + setByModuleId(modulePath: string, mod: ModuleCache): this; + set(fsPath: string, mod: ModuleCache): this; + getByModuleId(modulePath: string): ModuleCache & Required>; + get(fsPath: string): ModuleCache & Required>; + deleteByModuleId(modulePath: string): boolean; + delete(fsPath: string): boolean; + invalidateModule(mod: ModuleCache): boolean; + /** + * Invalidate modules that dependent on the given modules, up to the main entry + */ + invalidateDepTree(ids: string[] | Set, invalidated?: Set): Set; + /** + * Invalidate dependency modules of the given modules, down to the bottom-level dependencies + */ + invalidateSubDepTree(ids: string[] | Set, invalidated?: Set): Set; + /** + * Return parsed source map based on inlined source map of the module + */ + getSourceMap(id: string): EncodedSourceMap | null; +} +declare class ViteNodeRunner { + options: ViteNodeRunnerOptions; + root: string; + debug: boolean; + /** + * Holds the cache of modules + * Keys of the map are filepaths, or plain package names + */ + moduleCache: ModuleCacheMap; + constructor(options: ViteNodeRunnerOptions); + executeFile(file: string): Promise; + executeId(rawId: string): Promise; + /** @internal */ + cachedRequest(id: string, fsPath: string, callstack: string[]): Promise; + shouldResolveId(id: string, _importee?: string): boolean; + private _resolveUrl; + resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]>; + /** @internal */ + dependencyRequest(id: string, fsPath: string, callstack: string[]): Promise; + /** @internal */ + directRequest(id: string, fsPath: string, _callstack: string[]): Promise; + protected getContextPrimitives(): { + Object: ObjectConstructor; + Reflect: typeof Reflect; + Symbol: SymbolConstructor; + }; + protected runModule(context: Record, transformed: string): Promise; + prepareContext(context: Record): Record; + /** + * Define if a module should be interop-ed + * This function mostly for the ability to override by subclass + */ + shouldInterop(path: string, mod: any): boolean; + protected importExternalModule(path: string): Promise; + /** + * Import a module and interop it + */ + interopedImport(path: string): Promise; +} + +type Nullable = T | null | undefined; +type Arrayable = T | Array; +type Awaitable = T | PromiseLike; +interface DepsHandlingOptions { + external?: (string | RegExp)[]; + inline?: (string | RegExp)[] | true; + /** + * A list of directories that are considered to hold Node.js modules + * Have to include "/" at the start and end of the path + * + * Vite-Node checks the whole absolute path of the import, so make sure you don't include + * unwanted files accidentally + * @default ['/node_modules/'] + */ + moduleDirectories?: string[]; + cacheDir?: string; + /** + * Try to guess the CJS version of a package when it's invalid ESM + * @default false + */ + fallbackCJS?: boolean; +} +interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +interface RawSourceMap extends StartOfSourceMap { + version: number; + sources: string[]; + names: string[]; + sourcesContent?: (string | null)[]; + mappings: string; +} +interface FetchResult { + code?: string; + externalize?: string; + map?: EncodedSourceMap | null; +} +type HotContext = Omit; +type FetchFunction = (id: string) => Promise; +type ResolveIdFunction = (id: string, importer?: string) => Awaitable; +type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext; +interface ModuleCache { + promise?: Promise; + exports?: any; + evaluated?: boolean; + resolving?: boolean; + code?: string; + map?: EncodedSourceMap; + /** + * Module ids that imports this module + */ + importers?: Set; + imports?: Set; +} +interface ViteNodeRunnerOptions { + root: string; + fetchModule: FetchFunction; + resolveId?: ResolveIdFunction; + createHotContext?: CreateHotContextFunction; + base?: string; + moduleCache?: ModuleCacheMap; + interopDefault?: boolean; + requestStubs?: Record; + debug?: boolean; +} +interface ViteNodeResolveId { + external?: boolean | 'absolute' | 'relative'; + id: string; + meta?: Record | null; + moduleSideEffects?: boolean | 'no-treeshake' | null; + syntheticNamedExports?: boolean | string | null; +} +interface ViteNodeServerOptions { + /** + * Inject inline sourcemap to modules + * @default 'inline' + */ + sourcemap?: 'inline' | boolean; + /** + * Deps handling + */ + deps?: DepsHandlingOptions; + /** + * Transform method for modules + */ + transformMode?: { + ssr?: RegExp[]; + web?: RegExp[]; + }; + debug?: DebuggerOptions; +} +interface DebuggerOptions { + /** + * Dump the transformed module to filesystem + * Passing a string will dump to the specified path + */ + dumpModules?: boolean | string; + /** + * Read dumpped module from filesystem whenever exists. + * Useful for debugging by modifying the dump result from the filesystem. + */ + loadDumppedModules?: boolean; +} + +export { type Arrayable as A, type CustomEventMap as C, type DebuggerOptions as D, type FetchResult as F, type HMRPayload as H, ModuleCacheMap as M, type Nullable as N, type RawSourceMap as R, type StartOfSourceMap as S, type ViteNodeServerOptions as V, ViteNodeRunner as a, type HotContext as b, type DepsHandlingOptions as c, type ViteNodeResolveId as d, DEFAULT_REQUEST_STUBS as e, type Awaitable as f, type FetchFunction as g, type ResolveIdFunction as h, type CreateHotContextFunction as i, type ModuleCache as j, type ViteNodeRunnerOptions as k }; diff --git a/web/node_modules/vite-node/dist/index.cjs b/web/node_modules/vite-node/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..eb109abbed09786c904e3c767f123a1a0dae21ec --- /dev/null +++ b/web/node_modules/vite-node/dist/index.cjs @@ -0,0 +1,2 @@ +'use strict'; + diff --git a/web/node_modules/vite-node/dist/index.d.ts b/web/node_modules/vite-node/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c1014e36f5a4ef05dc2793e92630a5a467ec0c2 --- /dev/null +++ b/web/node_modules/vite-node/dist/index.d.ts @@ -0,0 +1,2 @@ +export { A as Arrayable, f as Awaitable, i as CreateHotContextFunction, D as DebuggerOptions, c as DepsHandlingOptions, g as FetchFunction, F as FetchResult, b as HotContext, j as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, h as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, k as ViteNodeRunnerOptions, V as ViteNodeServerOptions } from './index-WT31LSgS.js'; +export { D as DecodedSourceMap, E as EncodedSourceMap, S as SourceMapInput } from './trace-mapping.d-xyIfZtPm.js'; diff --git a/web/node_modules/vite-node/dist/index.mjs b/web/node_modules/vite-node/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/web/node_modules/vite-node/dist/index.mjs @@ -0,0 +1 @@ + diff --git a/web/node_modules/vite-node/dist/server.cjs b/web/node_modules/vite-node/dist/server.cjs new file mode 100644 index 0000000000000000000000000000000000000000..76a18d1646518f734137ef31a14336f264b96e76 --- /dev/null +++ b/web/node_modules/vite-node/dist/server.cjs @@ -0,0 +1,428 @@ +'use strict'; + +var node_perf_hooks = require('node:perf_hooks'); +var fs = require('node:fs'); +var assert = require('node:assert'); +var pathe = require('pathe'); +var createDebug = require('debug'); +var utils = require('./utils.cjs'); +var constants = require('./constants.cjs'); +var c = require('picocolors'); +var sourceMap = require('./source-map.cjs'); +require('node:url'); +require('node:module'); +require('node:path'); + +const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]); +const ESM_SYNTAX_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; +const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/; +const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/; +const defaultInline = [ + /virtual:/, + /\.[mc]?ts$/, + // special Vite query strings + /[?&](init|raw|url|inline)\b/, + // Vite returns a string for assets imports, even if it's inside "node_modules" + new RegExp(`\\.(${constants.KNOWN_ASSET_TYPES.join("|")})$`) +]; +const depsExternal = [ + /\/node_modules\/.*\.cjs\.js$/, + /\/node_modules\/.*\.mjs$/ +]; +function guessCJSversion(id) { + if (id.match(ESM_EXT_RE)) { + for (const i of [ + id.replace(ESM_EXT_RE, ".mjs"), + id.replace(ESM_EXT_RE, ".umd.js"), + id.replace(ESM_EXT_RE, ".cjs.js"), + id.replace(ESM_EXT_RE, ".js") + ]) { + if (fs.existsSync(i)) + return i; + } + } + if (id.match(ESM_FOLDER_RE)) { + for (const i of [ + id.replace(ESM_FOLDER_RE, "/umd/$1"), + id.replace(ESM_FOLDER_RE, "/cjs/$1"), + id.replace(ESM_FOLDER_RE, "/lib/$1"), + id.replace(ESM_FOLDER_RE, "/$1") + ]) { + if (fs.existsSync(i)) + return i; + } + } +} +async function isValidNodeImport(id) { + const extension = pathe.extname(id); + if (BUILTIN_EXTENSIONS.has(extension)) + return true; + if (extension !== ".js") + return false; + if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(id)) + return false; + id = id.replace("file:///", ""); + const package_ = await utils.findNearestPackageData(pathe.dirname(id)); + if (package_.type === "module") + return true; + const code = await fs.promises.readFile(id, "utf8").catch(() => ""); + return !ESM_SYNTAX_RE.test(code); +} +const _defaultExternalizeCache = /* @__PURE__ */ new Map(); +async function shouldExternalize(id, options, cache = _defaultExternalizeCache) { + if (!cache.has(id)) + cache.set(id, _shouldExternalize(id, options)); + return cache.get(id); +} +async function _shouldExternalize(id, options) { + if (utils.isNodeBuiltin(id)) + return id; + if (id.startsWith("data:") || /^(https?:)?\/\//.test(id)) + return id; + id = patchWindowsImportPath(id); + if ((options == null ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) + return id; + const moduleDirectories = (options == null ? void 0 : options.moduleDirectories) || ["/node_modules/"]; + if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.inline)) + return false; + if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.external)) + return id; + const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir)); + const guessCJS = isLibraryModule && (options == null ? void 0 : options.fallbackCJS); + id = guessCJS ? guessCJSversion(id) || id : id; + if (matchExternalizePattern(id, moduleDirectories, defaultInline)) + return false; + if (matchExternalizePattern(id, moduleDirectories, depsExternal)) + return id; + if (isLibraryModule && await isValidNodeImport(id)) + return id; + return false; +} +function matchExternalizePattern(id, moduleDirectories, patterns) { + if (patterns == null) + return false; + if (patterns === true) + return true; + for (const ex of patterns) { + if (typeof ex === "string") { + if (moduleDirectories.some((dir) => id.includes(pathe.join(dir, ex)))) + return true; + } else { + if (ex.test(id)) + return true; + } + } + return false; +} +function patchWindowsImportPath(path) { + if (path.match(/^\w:\\/)) + return `file:///${utils.slash(path)}`; + else if (path.match(/^\w:\//)) + return `file:///${path}`; + else + return path; +} + +function hashCode(s) { + return s.split("").reduce((a, b) => { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0); +} +class Debugger { + constructor(root, options) { + this.options = options; + if (options.dumpModules) + this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules); + if (this.dumpDir) { + if (options.loadDumppedModules) + console.info(c.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`)); + else + console.info(c.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`)); + } + this.initPromise = this.clearDump(); + } + dumpDir; + initPromise; + externalizeMap = /* @__PURE__ */ new Map(); + async clearDump() { + if (!this.dumpDir) + return; + if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir)) + await fs.promises.rm(this.dumpDir, { recursive: true, force: true }); + await fs.promises.mkdir(this.dumpDir, { recursive: true }); + } + encodeId(id) { + return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`; + } + async recordExternalize(id, path) { + if (!this.dumpDir) + return; + this.externalizeMap.set(id, path); + await this.writeInfo(); + } + async dumpFile(id, result) { + if (!result || !this.dumpDir) + return; + await this.initPromise; + const name = this.encodeId(id); + return await fs.promises.writeFile(pathe.join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")} +${result.code}`, "utf-8"); + } + async loadDump(id) { + if (!this.dumpDir) + return null; + await this.initPromise; + const name = this.encodeId(id); + const path = pathe.join(this.dumpDir, name); + if (!fs.existsSync(path)) + return null; + const code = await fs.promises.readFile(path, "utf-8"); + return { + code: code.replace(/^\/\/.*?\n/, ""), + map: void 0 + }; + } + async writeInfo() { + if (!this.dumpDir) + return; + const info = JSON.stringify({ + time: (/* @__PURE__ */ new Date()).toLocaleString(), + externalize: Object.fromEntries(this.externalizeMap.entries()) + }, null, 2); + return fs.promises.writeFile(pathe.join(this.dumpDir, "info.json"), info, "utf-8"); + } +} + +const debugRequest = createDebug("vite-node:server:request"); +class ViteNodeServer { + constructor(server, options = {}) { + this.server = server; + this.options = options; + var _a, _b, _c; + const ssrOptions = server.config.ssr; + options.deps ?? (options.deps = {}); + options.deps.cacheDir = pathe.relative(server.config.root, options.deps.cacheDir || server.config.cacheDir); + if (ssrOptions) { + if (ssrOptions.noExternal === true) { + (_a = options.deps).inline ?? (_a.inline = true); + } else if (options.deps.inline !== true) { + (_b = options.deps).inline ?? (_b.inline = []); + const inline = options.deps.inline; + options.deps.inline.push(...utils.toArray(ssrOptions.noExternal).filter((dep) => !inline.includes(dep))); + } + } + if (process.env.VITE_NODE_DEBUG_DUMP) { + options.debug = Object.assign({ + dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP, + loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load" + }, options.debug ?? {}); + } + if (options.debug) + this.debugger = new Debugger(server.config.root, options.debug); + (_c = options.deps).moduleDirectories ?? (_c.moduleDirectories = []); + const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES; + const customModuleDirectories = envValue == null ? void 0 : envValue.split(","); + if (customModuleDirectories) + options.deps.moduleDirectories.push(...customModuleDirectories); + options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => { + if (!dir.startsWith("/")) + dir = `/${dir}`; + if (!dir.endsWith("/")) + dir += "/"; + return pathe.normalize(dir); + }); + if (!options.deps.moduleDirectories.includes("/node_modules/")) + options.deps.moduleDirectories.push("/node_modules/"); + } + fetchPromiseMap = { + ssr: /* @__PURE__ */ new Map(), + web: /* @__PURE__ */ new Map() + }; + transformPromiseMap = { + ssr: /* @__PURE__ */ new Map(), + web: /* @__PURE__ */ new Map() + }; + existingOptimizedDeps = /* @__PURE__ */ new Set(); + fetchCaches = { + ssr: /* @__PURE__ */ new Map(), + web: /* @__PURE__ */ new Map() + }; + fetchCache = /* @__PURE__ */ new Map(); + externalizeCache = /* @__PURE__ */ new Map(); + debugger; + shouldExternalize(id) { + return shouldExternalize(id, this.options.deps, this.externalizeCache); + } + async ensureExists(id) { + if (this.existingOptimizedDeps.has(id)) + return true; + if (fs.existsSync(id)) { + this.existingOptimizedDeps.add(id); + return true; + } + return new Promise((resolve2) => { + setTimeout(() => { + this.ensureExists(id).then(() => { + resolve2(true); + }); + }); + }); + } + async resolveId(id, importer, transformMode) { + if (importer && !importer.startsWith(utils.withTrailingSlash(this.server.config.root))) + importer = pathe.resolve(this.server.config.root, importer); + const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr"); + return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" }); + } + getSourceMap(source) { + var _a, _b; + const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result; + if (fetchResult == null ? void 0 : fetchResult.map) + return fetchResult.map; + const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult; + return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null; + } + assertMode(mode) { + assert(mode === "web" || mode === "ssr", `"transformMode" can only be "web" or "ssr", received "${mode}".`); + } + async fetchModule(id, transformMode) { + const moduleId = utils.normalizeModuleId(id); + const mode = transformMode || this.getTransformMode(id); + this.assertMode(mode); + const promiseMap = this.fetchPromiseMap[mode]; + if (!promiseMap.has(moduleId)) { + promiseMap.set(moduleId, this._fetchModule(moduleId, mode).then((r) => { + return this.options.sourcemap !== true ? { ...r, map: void 0 } : r; + }).finally(() => { + promiseMap.delete(moduleId); + })); + } + return promiseMap.get(moduleId); + } + async transformRequest(id, filepath = id, transformMode) { + const mode = transformMode || this.getTransformMode(id); + this.assertMode(mode); + const promiseMap = this.transformPromiseMap[mode]; + if (!promiseMap.has(id)) { + promiseMap.set(id, this._transformRequest(id, filepath, mode).finally(() => { + promiseMap.delete(id); + })); + } + return promiseMap.get(id); + } + async transformModule(id, transformMode) { + if (transformMode !== "web") + throw new Error('`transformModule` only supports `transformMode: "web"`.'); + const normalizedId = utils.normalizeModuleId(id); + const mod = this.server.moduleGraph.getModuleById(normalizedId); + const result = (mod == null ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId); + return { + code: result == null ? void 0 : result.code + }; + } + getTransformMode(id) { + var _a, _b, _c, _d; + const withoutQuery = id.split("?")[0]; + if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r))) + return "web"; + if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r))) + return "ssr"; + if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) + return "ssr"; + return "web"; + } + getChangedModule(id, file) { + const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file); + if (module) + return module; + const _modules = this.server.moduleGraph.getModulesByFile(file); + if (!_modules || !_modules.size) + return null; + const modules = [..._modules]; + let mod = modules[0]; + let latestMax = -1; + for (const m of _modules) { + const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp); + if (timestamp > latestMax) { + latestMax = timestamp; + mod = m; + } + } + return mod; + } + async _fetchModule(id, transformMode) { + var _a, _b; + let result; + const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir; + if (cacheDir && id.includes(cacheDir)) { + if (!id.startsWith(utils.withTrailingSlash(this.server.config.root))) + id = pathe.join(this.server.config.root, id); + const timeout = setTimeout(() => { + throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`); + }, 5e3); + await this.ensureExists(id); + clearTimeout(timeout); + } + const { path: filePath } = utils.toFilePath(id, this.server.config.root); + const moduleNode = this.getChangedModule(id, filePath); + const cache = this.fetchCaches[transformMode].get(filePath); + const timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0; + if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) + return cache.result; + const time = Date.now(); + const externalize = await this.shouldExternalize(filePath); + let duration; + if (externalize) { + result = { externalize }; + (_b = this.debugger) == null ? void 0 : _b.recordExternalize(id, externalize); + } else { + const start = node_perf_hooks.performance.now(); + const r = await this._transformRequest(id, filePath, transformMode); + duration = node_perf_hooks.performance.now() - start; + result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map }; + } + const cacheEntry = { + duration, + timestamp: time, + result + }; + this.fetchCaches[transformMode].set(filePath, cacheEntry); + this.fetchCache.set(filePath, cacheEntry); + return result; + } + async processTransformResult(filepath, result) { + const mod = this.server.moduleGraph.getModuleById(filepath); + return sourceMap.withInlineSourcemap(result, { + filepath: (mod == null ? void 0 : mod.file) || filepath, + root: this.server.config.root + }); + } + async _transformRequest(id, filepath, transformMode) { + var _a, _b, _c, _d; + debugRequest(id); + let result = null; + if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) { + result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null; + if (result) + return result; + } + if (transformMode === "web") { + result = await this.server.transformRequest(id); + if (result) + result = await this.server.ssrTransform(result.code, result.map, id); + } else { + result = await this.server.transformRequest(id, { ssr: true }); + } + const sourcemap = this.options.sourcemap ?? "inline"; + if (sourcemap === "inline" && result && !id.includes("node_modules")) + result = await this.processTransformResult(filepath, result); + if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules) + await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result)); + return result; + } +} + +exports.ViteNodeServer = ViteNodeServer; +exports.guessCJSversion = guessCJSversion; +exports.shouldExternalize = shouldExternalize; diff --git a/web/node_modules/vite-node/dist/server.d.ts b/web/node_modules/vite-node/dist/server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c7d7cc1dc158bbd493db95cd2b5db31bcdedd83 --- /dev/null +++ b/web/node_modules/vite-node/dist/server.d.ts @@ -0,0 +1,58 @@ +import { TransformResult, ViteDevServer } from 'vite'; +import { D as DebuggerOptions, c as DepsHandlingOptions, V as ViteNodeServerOptions, d as ViteNodeResolveId, F as FetchResult } from './index-WT31LSgS.js'; +import { E as EncodedSourceMap } from './trace-mapping.d-xyIfZtPm.js'; + +declare class Debugger { + options: DebuggerOptions; + dumpDir: string | undefined; + initPromise: Promise | undefined; + externalizeMap: Map; + constructor(root: string, options: DebuggerOptions); + clearDump(): Promise; + encodeId(id: string): string; + recordExternalize(id: string, path: string): Promise; + dumpFile(id: string, result: TransformResult | null): Promise; + loadDump(id: string): Promise; + writeInfo(): Promise; +} + +declare function guessCJSversion(id: string): string | undefined; +declare function shouldExternalize(id: string, options?: DepsHandlingOptions, cache?: Map>): Promise; + +interface FetchCache { + duration?: number; + timestamp: number; + result: FetchResult; +} +declare class ViteNodeServer { + server: ViteDevServer; + options: ViteNodeServerOptions; + private fetchPromiseMap; + private transformPromiseMap; + private existingOptimizedDeps; + fetchCaches: { + ssr: Map; + web: Map; + }; + fetchCache: Map; + externalizeCache: Map>; + debugger?: Debugger; + constructor(server: ViteDevServer, options?: ViteNodeServerOptions); + shouldExternalize(id: string): Promise; + private ensureExists; + resolveId(id: string, importer?: string, transformMode?: 'web' | 'ssr'): Promise; + getSourceMap(source: string): EncodedSourceMap | null; + private assertMode; + fetchModule(id: string, transformMode?: 'web' | 'ssr'): Promise; + transformRequest(id: string, filepath?: string, transformMode?: 'web' | 'ssr'): Promise; + transformModule(id: string, transformMode?: 'web' | 'ssr'): Promise<{ + code: string | undefined; + }>; + getTransformMode(id: string): "web" | "ssr"; + private getChangedModule; + private _fetchModule; + protected processTransformResult(filepath: string, result: TransformResult): Promise; + private _transformRequest; +} + +export { ViteNodeServer, guessCJSversion, shouldExternalize }; diff --git a/web/node_modules/vite-node/dist/server.mjs b/web/node_modules/vite-node/dist/server.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cf859a4b0e149cddf55349ecf9575144dcfcb366 --- /dev/null +++ b/web/node_modules/vite-node/dist/server.mjs @@ -0,0 +1,424 @@ +import { performance } from 'node:perf_hooks'; +import { existsSync, promises } from 'node:fs'; +import assert from 'node:assert'; +import { join, extname, dirname, resolve, relative, normalize } from 'pathe'; +import createDebug from 'debug'; +import { isNodeBuiltin, slash, findNearestPackageData, toArray, withTrailingSlash, normalizeModuleId, toFilePath } from './utils.mjs'; +import { KNOWN_ASSET_TYPES } from './constants.mjs'; +import c from 'picocolors'; +import { withInlineSourcemap } from './source-map.mjs'; +import 'node:url'; +import 'node:module'; +import 'node:path'; + +const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]); +const ESM_SYNTAX_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; +const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/; +const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/; +const defaultInline = [ + /virtual:/, + /\.[mc]?ts$/, + // special Vite query strings + /[?&](init|raw|url|inline)\b/, + // Vite returns a string for assets imports, even if it's inside "node_modules" + new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`) +]; +const depsExternal = [ + /\/node_modules\/.*\.cjs\.js$/, + /\/node_modules\/.*\.mjs$/ +]; +function guessCJSversion(id) { + if (id.match(ESM_EXT_RE)) { + for (const i of [ + id.replace(ESM_EXT_RE, ".mjs"), + id.replace(ESM_EXT_RE, ".umd.js"), + id.replace(ESM_EXT_RE, ".cjs.js"), + id.replace(ESM_EXT_RE, ".js") + ]) { + if (existsSync(i)) + return i; + } + } + if (id.match(ESM_FOLDER_RE)) { + for (const i of [ + id.replace(ESM_FOLDER_RE, "/umd/$1"), + id.replace(ESM_FOLDER_RE, "/cjs/$1"), + id.replace(ESM_FOLDER_RE, "/lib/$1"), + id.replace(ESM_FOLDER_RE, "/$1") + ]) { + if (existsSync(i)) + return i; + } + } +} +async function isValidNodeImport(id) { + const extension = extname(id); + if (BUILTIN_EXTENSIONS.has(extension)) + return true; + if (extension !== ".js") + return false; + if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(id)) + return false; + id = id.replace("file:///", ""); + const package_ = await findNearestPackageData(dirname(id)); + if (package_.type === "module") + return true; + const code = await promises.readFile(id, "utf8").catch(() => ""); + return !ESM_SYNTAX_RE.test(code); +} +const _defaultExternalizeCache = /* @__PURE__ */ new Map(); +async function shouldExternalize(id, options, cache = _defaultExternalizeCache) { + if (!cache.has(id)) + cache.set(id, _shouldExternalize(id, options)); + return cache.get(id); +} +async function _shouldExternalize(id, options) { + if (isNodeBuiltin(id)) + return id; + if (id.startsWith("data:") || /^(https?:)?\/\//.test(id)) + return id; + id = patchWindowsImportPath(id); + if ((options == null ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) + return id; + const moduleDirectories = (options == null ? void 0 : options.moduleDirectories) || ["/node_modules/"]; + if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.inline)) + return false; + if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.external)) + return id; + const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir)); + const guessCJS = isLibraryModule && (options == null ? void 0 : options.fallbackCJS); + id = guessCJS ? guessCJSversion(id) || id : id; + if (matchExternalizePattern(id, moduleDirectories, defaultInline)) + return false; + if (matchExternalizePattern(id, moduleDirectories, depsExternal)) + return id; + if (isLibraryModule && await isValidNodeImport(id)) + return id; + return false; +} +function matchExternalizePattern(id, moduleDirectories, patterns) { + if (patterns == null) + return false; + if (patterns === true) + return true; + for (const ex of patterns) { + if (typeof ex === "string") { + if (moduleDirectories.some((dir) => id.includes(join(dir, ex)))) + return true; + } else { + if (ex.test(id)) + return true; + } + } + return false; +} +function patchWindowsImportPath(path) { + if (path.match(/^\w:\\/)) + return `file:///${slash(path)}`; + else if (path.match(/^\w:\//)) + return `file:///${path}`; + else + return path; +} + +function hashCode(s) { + return s.split("").reduce((a, b) => { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0); +} +class Debugger { + constructor(root, options) { + this.options = options; + if (options.dumpModules) + this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules); + if (this.dumpDir) { + if (options.loadDumppedModules) + console.info(c.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`)); + else + console.info(c.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`)); + } + this.initPromise = this.clearDump(); + } + dumpDir; + initPromise; + externalizeMap = /* @__PURE__ */ new Map(); + async clearDump() { + if (!this.dumpDir) + return; + if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) + await promises.rm(this.dumpDir, { recursive: true, force: true }); + await promises.mkdir(this.dumpDir, { recursive: true }); + } + encodeId(id) { + return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`; + } + async recordExternalize(id, path) { + if (!this.dumpDir) + return; + this.externalizeMap.set(id, path); + await this.writeInfo(); + } + async dumpFile(id, result) { + if (!result || !this.dumpDir) + return; + await this.initPromise; + const name = this.encodeId(id); + return await promises.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")} +${result.code}`, "utf-8"); + } + async loadDump(id) { + if (!this.dumpDir) + return null; + await this.initPromise; + const name = this.encodeId(id); + const path = join(this.dumpDir, name); + if (!existsSync(path)) + return null; + const code = await promises.readFile(path, "utf-8"); + return { + code: code.replace(/^\/\/.*?\n/, ""), + map: void 0 + }; + } + async writeInfo() { + if (!this.dumpDir) + return; + const info = JSON.stringify({ + time: (/* @__PURE__ */ new Date()).toLocaleString(), + externalize: Object.fromEntries(this.externalizeMap.entries()) + }, null, 2); + return promises.writeFile(join(this.dumpDir, "info.json"), info, "utf-8"); + } +} + +const debugRequest = createDebug("vite-node:server:request"); +class ViteNodeServer { + constructor(server, options = {}) { + this.server = server; + this.options = options; + var _a, _b, _c; + const ssrOptions = server.config.ssr; + options.deps ?? (options.deps = {}); + options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir); + if (ssrOptions) { + if (ssrOptions.noExternal === true) { + (_a = options.deps).inline ?? (_a.inline = true); + } else if (options.deps.inline !== true) { + (_b = options.deps).inline ?? (_b.inline = []); + const inline = options.deps.inline; + options.deps.inline.push(...toArray(ssrOptions.noExternal).filter((dep) => !inline.includes(dep))); + } + } + if (process.env.VITE_NODE_DEBUG_DUMP) { + options.debug = Object.assign({ + dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP, + loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load" + }, options.debug ?? {}); + } + if (options.debug) + this.debugger = new Debugger(server.config.root, options.debug); + (_c = options.deps).moduleDirectories ?? (_c.moduleDirectories = []); + const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES; + const customModuleDirectories = envValue == null ? void 0 : envValue.split(","); + if (customModuleDirectories) + options.deps.moduleDirectories.push(...customModuleDirectories); + options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => { + if (!dir.startsWith("/")) + dir = `/${dir}`; + if (!dir.endsWith("/")) + dir += "/"; + return normalize(dir); + }); + if (!options.deps.moduleDirectories.includes("/node_modules/")) + options.deps.moduleDirectories.push("/node_modules/"); + } + fetchPromiseMap = { + ssr: /* @__PURE__ */ new Map(), + web: /* @__PURE__ */ new Map() + }; + transformPromiseMap = { + ssr: /* @__PURE__ */ new Map(), + web: /* @__PURE__ */ new Map() + }; + existingOptimizedDeps = /* @__PURE__ */ new Set(); + fetchCaches = { + ssr: /* @__PURE__ */ new Map(), + web: /* @__PURE__ */ new Map() + }; + fetchCache = /* @__PURE__ */ new Map(); + externalizeCache = /* @__PURE__ */ new Map(); + debugger; + shouldExternalize(id) { + return shouldExternalize(id, this.options.deps, this.externalizeCache); + } + async ensureExists(id) { + if (this.existingOptimizedDeps.has(id)) + return true; + if (existsSync(id)) { + this.existingOptimizedDeps.add(id); + return true; + } + return new Promise((resolve2) => { + setTimeout(() => { + this.ensureExists(id).then(() => { + resolve2(true); + }); + }); + }); + } + async resolveId(id, importer, transformMode) { + if (importer && !importer.startsWith(withTrailingSlash(this.server.config.root))) + importer = resolve(this.server.config.root, importer); + const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr"); + return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" }); + } + getSourceMap(source) { + var _a, _b; + const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result; + if (fetchResult == null ? void 0 : fetchResult.map) + return fetchResult.map; + const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult; + return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null; + } + assertMode(mode) { + assert(mode === "web" || mode === "ssr", `"transformMode" can only be "web" or "ssr", received "${mode}".`); + } + async fetchModule(id, transformMode) { + const moduleId = normalizeModuleId(id); + const mode = transformMode || this.getTransformMode(id); + this.assertMode(mode); + const promiseMap = this.fetchPromiseMap[mode]; + if (!promiseMap.has(moduleId)) { + promiseMap.set(moduleId, this._fetchModule(moduleId, mode).then((r) => { + return this.options.sourcemap !== true ? { ...r, map: void 0 } : r; + }).finally(() => { + promiseMap.delete(moduleId); + })); + } + return promiseMap.get(moduleId); + } + async transformRequest(id, filepath = id, transformMode) { + const mode = transformMode || this.getTransformMode(id); + this.assertMode(mode); + const promiseMap = this.transformPromiseMap[mode]; + if (!promiseMap.has(id)) { + promiseMap.set(id, this._transformRequest(id, filepath, mode).finally(() => { + promiseMap.delete(id); + })); + } + return promiseMap.get(id); + } + async transformModule(id, transformMode) { + if (transformMode !== "web") + throw new Error('`transformModule` only supports `transformMode: "web"`.'); + const normalizedId = normalizeModuleId(id); + const mod = this.server.moduleGraph.getModuleById(normalizedId); + const result = (mod == null ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId); + return { + code: result == null ? void 0 : result.code + }; + } + getTransformMode(id) { + var _a, _b, _c, _d; + const withoutQuery = id.split("?")[0]; + if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r))) + return "web"; + if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r))) + return "ssr"; + if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) + return "ssr"; + return "web"; + } + getChangedModule(id, file) { + const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file); + if (module) + return module; + const _modules = this.server.moduleGraph.getModulesByFile(file); + if (!_modules || !_modules.size) + return null; + const modules = [..._modules]; + let mod = modules[0]; + let latestMax = -1; + for (const m of _modules) { + const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp); + if (timestamp > latestMax) { + latestMax = timestamp; + mod = m; + } + } + return mod; + } + async _fetchModule(id, transformMode) { + var _a, _b; + let result; + const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir; + if (cacheDir && id.includes(cacheDir)) { + if (!id.startsWith(withTrailingSlash(this.server.config.root))) + id = join(this.server.config.root, id); + const timeout = setTimeout(() => { + throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`); + }, 5e3); + await this.ensureExists(id); + clearTimeout(timeout); + } + const { path: filePath } = toFilePath(id, this.server.config.root); + const moduleNode = this.getChangedModule(id, filePath); + const cache = this.fetchCaches[transformMode].get(filePath); + const timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0; + if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) + return cache.result; + const time = Date.now(); + const externalize = await this.shouldExternalize(filePath); + let duration; + if (externalize) { + result = { externalize }; + (_b = this.debugger) == null ? void 0 : _b.recordExternalize(id, externalize); + } else { + const start = performance.now(); + const r = await this._transformRequest(id, filePath, transformMode); + duration = performance.now() - start; + result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map }; + } + const cacheEntry = { + duration, + timestamp: time, + result + }; + this.fetchCaches[transformMode].set(filePath, cacheEntry); + this.fetchCache.set(filePath, cacheEntry); + return result; + } + async processTransformResult(filepath, result) { + const mod = this.server.moduleGraph.getModuleById(filepath); + return withInlineSourcemap(result, { + filepath: (mod == null ? void 0 : mod.file) || filepath, + root: this.server.config.root + }); + } + async _transformRequest(id, filepath, transformMode) { + var _a, _b, _c, _d; + debugRequest(id); + let result = null; + if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) { + result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null; + if (result) + return result; + } + if (transformMode === "web") { + result = await this.server.transformRequest(id); + if (result) + result = await this.server.ssrTransform(result.code, result.map, id); + } else { + result = await this.server.transformRequest(id, { ssr: true }); + } + const sourcemap = this.options.sourcemap ?? "inline"; + if (sourcemap === "inline" && result && !id.includes("node_modules")) + result = await this.processTransformResult(filepath, result); + if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules) + await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result)); + return result; + } +} + +export { ViteNodeServer, guessCJSversion, shouldExternalize }; diff --git a/web/node_modules/vite-node/dist/source-map.cjs b/web/node_modules/vite-node/dist/source-map.cjs new file mode 100644 index 0000000000000000000000000000000000000000..476e56d563b749759ae477196a467ad0a74be230 --- /dev/null +++ b/web/node_modules/vite-node/dist/source-map.cjs @@ -0,0 +1,916 @@ +'use strict'; + +var pathe = require('pathe'); +var utils = require('./utils.cjs'); +var path = require('node:path'); +var fs = require('node:fs'); +require('node:url'); +require('node:module'); + +const comma = ','.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; +} +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator$1); +} +function sortComparator$1(a, b) { + return a[0] - b[0]; +} + +// 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; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +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: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.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('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.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 <= UrlType.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$1(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.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 UrlType.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 UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.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 UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +function resolve(input, base) { + // The base 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 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$1(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +function maybeSort(mappings, owned) { + 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, 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]; +} + +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]); + * ``` + */ +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, + }; +} +/** + * 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. + */ +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) { + // 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)); +} + +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)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * 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. + */ +let originalPositionFor; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : 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; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + originalPositionFor = (map, { line, column, bias }) => { + 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, 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 OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} + +let errorFormatterInstalled = false; +const fileContentsCache = {}; +const sourceMapCache = {}; +const reSourceMap = /^data:application\/json[^,]+base64,/; +let retrieveFileHandlers = []; +let retrieveMapHandlers = []; +function globalProcessVersion() { + if (typeof process === "object" && process !== null) + return process.version; + else + return ""; +} +function handlerExec(list) { + return function(arg) { + for (let i = 0; i < list.length; i++) { + const ret = list[i](arg); + if (ret) + return ret; + } + return null; + }; +} +let retrieveFile = handlerExec(retrieveFileHandlers); +retrieveFileHandlers.push((path2) => { + path2 = path2.trim(); + if (path2.startsWith("file:")) { + path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => { + return drive ? "" : "/"; + }); + } + if (path2 in fileContentsCache) + return fileContentsCache[path2]; + let contents = ""; + try { + if (fs.existsSync(path2)) + contents = fs.readFileSync(path2, "utf8"); + } catch (er) { + } + return fileContentsCache[path2] = contents; +}); +function supportRelativeURL(file, url) { + if (!file) + return url; + const dir = path.dirname(file); + const match = /^\w+:\/\/[^\/]*/.exec(dir); + let protocol = match ? match[0] : ""; + const startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + protocol += "/"; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/"); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} +function retrieveSourceMapURL(source) { + const fileData = retrieveFile(source); + if (!fileData) + return null; + const re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + let lastMatch, match; + while (match = re.exec(fileData)) + lastMatch = match; + if (!lastMatch) + return null; + return lastMatch[1]; +} +let retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push((source) => { + let sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) + return null; + let sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1); + sourceMapData = Buffer.from(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + if (!sourceMapData) + return null; + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); +function mapSourcePosition(position) { + var _a; + if (!position.source) + return position; + let sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + const urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap && urlAndMap.map) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new TraceMap(urlAndMap.map) + }; + if ((_a = sourceMap.map) == null ? void 0 : _a.sourcesContent) { + sourceMap.map.sources.forEach((source, i) => { + var _a2, _b; + const contents = (_b = (_a2 = sourceMap.map) == null ? void 0 : _a2.sourcesContent) == null ? void 0 : _b[i]; + if (contents && source && sourceMap.url) { + const url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + if (sourceMap && sourceMap.map && sourceMap.url) { + const originalPosition = originalPositionFor(sourceMap.map, position); + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, + originalPosition.source + ); + return originalPosition; + } + } + return position; +} +function mapEvalOrigin(origin) { + let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + const position = mapSourcePosition({ + name: null, + source: match[2], + line: +match[3], + column: +match[4] - 1 + }); + return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`; + } + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) + return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`; + return origin; +} +function CallSiteToString() { + let fileName; + let fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; + } + if (fileName) { + fileLocation += fileName; + } else { + fileLocation += ""; + } + const lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += `:${lineNumber}`; + const columnNumber = this.getColumnNumber(); + if (columnNumber) + fileLocation += `:${columnNumber}`; + } + } + let line = ""; + const functionName = this.getFunctionName(); + let addSuffix = true; + const isConstructor = this.isConstructor(); + const isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + let typeName = this.getTypeName(); + if (typeName === "[object Object]") + typeName = "null"; + const methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) + line += `${typeName}.`; + line += functionName; + if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) + line += ` [as ${methodName}]`; + } else { + line += `${typeName}.${methodName || ""}`; + } + } else if (isConstructor) { + line += `new ${functionName || ""}`; + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) + line += ` (${fileLocation})`; + return line; +} +function cloneCallSite(frame) { + const object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => { + const key = name; + object[key] = /^(?:is|get)/.test(name) ? function() { + return frame[key].call(frame); + } : frame[key]; + }); + object.toString = CallSiteToString; + return object; +} +function wrapCallSite(frame, state) { + if (state === void 0) + state = { nextPosition: null, curPosition: null }; + if (frame.isNative()) { + state.curPosition = null; + return frame; + } + const source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + const line = frame.getLineNumber(); + let column = frame.getColumnNumber() - 1; + const noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + const headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; + if (line === 1 && column > headerLength && !frame.isEval()) + column -= headerLength; + const position = mapSourcePosition({ + name: null, + source, + line, + column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + const originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) + return originalFunctionName(); + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { + return position.source ?? void 0; + }; + frame.getLineNumber = function() { + return position.line; + }; + frame.getColumnNumber = function() { + return position.column + 1; + }; + frame.getScriptNameOrSourceURL = function() { + return position.source; + }; + return frame; + } + let origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { + return origin || void 0; + }; + return frame; + } + return frame; +} +function prepareStackTrace(error, stack) { + const name = error.name || "Error"; + const message = error.message || ""; + const errorString = `${name}: ${message}`; + const state = { nextPosition: null, curPosition: null }; + const processedStack = []; + for (let i = stack.length - 1; i >= 0; i--) { + processedStack.push(` + at ${wrapCallSite(stack[i], state)}`); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(""); +} +retrieveFileHandlers.slice(0); +retrieveMapHandlers.slice(0); +const install = function(options) { + options = options || {}; + if (options.retrieveFile) { + if (options.overrideRetrieveFile) + retrieveFileHandlers.length = 0; + retrieveFileHandlers.unshift(options.retrieveFile); + } + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) + retrieveMapHandlers.length = 0; + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } +}; + +let SOURCEMAPPING_URL = "sourceMa"; +SOURCEMAPPING_URL += "ppingURL"; +const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node"; +const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`; +const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`); +function withInlineSourcemap(result, options) { + var _a; + const map = result.map; + let code = result.code; + if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE)) + return result; + if ("sources" in map) { + map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => { + if (!source) + return source; + if (pathe.isAbsolute(source)) { + const actualPath = !source.startsWith(utils.withTrailingSlash(options.root)) && source.startsWith("/") ? pathe.resolve(options.root, source.slice(1)) : source; + return pathe.relative(pathe.dirname(options.filepath), actualPath); + } + return source; + }); + } + const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm"); + while (OTHER_SOURCE_MAP_REGEXP.test(code)) + code = code.replace(OTHER_SOURCE_MAP_REGEXP, ""); + const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64"); + result.code = `${code.trimEnd()} + +${VITE_NODE_SOURCEMAPPING_SOURCE} +//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap} +`; + return result; +} +function extractSourceMap(code) { + var _a; + const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1]; + if (mapString) + return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8")); + return null; +} +function installSourcemapsSupport(options) { + install({ + retrieveSourceMap(source) { + const map = options.getSourceMap(source); + if (map) { + return { + url: source, + map + }; + } + return null; + } + }); +} + +exports.extractSourceMap = extractSourceMap; +exports.installSourcemapsSupport = installSourcemapsSupport; +exports.withInlineSourcemap = withInlineSourcemap; diff --git a/web/node_modules/vite-node/dist/source-map.d.ts b/web/node_modules/vite-node/dist/source-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3ab712d902518cc4c5c92953460c81bed9457a2 --- /dev/null +++ b/web/node_modules/vite-node/dist/source-map.d.ts @@ -0,0 +1,14 @@ +import { TransformResult } from 'vite'; +import { E as EncodedSourceMap } from './trace-mapping.d-xyIfZtPm.js'; + +interface InstallSourceMapSupportOptions { + getSourceMap: (source: string) => EncodedSourceMap | null | undefined; +} +declare function withInlineSourcemap(result: TransformResult, options: { + root: string; + filepath: string; +}): TransformResult; +declare function extractSourceMap(code: string): EncodedSourceMap | null; +declare function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void; + +export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap }; diff --git a/web/node_modules/vite-node/dist/source-map.mjs b/web/node_modules/vite-node/dist/source-map.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a9ded6e4e0a57886cbfd1b94b50320222edb1ab6 --- /dev/null +++ b/web/node_modules/vite-node/dist/source-map.mjs @@ -0,0 +1,912 @@ +import { isAbsolute, resolve as resolve$2, relative, dirname } from 'pathe'; +import { withTrailingSlash } from './utils.mjs'; +import path from 'node:path'; +import fs from 'node:fs'; +import 'node:url'; +import 'node:module'; + +const comma = ','.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; +} +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator$1); +} +function sortComparator$1(a, b) { + return a[0] - b[0]; +} + +// 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; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +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: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.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('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.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 <= UrlType.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$1(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.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 UrlType.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 UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.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 UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +function resolve(input, base) { + // The base 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 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$1(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +function maybeSort(mappings, owned) { + 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, 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]; +} + +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]); + * ``` + */ +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, + }; +} +/** + * 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. + */ +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) { + // 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)); +} + +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)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * 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. + */ +let originalPositionFor; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : 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; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + originalPositionFor = (map, { line, column, bias }) => { + 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, 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 OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} + +let errorFormatterInstalled = false; +const fileContentsCache = {}; +const sourceMapCache = {}; +const reSourceMap = /^data:application\/json[^,]+base64,/; +let retrieveFileHandlers = []; +let retrieveMapHandlers = []; +function globalProcessVersion() { + if (typeof process === "object" && process !== null) + return process.version; + else + return ""; +} +function handlerExec(list) { + return function(arg) { + for (let i = 0; i < list.length; i++) { + const ret = list[i](arg); + if (ret) + return ret; + } + return null; + }; +} +let retrieveFile = handlerExec(retrieveFileHandlers); +retrieveFileHandlers.push((path2) => { + path2 = path2.trim(); + if (path2.startsWith("file:")) { + path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => { + return drive ? "" : "/"; + }); + } + if (path2 in fileContentsCache) + return fileContentsCache[path2]; + let contents = ""; + try { + if (fs.existsSync(path2)) + contents = fs.readFileSync(path2, "utf8"); + } catch (er) { + } + return fileContentsCache[path2] = contents; +}); +function supportRelativeURL(file, url) { + if (!file) + return url; + const dir = path.dirname(file); + const match = /^\w+:\/\/[^\/]*/.exec(dir); + let protocol = match ? match[0] : ""; + const startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + protocol += "/"; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/"); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} +function retrieveSourceMapURL(source) { + const fileData = retrieveFile(source); + if (!fileData) + return null; + const re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + let lastMatch, match; + while (match = re.exec(fileData)) + lastMatch = match; + if (!lastMatch) + return null; + return lastMatch[1]; +} +let retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push((source) => { + let sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) + return null; + let sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1); + sourceMapData = Buffer.from(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + if (!sourceMapData) + return null; + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); +function mapSourcePosition(position) { + var _a; + if (!position.source) + return position; + let sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + const urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap && urlAndMap.map) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new TraceMap(urlAndMap.map) + }; + if ((_a = sourceMap.map) == null ? void 0 : _a.sourcesContent) { + sourceMap.map.sources.forEach((source, i) => { + var _a2, _b; + const contents = (_b = (_a2 = sourceMap.map) == null ? void 0 : _a2.sourcesContent) == null ? void 0 : _b[i]; + if (contents && source && sourceMap.url) { + const url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + if (sourceMap && sourceMap.map && sourceMap.url) { + const originalPosition = originalPositionFor(sourceMap.map, position); + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, + originalPosition.source + ); + return originalPosition; + } + } + return position; +} +function mapEvalOrigin(origin) { + let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + const position = mapSourcePosition({ + name: null, + source: match[2], + line: +match[3], + column: +match[4] - 1 + }); + return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`; + } + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) + return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`; + return origin; +} +function CallSiteToString() { + let fileName; + let fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; + } + if (fileName) { + fileLocation += fileName; + } else { + fileLocation += ""; + } + const lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += `:${lineNumber}`; + const columnNumber = this.getColumnNumber(); + if (columnNumber) + fileLocation += `:${columnNumber}`; + } + } + let line = ""; + const functionName = this.getFunctionName(); + let addSuffix = true; + const isConstructor = this.isConstructor(); + const isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + let typeName = this.getTypeName(); + if (typeName === "[object Object]") + typeName = "null"; + const methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) + line += `${typeName}.`; + line += functionName; + if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) + line += ` [as ${methodName}]`; + } else { + line += `${typeName}.${methodName || ""}`; + } + } else if (isConstructor) { + line += `new ${functionName || ""}`; + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) + line += ` (${fileLocation})`; + return line; +} +function cloneCallSite(frame) { + const object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => { + const key = name; + object[key] = /^(?:is|get)/.test(name) ? function() { + return frame[key].call(frame); + } : frame[key]; + }); + object.toString = CallSiteToString; + return object; +} +function wrapCallSite(frame, state) { + if (state === void 0) + state = { nextPosition: null, curPosition: null }; + if (frame.isNative()) { + state.curPosition = null; + return frame; + } + const source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + const line = frame.getLineNumber(); + let column = frame.getColumnNumber() - 1; + const noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + const headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; + if (line === 1 && column > headerLength && !frame.isEval()) + column -= headerLength; + const position = mapSourcePosition({ + name: null, + source, + line, + column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + const originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) + return originalFunctionName(); + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { + return position.source ?? void 0; + }; + frame.getLineNumber = function() { + return position.line; + }; + frame.getColumnNumber = function() { + return position.column + 1; + }; + frame.getScriptNameOrSourceURL = function() { + return position.source; + }; + return frame; + } + let origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { + return origin || void 0; + }; + return frame; + } + return frame; +} +function prepareStackTrace(error, stack) { + const name = error.name || "Error"; + const message = error.message || ""; + const errorString = `${name}: ${message}`; + const state = { nextPosition: null, curPosition: null }; + const processedStack = []; + for (let i = stack.length - 1; i >= 0; i--) { + processedStack.push(` + at ${wrapCallSite(stack[i], state)}`); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(""); +} +retrieveFileHandlers.slice(0); +retrieveMapHandlers.slice(0); +const install = function(options) { + options = options || {}; + if (options.retrieveFile) { + if (options.overrideRetrieveFile) + retrieveFileHandlers.length = 0; + retrieveFileHandlers.unshift(options.retrieveFile); + } + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) + retrieveMapHandlers.length = 0; + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } +}; + +let SOURCEMAPPING_URL = "sourceMa"; +SOURCEMAPPING_URL += "ppingURL"; +const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node"; +const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`; +const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`); +function withInlineSourcemap(result, options) { + var _a; + const map = result.map; + let code = result.code; + if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE)) + return result; + if ("sources" in map) { + map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => { + if (!source) + return source; + if (isAbsolute(source)) { + const actualPath = !source.startsWith(withTrailingSlash(options.root)) && source.startsWith("/") ? resolve$2(options.root, source.slice(1)) : source; + return relative(dirname(options.filepath), actualPath); + } + return source; + }); + } + const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm"); + while (OTHER_SOURCE_MAP_REGEXP.test(code)) + code = code.replace(OTHER_SOURCE_MAP_REGEXP, ""); + const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64"); + result.code = `${code.trimEnd()} + +${VITE_NODE_SOURCEMAPPING_SOURCE} +//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap} +`; + return result; +} +function extractSourceMap(code) { + var _a; + const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1]; + if (mapString) + return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8")); + return null; +} +function installSourcemapsSupport(options) { + install({ + retrieveSourceMap(source) { + const map = options.getSourceMap(source); + if (map) { + return { + url: source, + map + }; + } + return null; + } + }); +} + +export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap }; diff --git a/web/node_modules/vite-node/dist/trace-mapping.d-xyIfZtPm.d.ts b/web/node_modules/vite-node/dist/trace-mapping.d-xyIfZtPm.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab1d16c8bc90435aa7b2239be7792e66e539f5cf --- /dev/null +++ b/web/node_modules/vite-node/dist/trace-mapping.d-xyIfZtPm.d.ts @@ -0,0 +1,54 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +type SourceMapInput = string | Ro | Ro | TraceMap; +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']; +} +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; +}; + +declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} + +export type { DecodedSourceMap as D, EncodedSourceMap as E, SourceMapInput as S }; diff --git a/web/node_modules/vite-node/dist/types.cjs b/web/node_modules/vite-node/dist/types.cjs new file mode 100644 index 0000000000000000000000000000000000000000..eb109abbed09786c904e3c767f123a1a0dae21ec --- /dev/null +++ b/web/node_modules/vite-node/dist/types.cjs @@ -0,0 +1,2 @@ +'use strict'; + diff --git a/web/node_modules/vite-node/dist/types.d.ts b/web/node_modules/vite-node/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c1014e36f5a4ef05dc2793e92630a5a467ec0c2 --- /dev/null +++ b/web/node_modules/vite-node/dist/types.d.ts @@ -0,0 +1,2 @@ +export { A as Arrayable, f as Awaitable, i as CreateHotContextFunction, D as DebuggerOptions, c as DepsHandlingOptions, g as FetchFunction, F as FetchResult, b as HotContext, j as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, h as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, k as ViteNodeRunnerOptions, V as ViteNodeServerOptions } from './index-WT31LSgS.js'; +export { D as DecodedSourceMap, E as EncodedSourceMap, S as SourceMapInput } from './trace-mapping.d-xyIfZtPm.js'; diff --git a/web/node_modules/vite-node/dist/types.mjs b/web/node_modules/vite-node/dist/types.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/web/node_modules/vite-node/dist/types.mjs @@ -0,0 +1 @@ + diff --git a/web/node_modules/vite-node/dist/utils.cjs b/web/node_modules/vite-node/dist/utils.cjs new file mode 100644 index 0000000000000000000000000000000000000000..5a0a231b15f3587045c8a6f132923e927a3df5e0 --- /dev/null +++ b/web/node_modules/vite-node/dist/utils.cjs @@ -0,0 +1,194 @@ +'use strict'; + +var node_url = require('node:url'); +var node_module = require('node:module'); +var fs = require('node:fs'); +var pathe = require('pathe'); + +const isWindows = process.platform === "win32"; +const drive = isWindows ? process.cwd()[0] : null; +const driveOpposite = drive ? drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase() : null; +const driveRegexp = drive ? new RegExp(`(?:^|/@fs/)${drive}(:[\\/])`) : null; +const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(:[\\/])`) : null; +function slash(str) { + return str.replace(/\\/g, "/"); +} +const VALID_ID_PREFIX = "/@id/"; +function normalizeRequestId(id, base) { + if (base && id.startsWith(withTrailingSlash(base))) + id = `/${id.slice(base.length)}`; + if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id))) + id = id.replace(driveOppositeRegext, `${drive}$1`); + return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, ""); +} +const queryRE = /\?.*$/s; +const hashRE = /#.*$/s; +function cleanUrl(url) { + return url.replace(hashRE, "").replace(queryRE, ""); +} +const internalRequests = [ + "@vite/client", + "@vite/env" +]; +const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`); +function isInternalRequest(id) { + return internalRequestRegexp.test(id); +} +const prefixedBuiltins = /* @__PURE__ */ new Set([ + "node:test" +]); +const builtins = /* @__PURE__ */ new Set([ + ...node_module.builtinModules, + "assert/strict", + "diagnostics_channel", + "dns/promises", + "fs/promises", + "path/posix", + "path/win32", + "readline/promises", + "stream/consumers", + "stream/promises", + "stream/web", + "timers/promises", + "util/types", + "wasi" +]); +function normalizeModuleId(id) { + if (prefixedBuiltins.has(id)) + return id; + return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").replace(/^node:/, "").replace(/^\/+/, "/"); +} +function isPrimitive(v) { + return v !== Object(v); +} +function toFilePath(id, root) { + let { absolute, exists } = (() => { + if (id.startsWith("/@fs/")) + return { absolute: id.slice(4), exists: true }; + if (!id.startsWith(withTrailingSlash(root)) && id.startsWith("/")) { + const resolved = pathe.resolve(root, id.slice(1)); + if (fs.existsSync(cleanUrl(resolved))) + return { absolute: resolved, exists: true }; + } else if (id.startsWith(withTrailingSlash(root)) && fs.existsSync(cleanUrl(id))) { + return { absolute: id, exists: true }; + } + return { absolute: id, exists: false }; + })(); + if (absolute.startsWith("//")) + absolute = absolute.slice(1); + return { + path: isWindows && absolute.startsWith("/") ? slash(node_url.fileURLToPath(node_url.pathToFileURL(absolute.slice(1)).href)) : absolute, + exists + }; +} +const NODE_BUILTIN_NAMESPACE = "node:"; +function isNodeBuiltin(id) { + if (prefixedBuiltins.has(id)) + return true; + return builtins.has( + id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id + ); +} +function toArray(array) { + if (array === null || array === void 0) + array = []; + if (Array.isArray(array)) + return array; + return [array]; +} +function getCachedData(cache, basedir, originalBasedir) { + const pkgData = cache.get(getFnpdCacheKey(basedir)); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), pkgData); + }); + return pkgData; + } +} +function setCacheData(cache, data, basedir, originalBasedir) { + cache.set(getFnpdCacheKey(basedir), data); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), data); + }); +} +function getFnpdCacheKey(basedir) { + return `fnpd_${basedir}`; +} +function traverseBetweenDirs(longerDir, shorterDir, cb) { + while (longerDir !== shorterDir) { + cb(longerDir); + longerDir = pathe.dirname(longerDir); + } +} +function withTrailingSlash(path) { + if (path[path.length - 1] !== "/") + return `${path}/`; + return path; +} +function createImportMetaEnvProxy() { + const booleanKeys = [ + "DEV", + "PROD", + "SSR" + ]; + return new Proxy(process.env, { + get(_, key) { + if (typeof key !== "string") + return void 0; + if (booleanKeys.includes(key)) + return !!process.env[key]; + return process.env[key]; + }, + set(_, key, value) { + if (typeof key !== "string") + return true; + if (booleanKeys.includes(key)) + process.env[key] = value ? "1" : ""; + else + process.env[key] = value; + return true; + } + }); +} +const packageCache = /* @__PURE__ */ new Map(); +async function findNearestPackageData(basedir) { + var _a; + const originalBasedir = basedir; + while (basedir) { + const cached = getCachedData(packageCache, basedir, originalBasedir); + if (cached) + return cached; + const pkgPath = pathe.join(basedir, "package.json"); + if ((_a = await fs.promises.stat(pkgPath).catch(() => { + })) == null ? void 0 : _a.isFile()) { + const pkgData = JSON.parse(await fs.promises.readFile(pkgPath, "utf8")); + if (packageCache) + setCacheData(packageCache, pkgData, basedir, originalBasedir); + return pkgData; + } + const nextBasedir = pathe.dirname(basedir); + if (nextBasedir === basedir) + break; + basedir = nextBasedir; + } + return {}; +} + +exports.VALID_ID_PREFIX = VALID_ID_PREFIX; +exports.cleanUrl = cleanUrl; +exports.createImportMetaEnvProxy = createImportMetaEnvProxy; +exports.findNearestPackageData = findNearestPackageData; +exports.getCachedData = getCachedData; +exports.hashRE = hashRE; +exports.isInternalRequest = isInternalRequest; +exports.isNodeBuiltin = isNodeBuiltin; +exports.isPrimitive = isPrimitive; +exports.isWindows = isWindows; +exports.normalizeModuleId = normalizeModuleId; +exports.normalizeRequestId = normalizeRequestId; +exports.queryRE = queryRE; +exports.setCacheData = setCacheData; +exports.slash = slash; +exports.toArray = toArray; +exports.toFilePath = toFilePath; +exports.withTrailingSlash = withTrailingSlash; diff --git a/web/node_modules/vite-node/dist/utils.d.ts b/web/node_modules/vite-node/dist/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3b08cd05c45dd37e1dd44f9a573bab70e6c0531 --- /dev/null +++ b/web/node_modules/vite-node/dist/utils.d.ts @@ -0,0 +1,33 @@ +import { N as Nullable, A as Arrayable } from './index-WT31LSgS.js'; +import './trace-mapping.d-xyIfZtPm.js'; + +declare const isWindows: boolean; +declare function slash(str: string): string; +declare const VALID_ID_PREFIX = "/@id/"; +declare function normalizeRequestId(id: string, base?: string): string; +declare const queryRE: RegExp; +declare const hashRE: RegExp; +declare function cleanUrl(url: string): string; +declare function isInternalRequest(id: string): boolean; +declare function normalizeModuleId(id: string): string; +declare function isPrimitive(v: any): boolean; +declare function toFilePath(id: string, root: string): { + path: string; + exists: boolean; +}; +declare function isNodeBuiltin(id: string): boolean; +/** + * Convert `Arrayable` to `Array` + * + * @category Array + */ +declare function toArray(array?: Nullable>): Array; +declare function getCachedData(cache: Map, basedir: string, originalBasedir: string): NonNullable | undefined; +declare function setCacheData(cache: Map, data: T, basedir: string, originalBasedir: string): void; +declare function withTrailingSlash(path: string): string; +declare function createImportMetaEnvProxy(): NodeJS.ProcessEnv; +declare function findNearestPackageData(basedir: string): Promise<{ + type?: 'module' | 'commonjs'; +}>; + +export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, findNearestPackageData, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath, withTrailingSlash }; diff --git a/web/node_modules/vite-node/dist/utils.mjs b/web/node_modules/vite-node/dist/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ca7cb59714fe6d39d15d67e645e15a5450550dc1 --- /dev/null +++ b/web/node_modules/vite-node/dist/utils.mjs @@ -0,0 +1,175 @@ +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { builtinModules } from 'node:module'; +import { existsSync, promises } from 'node:fs'; +import { resolve, dirname, join } from 'pathe'; + +const isWindows = process.platform === "win32"; +const drive = isWindows ? process.cwd()[0] : null; +const driveOpposite = drive ? drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase() : null; +const driveRegexp = drive ? new RegExp(`(?:^|/@fs/)${drive}(:[\\/])`) : null; +const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(:[\\/])`) : null; +function slash(str) { + return str.replace(/\\/g, "/"); +} +const VALID_ID_PREFIX = "/@id/"; +function normalizeRequestId(id, base) { + if (base && id.startsWith(withTrailingSlash(base))) + id = `/${id.slice(base.length)}`; + if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id))) + id = id.replace(driveOppositeRegext, `${drive}$1`); + return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, ""); +} +const queryRE = /\?.*$/s; +const hashRE = /#.*$/s; +function cleanUrl(url) { + return url.replace(hashRE, "").replace(queryRE, ""); +} +const internalRequests = [ + "@vite/client", + "@vite/env" +]; +const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`); +function isInternalRequest(id) { + return internalRequestRegexp.test(id); +} +const prefixedBuiltins = /* @__PURE__ */ new Set([ + "node:test" +]); +const builtins = /* @__PURE__ */ new Set([ + ...builtinModules, + "assert/strict", + "diagnostics_channel", + "dns/promises", + "fs/promises", + "path/posix", + "path/win32", + "readline/promises", + "stream/consumers", + "stream/promises", + "stream/web", + "timers/promises", + "util/types", + "wasi" +]); +function normalizeModuleId(id) { + if (prefixedBuiltins.has(id)) + return id; + return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").replace(/^node:/, "").replace(/^\/+/, "/"); +} +function isPrimitive(v) { + return v !== Object(v); +} +function toFilePath(id, root) { + let { absolute, exists } = (() => { + if (id.startsWith("/@fs/")) + return { absolute: id.slice(4), exists: true }; + if (!id.startsWith(withTrailingSlash(root)) && id.startsWith("/")) { + const resolved = resolve(root, id.slice(1)); + if (existsSync(cleanUrl(resolved))) + return { absolute: resolved, exists: true }; + } else if (id.startsWith(withTrailingSlash(root)) && existsSync(cleanUrl(id))) { + return { absolute: id, exists: true }; + } + return { absolute: id, exists: false }; + })(); + if (absolute.startsWith("//")) + absolute = absolute.slice(1); + return { + path: isWindows && absolute.startsWith("/") ? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href)) : absolute, + exists + }; +} +const NODE_BUILTIN_NAMESPACE = "node:"; +function isNodeBuiltin(id) { + if (prefixedBuiltins.has(id)) + return true; + return builtins.has( + id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id + ); +} +function toArray(array) { + if (array === null || array === void 0) + array = []; + if (Array.isArray(array)) + return array; + return [array]; +} +function getCachedData(cache, basedir, originalBasedir) { + const pkgData = cache.get(getFnpdCacheKey(basedir)); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), pkgData); + }); + return pkgData; + } +} +function setCacheData(cache, data, basedir, originalBasedir) { + cache.set(getFnpdCacheKey(basedir), data); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), data); + }); +} +function getFnpdCacheKey(basedir) { + return `fnpd_${basedir}`; +} +function traverseBetweenDirs(longerDir, shorterDir, cb) { + while (longerDir !== shorterDir) { + cb(longerDir); + longerDir = dirname(longerDir); + } +} +function withTrailingSlash(path) { + if (path[path.length - 1] !== "/") + return `${path}/`; + return path; +} +function createImportMetaEnvProxy() { + const booleanKeys = [ + "DEV", + "PROD", + "SSR" + ]; + return new Proxy(process.env, { + get(_, key) { + if (typeof key !== "string") + return void 0; + if (booleanKeys.includes(key)) + return !!process.env[key]; + return process.env[key]; + }, + set(_, key, value) { + if (typeof key !== "string") + return true; + if (booleanKeys.includes(key)) + process.env[key] = value ? "1" : ""; + else + process.env[key] = value; + return true; + } + }); +} +const packageCache = /* @__PURE__ */ new Map(); +async function findNearestPackageData(basedir) { + var _a; + const originalBasedir = basedir; + while (basedir) { + const cached = getCachedData(packageCache, basedir, originalBasedir); + if (cached) + return cached; + const pkgPath = join(basedir, "package.json"); + if ((_a = await promises.stat(pkgPath).catch(() => { + })) == null ? void 0 : _a.isFile()) { + const pkgData = JSON.parse(await promises.readFile(pkgPath, "utf8")); + if (packageCache) + setCacheData(packageCache, pkgData, basedir, originalBasedir); + return pkgData; + } + const nextBasedir = dirname(basedir); + if (nextBasedir === basedir) + break; + basedir = nextBasedir; + } + return {}; +} + +export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, findNearestPackageData, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath, withTrailingSlash }; diff --git a/web/node_modules/vite-node/package.json b/web/node_modules/vite-node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..503becbdd5d5225b7577fe568acbc18e61002426 --- /dev/null +++ b/web/node_modules/vite-node/package.json @@ -0,0 +1,95 @@ +{ + "name": "vite-node", + "type": "module", + "version": "1.3.1", + "description": "Vite as Node.js runtime", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/blob/main/packages/vite-node#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/vite-node" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./client": { + "types": "./dist/client.d.ts", + "import": "./dist/client.mjs", + "require": "./dist/client.cjs" + }, + "./server": { + "types": "./dist/server.d.ts", + "import": "./dist/server.mjs", + "require": "./dist/server.cjs" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "import": "./dist/utils.mjs", + "require": "./dist/utils.cjs" + }, + "./hmr": { + "types": "./dist/hmr.d.ts", + "import": "./dist/hmr.mjs", + "require": "./dist/hmr.cjs" + }, + "./source-map": { + "types": "./dist/source-map.d.ts", + "import": "./dist/source-map.mjs", + "require": "./dist/source-map.cjs" + }, + "./constants": { + "types": "./dist/constants.d.ts", + "import": "./dist/constants.mjs", + "require": "./dist/constants.cjs" + }, + "./*": "./*" + }, + "main": "./dist/index.mjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "./dist/*", + "./dist/index.d.ts" + ] + } + }, + "bin": { + "vite-node": "./vite-node.mjs" + }, + "files": [ + "*.d.ts", + "*.mjs", + "dist" + ], + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "pathe": "^1.1.1", + "picocolors": "^1.0.0", + "vite": "^5.0.0" + }, + "devDependencies": { + "@jridgewell/trace-mapping": "^0.3.22", + "@types/debug": "^4.1.12" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch --watch.include 'src/**' -m inline", + "typecheck": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/web/node_modules/vite-node/vite-node.mjs b/web/node_modules/vite-node/vite-node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..38bbdf5da787620a0a398ddd12cbee0aac0da9d8 --- /dev/null +++ b/web/node_modules/vite-node/vite-node.mjs @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import('./dist/cli.mjs') diff --git a/web/node_modules/vite/LICENSE.md b/web/node_modules/vite/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..3518027754ee7b98c508fb3d4e5b895e53c5e45e --- /dev/null +++ b/web/node_modules/vite/LICENSE.md @@ -0,0 +1,3508 @@ +# Vite core license +Vite is released under the MIT license: + +MIT License + +Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +# Licenses of bundled dependencies +The published Vite artifact additionally contains code with the following licenses: +Apache-2.0, BSD-2-Clause, CC0-1.0, ISC, MIT + +# Bundled dependencies: +## @ampproject/remapping +License: Apache-2.0 +By: Justin Ridgewell +Repository: git+https://github.com/ampproject/remapping.git + +> 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. + +--------------------------------------- + +## @jridgewell/gen-mapping +License: MIT +By: Justin Ridgewell +Repository: https://github.com/jridgewell/gen-mapping + +> Copyright 2022 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. + +--------------------------------------- + +## @jridgewell/resolve-uri +License: MIT +By: Justin Ridgewell +Repository: https://github.com/jridgewell/resolve-uri + +> 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. + +--------------------------------------- + +## @jridgewell/set-array +License: MIT +By: Justin Ridgewell +Repository: https://github.com/jridgewell/set-array + +> Copyright 2022 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. + +--------------------------------------- + +## @jridgewell/sourcemap-codec +License: MIT +By: Rich Harris +Repository: git+https://github.com/jridgewell/sourcemap-codec.git + +> The MIT License +> +> Copyright (c) 2015 Rich Harris +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## @jridgewell/trace-mapping +License: MIT +By: Justin Ridgewell +Repository: git+https://github.com/jridgewell/trace-mapping.git + +> Copyright 2022 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. + +--------------------------------------- + +## @nodelib/fs.scandir +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir + +> 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. + +--------------------------------------- + +## @nodelib/fs.stat +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat + +> 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. + +--------------------------------------- + +## @nodelib/fs.walk +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk + +> 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. + +--------------------------------------- + +## @polka/url +License: MIT +By: Luke Edwards +Repository: lukeed/polka + +--------------------------------------- + +## @rollup/plugin-alias +License: MIT +By: Johannes Stein +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## @rollup/plugin-commonjs +License: MIT +By: Rich Harris +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## @rollup/plugin-dynamic-import-vars +License: MIT +By: LarsDenBakker +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## @rollup/pluginutils +License: MIT +By: Rich Harris +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## acorn +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2022 by various contributors (see AUTHORS) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## acorn-walk +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2020 by various contributors (see AUTHORS) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## ansi-regex +License: MIT +By: Sindre Sorhus +Repository: chalk/ansi-regex + +> 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. + +--------------------------------------- + +## anymatch +License: ISC +By: Elan Shanker +Repository: https://github.com/micromatch/anymatch + +> The ISC License +> +> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## artichokie +License: MIT +By: sapphi-red, Evan You +Repository: git+https://github.com/sapphi-red/artichokie.git + +> MIT License +> +> Copyright (c) 2020-present, Yuxi (Evan) You +> Copyright (c) 2023-present, sapphi-red +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## astring +License: MIT +By: David Bonnet +Repository: https://github.com/davidbonnet/astring.git + +> Copyright (c) 2015, David Bonnet +> +> 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. + +--------------------------------------- + +## balanced-match +License: MIT +By: Julian Gruber +Repository: git://github.com/juliangruber/balanced-match.git + +> (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. + +--------------------------------------- + +## binary-extensions +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/binary-extensions + +> 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. + +--------------------------------------- + +## brace-expansion +License: MIT +By: Julian Gruber +Repository: git://github.com/juliangruber/brace-expansion.git + +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> 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. + +--------------------------------------- + +## cac +License: MIT +By: egoist +Repository: egoist/cac + +> The MIT License (MIT) +> +> Copyright (c) EGOIST <0x142857@gmail.com> (https://github.com/egoist) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## chokidar +License: MIT +By: Paul Miller, Elan Shanker +Repository: git+https://github.com/paulmillr/chokidar.git + +> The MIT License (MIT) +> +> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the “Software”), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## commondir +License: MIT +By: James Halliday +Repository: http://github.com/substack/node-commondir.git + +> The MIT License +> +> Copyright (c) 2013 James Halliday (mail@substack.net) +> +> Permission is hereby granted, free of charge, +> to any person obtaining a copy of this software and +> associated documentation files (the "Software"), to +> deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, +> merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom +> the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice +> shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +> ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## connect +License: MIT +By: TJ Holowaychuk, Douglas Christopher Wilson, Jonathan Ong, Tim Caswell +Repository: senchalabs/connect + +> (The MIT License) +> +> Copyright (c) 2010 Sencha Inc. +> Copyright (c) 2011 LearnBoost +> Copyright (c) 2011-2014 TJ Holowaychuk +> Copyright (c) 2015 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## convert-source-map +License: MIT +By: Thorsten Lorenz +Repository: git://github.com/thlorenz/convert-source-map.git + +> Copyright 2013 Thorsten Lorenz. +> All rights reserved. +> +> Permission is hereby granted, free of charge, to any person +> obtaining a copy of this software and associated documentation +> files (the "Software"), to deal in the Software without +> restriction, including without limitation the rights to use, +> copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the +> Software is furnished to do so, subject to the following +> conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +> OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## cors +License: MIT +By: Troy Goode +Repository: expressjs/cors + +> (The MIT License) +> +> Copyright (c) 2013 Troy Goode +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## cross-spawn +License: MIT +By: André Cruz +Repository: git@github.com:moxystudio/node-cross-spawn.git + +> 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. + +--------------------------------------- + +## cssesc +License: MIT +By: Mathias Bynens +Repository: https://github.com/mathiasbynens/cssesc.git + +> 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. + +--------------------------------------- + +## debug +License: MIT +By: Josh Junon, TJ Holowaychuk, Nathan Rajlich, Andrew Rhyne +Repository: git://github.com/debug-js/debug.git + +> (The MIT License) +> +> Copyright (c) 2014-2017 TJ Holowaychuk +> Copyright (c) 2018-2021 Josh Junon +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software +> and associated documentation files (the 'Software'), to deal in the Software without restriction, +> including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +> and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial +> portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +> LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## define-lazy-prop +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/define-lazy-prop + +> 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. + +--------------------------------------- + +## dotenv +License: BSD-2-Clause +Repository: git://github.com/motdotla/dotenv.git + +> Copyright (c) 2015, Scott Motte +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## dotenv-expand +License: BSD-2-Clause +By: motdotla +Repository: https://github.com/motdotla/dotenv-expand + +> Copyright (c) 2016, Scott Motte +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## ee-first +License: MIT +By: Jonathan Ong, Douglas Christopher Wilson +Repository: jonathanong/ee-first + +> The MIT License (MIT) +> +> Copyright (c) 2014 Jonathan Ong me@jongleberry.com +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## encodeurl +License: MIT +By: Douglas Christopher Wilson +Repository: pillarjs/encodeurl + +> (The MIT License) +> +> Copyright (c) 2016 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## entities +License: BSD-2-Clause +By: Felix Boehm +Repository: git://github.com/fb55/entities.git + +> Copyright (c) Felix Böhm +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +> +> Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +> +> Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +> +> THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS, +> EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## es-module-lexer +License: MIT +By: Guy Bedford +Repository: git+https://github.com/guybedford/es-module-lexer.git + +> MIT License +> ----------- +> +> Copyright (C) 2018-2022 Guy Bedford +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## escape-html +License: MIT +Repository: component/escape-html + +> (The MIT License) +> +> Copyright (c) 2012-2013 TJ Holowaychuk +> Copyright (c) 2015 Andreas Lubbe +> Copyright (c) 2015 Tiancheng "Timothy" Gu +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## estree-walker +License: MIT +By: Rich Harris +Repository: https://github.com/Rich-Harris/estree-walker + +> Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## etag +License: MIT +By: Douglas Christopher Wilson, David Björklund +Repository: jshttp/etag + +> (The MIT License) +> +> Copyright (c) 2014-2016 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## eventemitter3 +License: MIT +By: Arnout Kazemier +Repository: git://github.com/primus/eventemitter3.git + +> The MIT License (MIT) +> +> Copyright (c) 2014 Arnout Kazemier +> +> 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. + +--------------------------------------- + +## fast-glob +License: MIT +By: Denis Malinochkin +Repository: mrmlnc/fast-glob + +> 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. + +--------------------------------------- + +## fastq +License: ISC +By: Matteo Collina +Repository: git+https://github.com/mcollina/fastq.git + +> 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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> 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. + +--------------------------------------- + +## finalhandler +License: MIT +By: Douglas Christopher Wilson +Repository: pillarjs/finalhandler + +> (The MIT License) +> +> Copyright (c) 2014-2017 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## follow-redirects +License: MIT +By: Ruben Verborgh, Olivier Lalonde, James Talmage +Repository: git@github.com:follow-redirects/follow-redirects.git + +> Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +> of the Software, and to permit persons to whom the Software is furnished to do +> so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +> IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## fs.realpath +License: ISC +By: Isaac Z. Schlueter +Repository: git+https://github.com/isaacs/fs.realpath.git + +> 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. +> +> ---- +> +> This library bundles a version of the `fs.realpath` and `fs.realpathSync` +> methods from Node.js v0.10 under the terms of the Node.js MIT license. +> +> Node's license follows, also included at the header of `old.js` which contains +> the licensed code: +> +> Copyright Joyent, Inc. and other Node contributors. +> +> Permission is hereby granted, free of charge, to any person obtaining a +> copy of this software and associated documentation files (the "Software"), +> to deal in the Software without restriction, including without limitation +> the rights to use, copy, modify, merge, publish, distribute, sublicense, +> and/or sell copies of the Software, and to permit persons to whom the +> Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +> DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## generic-names +License: MIT +By: Alexey Litvinov +Repository: git+https://github.com/css-modules/generic-names.git + +> The MIT License (MIT) +> +> Copyright (c) 2015 Alexey Litvinov +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## glob +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/node-glob.git + +> The ISC License +> +> Copyright (c) 2009-2022 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. + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## http-proxy +License: MIT +By: Charlie Robbins, jcrugzz +Repository: https://github.com/http-party/node-http-proxy.git + +> node-http-proxy +> +> Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the Contributors. +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> "Software"), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## icss-utils +License: ISC +By: Glen Maddern +Repository: git+https://github.com/css-modules/icss-utils.git + +> ISC License (ISC) +> Copyright 2018 Glen Maddern +> +> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## inflight +License: ISC +By: Isaac Z. Schlueter +Repository: https://github.com/npm/inflight.git + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter +> +> 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. + +--------------------------------------- + +## inherits +License: ISC +Repository: git://github.com/isaacs/inherits + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +> REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +> FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +> INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +> LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +> OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +> PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## is-binary-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-binary-path + +> 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. + +--------------------------------------- + +## is-docker +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-docker + +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## is-reference +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/is-reference.git + +--------------------------------------- + +## is-wsl +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-wsl + +> 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. + +--------------------------------------- + +## isexe +License: ISC +By: Isaac Z. Schlueter +Repository: git+https://github.com/isaacs/isexe.git + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter and Contributors +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## js-tokens +License: MIT +By: Simon Lydell +Repository: lydell/js-tokens + +> The MIT License (MIT) +> +> Copyright (c) 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024 Simon Lydell +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## launch-editor +License: MIT +By: Evan You +Repository: git+https://github.com/yyx990803/launch-editor.git + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Yuxi (Evan) You +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## launch-editor-middleware +License: MIT +By: Evan You +Repository: git+https://github.com/yyx990803/launch-editor.git + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Yuxi (Evan) You +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## lilconfig +License: MIT +By: antonk52 +Repository: https://github.com/antonk52/lilconfig + +> MIT License +> +> Copyright (c) 2022 Anton Kastritskiy +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## loader-utils +License: MIT +By: Tobias Koppers @sokra +Repository: https://github.com/webpack/loader-utils.git + +> Copyright JS Foundation and other contributors +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## lodash.camelcase +License: MIT +By: John-David Dalton, Blaine Bublitz, Mathias Bynens +Repository: lodash/lodash + +> Copyright jQuery Foundation and other contributors +> +> Based on Underscore.js, copyright Jeremy Ashkenas, +> DocumentCloud and Investigative Reporters & Editors +> +> This software consists of voluntary contributions made by many +> individuals. For exact contribution history, see the revision history +> available at https://github.com/lodash/lodash +> +> The following license applies to all parts of this software except as +> documented below: +> +> ==== +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> "Software"), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +> +> ==== +> +> Copyright and related rights for sample code are waived via CC0. Sample +> code is defined as all source code displayed within the prose of the +> documentation. +> +> CC0: http://creativecommons.org/publicdomain/zero/1.0/ +> +> ==== +> +> Files located in the node_modules and vendor directories are externally +> maintained libraries used by this software which have their own +> licenses; we recommend you read them, as their terms may differ from the +> terms above. + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: https://github.com/rich-harris/magic-string + +> Copyright 2018 Rich Harris +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## merge2 +License: MIT +Repository: git@github.com:teambition/merge2.git + +> 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. + +--------------------------------------- + +## micromatch +License: MIT +By: Jon Schlinkert, Amila Welihinda, Bogdan Chadkin, Brian Woodward, Devon Govett, Elan Shanker, Fabrício Matté, Martin Kolárik, Olsten Larck, Paul Miller, Tom Byrer, Tyler Akins, Peter Bright, Kuba Juszczyk +Repository: micromatch/micromatch + +> 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. + +--------------------------------------- + +## minimatch +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/minimatch.git + +> 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. + +--------------------------------------- + +## mlly +License: MIT +Repository: unjs/mlly + +> MIT License +> +> Copyright (c) Pooya Parsa +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## mrmime +License: MIT +By: Luke Edwards +Repository: lukeed/mrmime + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (https://lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## ms +License: MIT +Repository: zeit/ms + +> The MIT License (MIT) +> +> Copyright (c) 2016 Zeit, 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. + +--------------------------------------- + +## normalize-path +License: MIT +By: Jon Schlinkert, Blaine Bublitz +Repository: jonschlinkert/normalize-path + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## object-assign +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/object-assign + +> 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. + +--------------------------------------- + +## on-finished +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: jshttp/on-finished + +> (The MIT License) +> +> Copyright (c) 2013 Jonathan Ong +> Copyright (c) 2014 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## once +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/once + +> 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. + +--------------------------------------- + +## open +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/open + +> 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. + +--------------------------------------- + +## parse5 +License: MIT +By: Ivan Nikulin, https://github.com/inikulin/parse5/graphs/contributors +Repository: git://github.com/inikulin/parse5.git + +> Copyright (c) 2013-2019 Ivan Nikulin (ifaaan@gmail.com, https://github.com/inikulin) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## parseurl +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: pillarjs/parseurl + +> (The MIT License) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2014-2017 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## path-key +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-key + +> 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. + +--------------------------------------- + +## periscopic +License: MIT +Repository: Rich-Harris/periscopic + +> Copyright (c) 2019 Rich Harris +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## picocolors +License: ISC +By: Alexey Raspopov +Repository: alexeyraspopov/picocolors + +> ISC License +> +> Copyright (c) 2021 Alexey 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. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> 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. + +--------------------------------------- + +## pify +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pify + +> 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. + +--------------------------------------- + +## postcss-import +License: MIT +By: Maxime Thirouin +Repository: https://github.com/postcss/postcss-import.git + +> The MIT License (MIT) +> +> Copyright (c) 2014 Maxime Thirouin, Jason Campbell & Kevin Mårtensson +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## postcss-load-config +License: MIT +By: Michael Ciniawky, Ryan Dunckel, Mateusz Derks, Dalton Santos, Patrick Gilday, François Wouts +Repository: postcss/postcss-load-config + +> 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. + +--------------------------------------- + +## postcss-modules +License: MIT +By: Alexander Madyankin +Repository: https://github.com/css-modules/postcss-modules.git + +> The MIT License (MIT) +> +> Copyright 2015-present Alexander Madyankin +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## postcss-modules-extract-imports +License: ISC +By: Glen Maddern +Repository: https://github.com/css-modules/postcss-modules-extract-imports.git + +> Copyright 2015 Glen Maddern +> +> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## postcss-modules-local-by-default +License: MIT +By: Mark Dalgleish +Repository: https://github.com/css-modules/postcss-modules-local-by-default.git + +> The MIT License (MIT) +> +> Copyright 2015 Mark Dalgleish +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## postcss-modules-scope +License: ISC +By: Glen Maddern +Repository: https://github.com/css-modules/postcss-modules-scope.git + +> ISC License (ISC) +> +> Copyright (c) 2015, Glen Maddern +> +> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## postcss-modules-values +License: ISC +By: Glen Maddern +Repository: git+https://github.com/css-modules/postcss-modules-values.git + +> ISC License (ISC) +> +> Copyright (c) 2015, Glen Maddern +> +> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## postcss-selector-parser +License: MIT +By: Ben Briggs, Chris Eppstein +Repository: postcss/postcss-selector-parser + +> 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. + +--------------------------------------- + +## postcss-value-parser +License: MIT +By: Bogdan Chadkin +Repository: https://github.com/TrySound/postcss-value-parser.git + +> 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. + +--------------------------------------- + +## queue-microtask +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/queue-microtask.git + +> The MIT License (MIT) +> +> Copyright (c) Feross Aboukhadijeh +> +> 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. + +--------------------------------------- + +## read-cache +License: MIT +By: Bogdan Chadkin +Repository: git+https://github.com/TrySound/read-cache.git + +> The MIT License (MIT) +> +> Copyright 2016 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. + +--------------------------------------- + +## readdirp +License: MIT +By: Thorsten Lorenz, Paul Miller +Repository: git://github.com/paulmillr/readdirp.git + +> MIT License +> +> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## requires-port +License: MIT +By: Arnout Kazemier +Repository: https://github.com/unshiftio/requires-port + +> The MIT License (MIT) +> +> Copyright (c) 2015 Unshift.io, Arnout Kazemier, the Contributors. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## resolve.exports +License: MIT +By: Luke Edwards +Repository: lukeed/resolve.exports + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## reusify +License: MIT +By: Matteo Collina +Repository: git+https://github.com/mcollina/reusify.git + +> The MIT License (MIT) +> +> Copyright (c) 2015 Matteo Collina +> +> 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. + +--------------------------------------- + +## run-parallel +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/run-parallel.git + +> The MIT License (MIT) +> +> Copyright (c) Feross Aboukhadijeh +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## shebang-command +License: MIT +By: Kevin Mårtensson +Repository: kevva/shebang-command + +> MIT License +> +> Copyright (c) Kevin Mårtensson (github.com/kevva) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## shebang-regex +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/shebang-regex + +> 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. + +--------------------------------------- + +## shell-quote +License: MIT +By: James Halliday +Repository: http://github.com/ljharb/shell-quote.git + +> The MIT License +> +> Copyright (c) 2013 James Halliday (mail@substack.net) +> +> Permission is hereby granted, free of charge, +> to any person obtaining a copy of this software and +> associated documentation files (the "Software"), to +> deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, +> merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom +> the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice +> shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +> ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## sirv +License: MIT +By: Luke Edwards +Repository: lukeed/sirv + +--------------------------------------- + +## statuses +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: jshttp/statuses + +> The MIT License (MIT) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2016 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## string-hash +License: CC0-1.0 +By: The Dark Sky Company +Repository: git://github.com/darkskyapp/string-hash.git + +--------------------------------------- + +## strip-ansi +License: MIT +By: Sindre Sorhus +Repository: chalk/strip-ansi + +> 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. + +--------------------------------------- + +## strip-literal +License: MIT +By: Anthony Fu +Repository: git+https://github.com/antfu/strip-literal.git + +> MIT License +> +> Copyright (c) 2022 Anthony Fu +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## totalist +License: MIT +By: Luke Edwards +Repository: lukeed/totalist + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## tsconfck +License: MIT +By: dominikg +Repository: git+https://github.com/dominikg/tsconfck.git + +> MIT License +> +> Copyright (c) 2021-present dominikg and [contributors](https://github.com/dominikg/tsconfck/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. +> +> -- Licenses for 3rd-party code included in tsconfck -- +> +> # strip-bom and strip-json-comments +> MIT License +> +> Copyright (c) Sindre Sorhus (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. + +--------------------------------------- + +## ufo +License: MIT +Repository: unjs/ufo + +> MIT License +> +> Copyright (c) Pooya Parsa +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## unpipe +License: MIT +By: Douglas Christopher Wilson +Repository: stream-utils/unpipe + +> (The MIT License) +> +> Copyright (c) 2015 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## util-deprecate +License: MIT +By: Nathan Rajlich +Repository: git://github.com/TooTallNate/util-deprecate.git + +> (The MIT License) +> +> Copyright (c) 2014 Nathan Rajlich +> +> Permission is hereby granted, free of charge, to any person +> obtaining a copy of this software and associated documentation +> files (the "Software"), to deal in the Software without +> restriction, including without limitation the rights to use, +> copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the +> Software is furnished to do so, subject to the following +> conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +> OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## utils-merge +License: MIT +By: Jared Hanson +Repository: git://github.com/jaredhanson/utils-merge.git + +> The MIT License (MIT) +> +> Copyright (c) 2013-2017 Jared Hanson +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## vary +License: MIT +By: Douglas Christopher Wilson +Repository: jshttp/vary + +> (The MIT License) +> +> Copyright (c) 2014-2017 Douglas Christopher Wilson +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## which +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/node-which.git + +> 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. + +--------------------------------------- + +## wrappy +License: ISC +By: Isaac Z. Schlueter +Repository: https://github.com/npm/wrappy + +> 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. + +--------------------------------------- + +## ws +License: MIT +By: Einar Otto Stangvik +Repository: git+https://github.com/websockets/ws.git + +> Copyright (c) 2011 Einar Otto Stangvik +> Copyright (c) 2013 Arnout Kazemier and contributors +> Copyright (c) 2016 Luigi Pinca and contributors +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## yaml +License: ISC +By: Eemeli Aro +Repository: github:eemeli/yaml + +> Copyright Eemeli Aro +> +> 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/web/node_modules/vite/README.md b/web/node_modules/vite/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89490d7b480a8e9e72864b6dd16034756b1082a5 --- /dev/null +++ b/web/node_modules/vite/README.md @@ -0,0 +1,20 @@ +# vite ⚡ + +> Next Generation Frontend Tooling + +- 💡 Instant Server Start +- ⚡️ Lightning Fast HMR +- 🛠️ Rich Features +- 📦 Optimized Build +- 🔩 Universal Plugin Interface +- 🔑 Fully Typed APIs + +Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts: + +- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vitejs.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vitejs.dev/guide/features.html#hot-module-replacement). + +- A [build command](https://vitejs.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production. + +In addition, Vite is highly extensible via its [Plugin API](https://vitejs.dev/guide/api-plugin.html) and [JavaScript API](https://vitejs.dev/guide/api-javascript.html) with full typing support. + +[Read the Docs to Learn More](https://vitejs.dev). diff --git a/web/node_modules/vite/bin/openChrome.applescript b/web/node_modules/vite/bin/openChrome.applescript new file mode 100644 index 0000000000000000000000000000000000000000..9ce2293231987ad28b0c23ece86147f0faad9676 --- /dev/null +++ b/web/node_modules/vite/bin/openChrome.applescript @@ -0,0 +1,95 @@ +(* +Copyright (c) 2015-present, Facebook, Inc. + +This source code is licensed under the MIT license found in the +LICENSE file at +https://github.com/facebookincubator/create-react-app/blob/master/LICENSE +*) + +property targetTab: null +property targetTabIndex: -1 +property targetWindow: null +property theProgram: "Google Chrome" + +on run argv + set theURL to item 1 of argv + + -- Allow requested program to be optional, + -- default to Google Chrome + if (count of argv) > 1 then + set theProgram to item 2 of argv + end if + + using terms from application "Google Chrome" + tell application theProgram + + if (count every window) = 0 then + make new window + end if + + -- 1: Looking for tab running debugger + -- then, Reload debugging tab if found + -- then return + set found to my lookupTabWithUrl(theURL) + if found then + set targetWindow's active tab index to targetTabIndex + tell targetTab to reload + tell targetWindow to activate + set index of targetWindow to 1 + return + end if + + -- 2: Looking for Empty tab + -- In case debugging tab was not found + -- We try to find an empty tab instead + set found to my lookupTabWithUrl("chrome://newtab/") + if found then + set targetWindow's active tab index to targetTabIndex + set URL of targetTab to theURL + tell targetWindow to activate + return + end if + + -- 3: Create new tab + -- both debugging and empty tab were not found + -- make a new tab with url + tell window 1 + activate + make new tab with properties {URL:theURL} + end tell + end tell + end using terms from +end run + +-- Function: +-- Lookup tab with given url +-- if found, store tab, index, and window in properties +-- (properties were declared on top of file) +on lookupTabWithUrl(lookupUrl) + using terms from application "Google Chrome" + tell application theProgram + -- Find a tab with the given url + set found to false + set theTabIndex to -1 + repeat with theWindow in every window + set theTabIndex to 0 + repeat with theTab in every tab of theWindow + set theTabIndex to theTabIndex + 1 + if (theTab's URL as string) contains lookupUrl then + -- assign tab, tab index, and window to properties + set targetTab to theTab + set targetTabIndex to theTabIndex + set targetWindow to theWindow + set found to true + exit repeat + end if + end repeat + + if found then + exit repeat + end if + end repeat + end tell + end using terms from + return found +end lookupTabWithUrl diff --git a/web/node_modules/vite/bin/vite.js b/web/node_modules/vite/bin/vite.js new file mode 100644 index 0000000000000000000000000000000000000000..a9bbb9c3a54716654ed2be91a4749b457dddd2f7 --- /dev/null +++ b/web/node_modules/vite/bin/vite.js @@ -0,0 +1,61 @@ +#!/usr/bin/env node +import { performance } from 'node:perf_hooks' + +if (!import.meta.url.includes('node_modules')) { + try { + // only available as dev dependency + await import('source-map-support').then((r) => r.default.install()) + } catch (e) {} +} + +global.__vite_start_time = performance.now() + +// check debug mode first before requiring the CLI. +const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg)) +const filterIndex = process.argv.findIndex((arg) => + /^(?:-f|--filter)$/.test(arg), +) +const profileIndex = process.argv.indexOf('--profile') + +if (debugIndex > 0) { + let value = process.argv[debugIndex + 1] + if (!value || value.startsWith('-')) { + value = 'vite:*' + } else { + // support debugging multiple flags with comma-separated list + value = value + .split(',') + .map((v) => `vite:${v}`) + .join(',') + } + process.env.DEBUG = `${ + process.env.DEBUG ? process.env.DEBUG + ',' : '' + }${value}` + + if (filterIndex > 0) { + const filter = process.argv[filterIndex + 1] + if (filter && !filter.startsWith('-')) { + process.env.VITE_DEBUG_FILTER = filter + } + } +} + +function start() { + return import('../dist/node/cli.js') +} + +if (profileIndex > 0) { + process.argv.splice(profileIndex, 1) + const next = process.argv[profileIndex] + if (next && !next.startsWith('-')) { + process.argv.splice(profileIndex, 1) + } + const inspector = await import('node:inspector').then((r) => r.default) + const session = (global.__vite_profile_session = new inspector.Session()) + session.connect() + session.post('Profiler.enable', () => { + session.post('Profiler.start', start) + }) +} else { + start() +} diff --git a/web/node_modules/vite/client.d.ts b/web/node_modules/vite/client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d81044009215ef258a07dcad470e52efbbaea3a --- /dev/null +++ b/web/node_modules/vite/client.d.ts @@ -0,0 +1,244 @@ +/// + +// CSS modules +type CSSModuleClasses = { readonly [key: string]: string } + +declare module '*.module.css' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.scss' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.sass' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.less' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.styl' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.stylus' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.pcss' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.sss' { + const classes: CSSModuleClasses + export default classes +} + +// CSS +declare module '*.css' {} +declare module '*.scss' {} +declare module '*.sass' {} +declare module '*.less' {} +declare module '*.styl' {} +declare module '*.stylus' {} +declare module '*.pcss' {} +declare module '*.sss' {} + +// Built-in asset types +// see `src/node/constants.ts` + +// images +declare module '*.apng' { + const src: string + export default src +} +declare module '*.png' { + const src: string + export default src +} +declare module '*.jpg' { + const src: string + export default src +} +declare module '*.jpeg' { + const src: string + export default src +} +declare module '*.jfif' { + const src: string + export default src +} +declare module '*.pjpeg' { + const src: string + export default src +} +declare module '*.pjp' { + const src: string + export default src +} +declare module '*.gif' { + const src: string + export default src +} +declare module '*.svg' { + const src: string + export default src +} +declare module '*.ico' { + const src: string + export default src +} +declare module '*.webp' { + const src: string + export default src +} +declare module '*.avif' { + const src: string + export default src +} + +// media +declare module '*.mp4' { + const src: string + export default src +} +declare module '*.webm' { + const src: string + export default src +} +declare module '*.ogg' { + const src: string + export default src +} +declare module '*.mp3' { + const src: string + export default src +} +declare module '*.wav' { + const src: string + export default src +} +declare module '*.flac' { + const src: string + export default src +} +declare module '*.aac' { + const src: string + export default src +} +declare module '*.opus' { + const src: string + export default src +} +declare module '*.mov' { + const src: string + export default src +} +declare module '*.m4a' { + const src: string + export default src +} +declare module '*.vtt' { + const src: string + export default src +} + +// fonts +declare module '*.woff' { + const src: string + export default src +} +declare module '*.woff2' { + const src: string + export default src +} +declare module '*.eot' { + const src: string + export default src +} +declare module '*.ttf' { + const src: string + export default src +} +declare module '*.otf' { + const src: string + export default src +} + +// other +declare module '*.webmanifest' { + const src: string + export default src +} +declare module '*.pdf' { + const src: string + export default src +} +declare module '*.txt' { + const src: string + export default src +} + +// wasm?init +declare module '*.wasm?init' { + const initWasm: ( + options?: WebAssembly.Imports, + ) => Promise + export default initWasm +} + +// web worker +declare module '*?worker' { + const workerConstructor: { + new (options?: { name?: string }): Worker + } + export default workerConstructor +} + +declare module '*?worker&inline' { + const workerConstructor: { + new (options?: { name?: string }): Worker + } + export default workerConstructor +} + +declare module '*?worker&url' { + const src: string + export default src +} + +declare module '*?sharedworker' { + const sharedWorkerConstructor: { + new (options?: { name?: string }): SharedWorker + } + export default sharedWorkerConstructor +} + +declare module '*?sharedworker&inline' { + const sharedWorkerConstructor: { + new (options?: { name?: string }): SharedWorker + } + export default sharedWorkerConstructor +} + +declare module '*?sharedworker&url' { + const src: string + export default src +} + +declare module '*?raw' { + const src: string + export default src +} + +declare module '*?url' { + const src: string + export default src +} + +declare module '*?inline' { + const src: string + export default src +} diff --git a/web/node_modules/vite/dist/client/client.mjs b/web/node_modules/vite/dist/client/client.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d9caf9c24b392126d9a618d98f0c64ecabb30d5 --- /dev/null +++ b/web/node_modules/vite/dist/client/client.mjs @@ -0,0 +1,804 @@ +import '@vite/env'; + +class HMRContext { + constructor(hmrClient, ownerPath) { + this.hmrClient = hmrClient; + this.ownerPath = ownerPath; + if (!hmrClient.dataMap.has(ownerPath)) { + hmrClient.dataMap.set(ownerPath, {}); + } + // when a file is hot updated, a new context is created + // clear its stale callbacks + const mod = hmrClient.hotModulesMap.get(ownerPath); + if (mod) { + mod.callbacks = []; + } + // clear stale custom event listeners + const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath); + if (staleListeners) { + for (const [event, staleFns] of staleListeners) { + const listeners = hmrClient.customListenersMap.get(event); + if (listeners) { + hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l))); + } + } + } + this.newListeners = new Map(); + hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners); + } + get data() { + return this.hmrClient.dataMap.get(this.ownerPath); + } + accept(deps, callback) { + if (typeof deps === 'function' || !deps) { + // self-accept: hot.accept(() => {}) + this.acceptDeps([this.ownerPath], ([mod]) => deps === null || deps === void 0 ? void 0 : deps(mod)); + } + else if (typeof deps === 'string') { + // explicit deps + this.acceptDeps([deps], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod)); + } + else if (Array.isArray(deps)) { + this.acceptDeps(deps, callback); + } + else { + throw new Error(`invalid hot.accept() usage.`); + } + } + // export names (first arg) are irrelevant on the client side, they're + // extracted in the server for propagation + acceptExports(_, callback) { + this.acceptDeps([this.ownerPath], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod)); + } + dispose(cb) { + this.hmrClient.disposeMap.set(this.ownerPath, cb); + } + prune(cb) { + this.hmrClient.pruneMap.set(this.ownerPath, cb); + } + // Kept for backward compatibility (#11036) + // eslint-disable-next-line @typescript-eslint/no-empty-function + decline() { } + invalidate(message) { + this.hmrClient.notifyListeners('vite:invalidate', { + path: this.ownerPath, + message, + }); + this.send('vite:invalidate', { path: this.ownerPath, message }); + this.hmrClient.logger.debug(`[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ''}`); + } + on(event, cb) { + const addToMap = (map) => { + const existing = map.get(event) || []; + existing.push(cb); + map.set(event, existing); + }; + addToMap(this.hmrClient.customListenersMap); + addToMap(this.newListeners); + } + off(event, cb) { + const removeFromMap = (map) => { + const existing = map.get(event); + if (existing === undefined) { + return; + } + const pruned = existing.filter((l) => l !== cb); + if (pruned.length === 0) { + map.delete(event); + return; + } + map.set(event, pruned); + }; + removeFromMap(this.hmrClient.customListenersMap); + removeFromMap(this.newListeners); + } + send(event, data) { + this.hmrClient.messenger.send(JSON.stringify({ type: 'custom', event, data })); + } + acceptDeps(deps, callback = () => { }) { + const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || { + id: this.ownerPath, + callbacks: [], + }; + mod.callbacks.push({ + deps, + fn: callback, + }); + this.hmrClient.hotModulesMap.set(this.ownerPath, mod); + } +} +class HMRMessenger { + constructor(connection) { + this.connection = connection; + this.queue = []; + } + send(message) { + this.queue.push(message); + this.flush(); + } + flush() { + if (this.connection.isReady()) { + this.queue.forEach((msg) => this.connection.send(msg)); + this.queue = []; + } + } +} +class HMRClient { + constructor(logger, connection, + // This allows implementing reloading via different methods depending on the environment + importUpdatedModule) { + this.logger = logger; + this.importUpdatedModule = importUpdatedModule; + this.hotModulesMap = new Map(); + this.disposeMap = new Map(); + this.pruneMap = new Map(); + this.dataMap = new Map(); + this.customListenersMap = new Map(); + this.ctxToListenersMap = new Map(); + this.updateQueue = []; + this.pendingUpdateQueue = false; + this.messenger = new HMRMessenger(connection); + } + async notifyListeners(event, data) { + const cbs = this.customListenersMap.get(event); + if (cbs) { + await Promise.allSettled(cbs.map((cb) => cb(data))); + } + } + clear() { + this.hotModulesMap.clear(); + this.disposeMap.clear(); + this.pruneMap.clear(); + this.dataMap.clear(); + this.customListenersMap.clear(); + this.ctxToListenersMap.clear(); + } + // After an HMR update, some modules are no longer imported on the page + // but they may have left behind side effects that need to be cleaned up + // (.e.g style injections) + // TODO Trigger their dispose callbacks. + prunePaths(paths) { + paths.forEach((path) => { + const fn = this.pruneMap.get(path); + if (fn) { + fn(this.dataMap.get(path)); + } + }); + } + warnFailedUpdate(err, path) { + if (!err.message.includes('fetch')) { + this.logger.error(err); + } + this.logger.error(`[hmr] Failed to reload ${path}. ` + + `This could be due to syntax errors or importing non-existent ` + + `modules. (see errors above)`); + } + /** + * buffer multiple hot updates triggered by the same src change + * so that they are invoked in the same order they were sent. + * (otherwise the order may be inconsistent because of the http request round trip) + */ + async queueUpdate(payload) { + this.updateQueue.push(this.fetchUpdate(payload)); + if (!this.pendingUpdateQueue) { + this.pendingUpdateQueue = true; + await Promise.resolve(); + this.pendingUpdateQueue = false; + const loading = [...this.updateQueue]; + this.updateQueue = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } + } + async fetchUpdate(update) { + const { path, acceptedPath } = update; + const mod = this.hotModulesMap.get(path); + if (!mod) { + // In a code-splitting project, + // it is common that the hot-updating module is not loaded yet. + // https://github.com/vitejs/vite/issues/721 + return; + } + let fetchedModule; + const isSelfUpdate = path === acceptedPath; + // determine the qualified callbacks before we re-import the modules + const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath)); + if (isSelfUpdate || qualifiedCallbacks.length > 0) { + const disposer = this.disposeMap.get(acceptedPath); + if (disposer) + await disposer(this.dataMap.get(acceptedPath)); + try { + fetchedModule = await this.importUpdatedModule(update); + } + catch (e) { + this.warnFailedUpdate(e, acceptedPath); + } + } + return () => { + for (const { deps, fn } of qualifiedCallbacks) { + fn(deps.map((dep) => (dep === acceptedPath ? fetchedModule : undefined))); + } + const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; + this.logger.debug(`[vite] hot updated: ${loggedPath}`); + }; + } +} + +const hmrConfigName = __HMR_CONFIG_NAME__; +const base$1 = __BASE__ || '/'; +// set :host styles to make playwright detect the element as visible +const template = /*html*/ ` + +
+
+
+

+    

+    

+    
+ Click outside, press Esc key, or fix the code to dismiss.
+ You can also disable this overlay by setting + server.hmr.overlay to false in ${hmrConfigName}. +
+
+
+`; +const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g; +const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm; +// Allow `ErrorOverlay` to extend `HTMLElement` even in environments where +// `HTMLElement` was not originally defined. +const { HTMLElement = class { +} } = globalThis; +class ErrorOverlay extends HTMLElement { + constructor(err, links = true) { + var _a; + super(); + this.root = this.attachShadow({ mode: 'open' }); + this.root.innerHTML = template; + codeframeRE.lastIndex = 0; + const hasFrame = err.frame && codeframeRE.test(err.frame); + const message = hasFrame + ? err.message.replace(codeframeRE, '') + : err.message; + if (err.plugin) { + this.text('.plugin', `[plugin:${err.plugin}] `); + } + this.text('.message-body', message.trim()); + const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`); + if (err.loc) { + this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links); + } + else if (err.id) { + this.text('.file', file); + } + if (hasFrame) { + this.text('.frame', err.frame.trim()); + } + this.text('.stack', err.stack, links); + this.root.querySelector('.window').addEventListener('click', (e) => { + e.stopPropagation(); + }); + this.addEventListener('click', () => { + this.close(); + }); + this.closeOnEsc = (e) => { + if (e.key === 'Escape' || e.code === 'Escape') { + this.close(); + } + }; + document.addEventListener('keydown', this.closeOnEsc); + } + text(selector, text, linkFiles = false) { + const el = this.root.querySelector(selector); + if (!linkFiles) { + el.textContent = text; + } + else { + let curIndex = 0; + let match; + fileRE.lastIndex = 0; + while ((match = fileRE.exec(text))) { + const { 0: file, index } = match; + if (index != null) { + const frag = text.slice(curIndex, index); + el.appendChild(document.createTextNode(frag)); + const link = document.createElement('a'); + link.textContent = file; + link.className = 'file-link'; + link.onclick = () => { + fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url)); + }; + el.appendChild(link); + curIndex += frag.length + file.length; + } + } + } + } + close() { + var _a; + (_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this); + document.removeEventListener('keydown', this.closeOnEsc); + } +} +const overlayId = 'vite-error-overlay'; +const { customElements } = globalThis; // Ensure `customElements` is defined before the next line. +if (customElements && !customElements.get(overlayId)) { + customElements.define(overlayId, ErrorOverlay); +} + +console.debug('[vite] connecting...'); +const importMetaUrl = new URL(import.meta.url); +// use server configuration, then fallback to inference +const serverHost = __SERVER_HOST__; +const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws'); +const hmrPort = __HMR_PORT__; +const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`; +const directSocketHost = __HMR_DIRECT_TARGET__; +const base = __BASE__ || '/'; +let socket; +try { + let fallback; + // only use fallback when port is inferred to prevent confusion + if (!hmrPort) { + fallback = () => { + // fallback to connecting directly to the hmr server + // for servers which does not support proxying websocket + socket = setupWebSocket(socketProtocol, directSocketHost, () => { + const currentScriptHostURL = new URL(import.meta.url); + const currentScriptHost = currentScriptHostURL.host + + currentScriptHostURL.pathname.replace(/@vite\/client$/, ''); + console.error('[vite] failed to connect to websocket.\n' + + 'your current setup:\n' + + ` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n` + + ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` + + 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .'); + }); + socket.addEventListener('open', () => { + console.info('[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.'); + }, { once: true }); + }; + } + socket = setupWebSocket(socketProtocol, socketHost, fallback); +} +catch (error) { + console.error(`[vite] failed to connect to websocket (${error}). `); +} +function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) { + const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr'); + let isOpened = false; + socket.addEventListener('open', () => { + isOpened = true; + notifyListeners('vite:ws:connect', { webSocket: socket }); + }, { once: true }); + // Listen for messages + socket.addEventListener('message', async ({ data }) => { + handleMessage(JSON.parse(data)); + }); + // ping server + socket.addEventListener('close', async ({ wasClean }) => { + if (wasClean) + return; + if (!isOpened && onCloseWithoutOpen) { + onCloseWithoutOpen(); + return; + } + notifyListeners('vite:ws:disconnect', { webSocket: socket }); + console.log(`[vite] server connection lost. polling for restart...`); + await waitForSuccessfulPing(protocol, hostAndPath); + location.reload(); + }); + return socket; +} +function cleanUrl(pathname) { + const url = new URL(pathname, location.toString()); + url.searchParams.delete('direct'); + return url.pathname + url.search; +} +let isFirstUpdate = true; +const outdatedLinkTags = new WeakSet(); +const debounceReload = (time) => { + let timer; + return () => { + if (timer) { + clearTimeout(timer); + timer = null; + } + timer = setTimeout(() => { + location.reload(); + }, time); + }; +}; +const pageReload = debounceReload(50); +const hmrClient = new HMRClient(console, { + isReady: () => socket && socket.readyState === 1, + send: (message) => socket.send(message), +}, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport, }) { + const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`); + const importPromise = import( + /* @vite-ignore */ + base + + acceptedPathWithoutQuery.slice(1) + + `?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${query ? `&${query}` : ''}`); + if (isWithinCircularImport) { + importPromise.catch(() => { + console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. ` + + `To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`); + pageReload(); + }); + } + return await importPromise; +}); +async function handleMessage(payload) { + switch (payload.type) { + case 'connected': + console.debug(`[vite] connected.`); + hmrClient.messenger.flush(); + // proxy(nginx, docker) hmr ws maybe caused timeout, + // so send ping package let ws keep alive. + setInterval(() => { + if (socket.readyState === socket.OPEN) { + socket.send('{"type":"ping"}'); + } + }, __HMR_TIMEOUT__); + break; + case 'update': + notifyListeners('vite:beforeUpdate', payload); + // if this is the first update and there's already an error overlay, it + // means the page opened with existing server compile error and the whole + // module script failed to load (since one of the nested imports is 500). + // in this case a normal update won't work and a full reload is needed. + if (isFirstUpdate && hasErrorOverlay()) { + window.location.reload(); + return; + } + else { + clearErrorOverlay(); + isFirstUpdate = false; + } + await Promise.all(payload.updates.map(async (update) => { + if (update.type === 'js-update') { + return hmrClient.queueUpdate(update); + } + // css-update + // this is only sent when a css file referenced with is updated + const { path, timestamp } = update; + const searchUrl = cleanUrl(path); + // can't use querySelector with `[href*=]` here since the link may be + // using relative paths so we need to use link.href to grab the full + // URL for the include check. + const el = Array.from(document.querySelectorAll('link')).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)); + if (!el) { + return; + } + const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`; + // rather than swapping the href on the existing tag, we will + // create a new link tag. Once the new stylesheet has loaded we + // will remove the existing link tag. This removes a Flash Of + // Unstyled Content that can occur when swapping out the tag href + // directly, as the new stylesheet has not yet been loaded. + return new Promise((resolve) => { + const newLinkTag = el.cloneNode(); + newLinkTag.href = new URL(newPath, el.href).href; + const removeOldEl = () => { + el.remove(); + console.debug(`[vite] css hot updated: ${searchUrl}`); + resolve(); + }; + newLinkTag.addEventListener('load', removeOldEl); + newLinkTag.addEventListener('error', removeOldEl); + outdatedLinkTags.add(el); + el.after(newLinkTag); + }); + })); + notifyListeners('vite:afterUpdate', payload); + break; + case 'custom': { + notifyListeners(payload.event, payload.data); + break; + } + case 'full-reload': + notifyListeners('vite:beforeFullReload', payload); + if (payload.path && payload.path.endsWith('.html')) { + // if html file is edited, only reload the page if the browser is + // currently on that page. + const pagePath = decodeURI(location.pathname); + const payloadPath = base + payload.path.slice(1); + if (pagePath === payloadPath || + payload.path === '/index.html' || + (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) { + pageReload(); + } + return; + } + else { + pageReload(); + } + break; + case 'prune': + notifyListeners('vite:beforePrune', payload); + hmrClient.prunePaths(payload.paths); + break; + case 'error': { + notifyListeners('vite:error', payload); + const err = payload.err; + if (enableOverlay) { + createErrorOverlay(err); + } + else { + console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`); + } + break; + } + default: { + const check = payload; + return check; + } + } +} +function notifyListeners(event, data) { + hmrClient.notifyListeners(event, data); +} +const enableOverlay = __HMR_ENABLE_OVERLAY__; +function createErrorOverlay(err) { + clearErrorOverlay(); + document.body.appendChild(new ErrorOverlay(err)); +} +function clearErrorOverlay() { + document.querySelectorAll(overlayId).forEach((n) => n.close()); +} +function hasErrorOverlay() { + return document.querySelectorAll(overlayId).length; +} +async function waitForSuccessfulPing(socketProtocol, hostAndPath, ms = 1000) { + const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'; + const ping = async () => { + // A fetch on a websocket URL will return a successful promise with status 400, + // but will reject a networking error. + // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors + try { + await fetch(`${pingHostProtocol}://${hostAndPath}`, { + mode: 'no-cors', + headers: { + // Custom headers won't be included in a request with no-cors so (ab)use one of the + // safelisted headers to identify the ping request + Accept: 'text/x-vite-ping', + }, + }); + return true; + } + catch { } + return false; + }; + if (await ping()) { + return; + } + await wait(ms); + // eslint-disable-next-line no-constant-condition + while (true) { + if (document.visibilityState === 'visible') { + if (await ping()) { + break; + } + await wait(ms); + } + else { + await waitForWindowShow(); + } + } +} +function wait(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function waitForWindowShow() { + return new Promise((resolve) => { + const onChange = async () => { + if (document.visibilityState === 'visible') { + resolve(); + document.removeEventListener('visibilitychange', onChange); + } + }; + document.addEventListener('visibilitychange', onChange); + }); +} +const sheetsMap = new Map(); +// collect existing style elements that may have been inserted during SSR +// to avoid FOUC or duplicate styles +if ('document' in globalThis) { + document + .querySelectorAll('style[data-vite-dev-id]') + .forEach((el) => { + sheetsMap.set(el.getAttribute('data-vite-dev-id'), el); + }); +} +// all css imports should be inserted at the same position +// because after build it will be a single css file +let lastInsertedStyle; +function updateStyle(id, content) { + let style = sheetsMap.get(id); + if (!style) { + style = document.createElement('style'); + style.setAttribute('type', 'text/css'); + style.setAttribute('data-vite-dev-id', id); + style.textContent = content; + if (!lastInsertedStyle) { + document.head.appendChild(style); + // reset lastInsertedStyle after async + // because dynamically imported css will be splitted into a different file + setTimeout(() => { + lastInsertedStyle = undefined; + }, 0); + } + else { + lastInsertedStyle.insertAdjacentElement('afterend', style); + } + lastInsertedStyle = style; + } + else { + style.textContent = content; + } + sheetsMap.set(id, style); +} +function removeStyle(id) { + const style = sheetsMap.get(id); + if (style) { + document.head.removeChild(style); + sheetsMap.delete(id); + } +} +function createHotContext(ownerPath) { + return new HMRContext(hmrClient, ownerPath); +} +/** + * urls here are dynamic import() urls that couldn't be statically analyzed + */ +function injectQuery(url, queryToInject) { + // skip urls that won't be handled by vite + if (url[0] !== '.' && url[0] !== '/') { + return url; + } + // can't use pathname from URL since it may be relative like ../ + const pathname = url.replace(/[?#].*$/, ''); + const { search, hash } = new URL(url, 'http://vitejs.dev'); + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; +} + +export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle }; +//# sourceMappingURL=client.mjs.map diff --git a/web/node_modules/vite/dist/client/client.mjs.map b/web/node_modules/vite/dist/client/client.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..adceda902fef74b5fbd5ec4d9bd4097d8d0e49dc --- /dev/null +++ b/web/node_modules/vite/dist/client/client.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"client.mjs","sources":["hmr.ts","overlay.ts","client.ts"],"sourcesContent":["import type { Update } from 'types/hmrPayload'\nimport type { ModuleNamespace, ViteHotContext } from 'types/hot'\nimport type { InferCustomEventPayload } from 'types/customEvent'\n\ntype CustomListenersMap = Map void)[]>\n\ninterface HotModule {\n id: string\n callbacks: HotCallback[]\n}\n\ninterface HotCallback {\n // the dependencies must be fetchable paths\n deps: string[]\n fn: (modules: Array) => void\n}\n\nexport interface HMRLogger {\n error(msg: string | Error): void\n debug(...msg: unknown[]): void\n}\n\nexport interface HMRConnection {\n /**\n * Checked before sending messages to the client.\n */\n isReady(): boolean\n /**\n * Send message to the client.\n */\n send(messages: string): void\n}\n\nexport class HMRContext implements ViteHotContext {\n private newListeners: CustomListenersMap\n\n constructor(\n private hmrClient: HMRClient,\n private ownerPath: string,\n ) {\n if (!hmrClient.dataMap.has(ownerPath)) {\n hmrClient.dataMap.set(ownerPath, {})\n }\n\n // when a file is hot updated, a new context is created\n // clear its stale callbacks\n const mod = hmrClient.hotModulesMap.get(ownerPath)\n if (mod) {\n mod.callbacks = []\n }\n\n // clear stale custom event listeners\n const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath)\n if (staleListeners) {\n for (const [event, staleFns] of staleListeners) {\n const listeners = hmrClient.customListenersMap.get(event)\n if (listeners) {\n hmrClient.customListenersMap.set(\n event,\n listeners.filter((l) => !staleFns.includes(l)),\n )\n }\n }\n }\n\n this.newListeners = new Map()\n hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners)\n }\n\n get data(): any {\n return this.hmrClient.dataMap.get(this.ownerPath)\n }\n\n accept(deps?: any, callback?: any): void {\n if (typeof deps === 'function' || !deps) {\n // self-accept: hot.accept(() => {})\n this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod))\n } else if (typeof deps === 'string') {\n // explicit deps\n this.acceptDeps([deps], ([mod]) => callback?.(mod))\n } else if (Array.isArray(deps)) {\n this.acceptDeps(deps, callback)\n } else {\n throw new Error(`invalid hot.accept() usage.`)\n }\n }\n\n // export names (first arg) are irrelevant on the client side, they're\n // extracted in the server for propagation\n acceptExports(\n _: string | readonly string[],\n callback: (data: any) => void,\n ): void {\n this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod))\n }\n\n dispose(cb: (data: any) => void): void {\n this.hmrClient.disposeMap.set(this.ownerPath, cb)\n }\n\n prune(cb: (data: any) => void): void {\n this.hmrClient.pruneMap.set(this.ownerPath, cb)\n }\n\n // Kept for backward compatibility (#11036)\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n decline(): void {}\n\n invalidate(message: string): void {\n this.hmrClient.notifyListeners('vite:invalidate', {\n path: this.ownerPath,\n message,\n })\n this.send('vite:invalidate', { path: this.ownerPath, message })\n this.hmrClient.logger.debug(\n `[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ''}`,\n )\n }\n\n on(\n event: T,\n cb: (payload: InferCustomEventPayload) => void,\n ): void {\n const addToMap = (map: Map) => {\n const existing = map.get(event) || []\n existing.push(cb)\n map.set(event, existing)\n }\n addToMap(this.hmrClient.customListenersMap)\n addToMap(this.newListeners)\n }\n\n off(\n event: T,\n cb: (payload: InferCustomEventPayload) => void,\n ): void {\n const removeFromMap = (map: Map) => {\n const existing = map.get(event)\n if (existing === undefined) {\n return\n }\n const pruned = existing.filter((l) => l !== cb)\n if (pruned.length === 0) {\n map.delete(event)\n return\n }\n map.set(event, pruned)\n }\n removeFromMap(this.hmrClient.customListenersMap)\n removeFromMap(this.newListeners)\n }\n\n send(event: T, data?: InferCustomEventPayload): void {\n this.hmrClient.messenger.send(\n JSON.stringify({ type: 'custom', event, data }),\n )\n }\n\n private acceptDeps(\n deps: string[],\n callback: HotCallback['fn'] = () => {},\n ): void {\n const mod: HotModule = this.hmrClient.hotModulesMap.get(this.ownerPath) || {\n id: this.ownerPath,\n callbacks: [],\n }\n mod.callbacks.push({\n deps,\n fn: callback,\n })\n this.hmrClient.hotModulesMap.set(this.ownerPath, mod)\n }\n}\n\nclass HMRMessenger {\n constructor(private connection: HMRConnection) {}\n\n private queue: string[] = []\n\n public send(message: string): void {\n this.queue.push(message)\n this.flush()\n }\n\n public flush(): void {\n if (this.connection.isReady()) {\n this.queue.forEach((msg) => this.connection.send(msg))\n this.queue = []\n }\n }\n}\n\nexport class HMRClient {\n public hotModulesMap = new Map()\n public disposeMap = new Map void | Promise>()\n public pruneMap = new Map void | Promise>()\n public dataMap = new Map()\n public customListenersMap: CustomListenersMap = new Map()\n public ctxToListenersMap = new Map()\n\n public messenger: HMRMessenger\n\n constructor(\n public logger: HMRLogger,\n connection: HMRConnection,\n // This allows implementing reloading via different methods depending on the environment\n private importUpdatedModule: (update: Update) => Promise,\n ) {\n this.messenger = new HMRMessenger(connection)\n }\n\n public async notifyListeners(\n event: T,\n data: InferCustomEventPayload,\n ): Promise\n public async notifyListeners(event: string, data: any): Promise {\n const cbs = this.customListenersMap.get(event)\n if (cbs) {\n await Promise.allSettled(cbs.map((cb) => cb(data)))\n }\n }\n\n public clear(): void {\n this.hotModulesMap.clear()\n this.disposeMap.clear()\n this.pruneMap.clear()\n this.dataMap.clear()\n this.customListenersMap.clear()\n this.ctxToListenersMap.clear()\n }\n\n // After an HMR update, some modules are no longer imported on the page\n // but they may have left behind side effects that need to be cleaned up\n // (.e.g style injections)\n // TODO Trigger their dispose callbacks.\n public prunePaths(paths: string[]): void {\n paths.forEach((path) => {\n const fn = this.pruneMap.get(path)\n if (fn) {\n fn(this.dataMap.get(path))\n }\n })\n }\n\n protected warnFailedUpdate(err: Error, path: string | string[]): void {\n if (!err.message.includes('fetch')) {\n this.logger.error(err)\n }\n this.logger.error(\n `[hmr] Failed to reload ${path}. ` +\n `This could be due to syntax errors or importing non-existent ` +\n `modules. (see errors above)`,\n )\n }\n\n private updateQueue: Promise<(() => void) | undefined>[] = []\n private pendingUpdateQueue = false\n\n /**\n * buffer multiple hot updates triggered by the same src change\n * so that they are invoked in the same order they were sent.\n * (otherwise the order may be inconsistent because of the http request round trip)\n */\n public async queueUpdate(payload: Update): Promise {\n this.updateQueue.push(this.fetchUpdate(payload))\n if (!this.pendingUpdateQueue) {\n this.pendingUpdateQueue = true\n await Promise.resolve()\n this.pendingUpdateQueue = false\n const loading = [...this.updateQueue]\n this.updateQueue = []\n ;(await Promise.all(loading)).forEach((fn) => fn && fn())\n }\n }\n\n private async fetchUpdate(update: Update): Promise<(() => void) | undefined> {\n const { path, acceptedPath } = update\n const mod = this.hotModulesMap.get(path)\n if (!mod) {\n // In a code-splitting project,\n // it is common that the hot-updating module is not loaded yet.\n // https://github.com/vitejs/vite/issues/721\n return\n }\n\n let fetchedModule: ModuleNamespace | undefined\n const isSelfUpdate = path === acceptedPath\n\n // determine the qualified callbacks before we re-import the modules\n const qualifiedCallbacks = mod.callbacks.filter(({ deps }) =>\n deps.includes(acceptedPath),\n )\n\n if (isSelfUpdate || qualifiedCallbacks.length > 0) {\n const disposer = this.disposeMap.get(acceptedPath)\n if (disposer) await disposer(this.dataMap.get(acceptedPath))\n try {\n fetchedModule = await this.importUpdatedModule(update)\n } catch (e) {\n this.warnFailedUpdate(e, acceptedPath)\n }\n }\n\n return () => {\n for (const { deps, fn } of qualifiedCallbacks) {\n fn(\n deps.map((dep) => (dep === acceptedPath ? fetchedModule : undefined)),\n )\n }\n const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`\n this.logger.debug(`[vite] hot updated: ${loggedPath}`)\n }\n }\n}\n","import type { ErrorPayload } from 'types/hmrPayload'\n\n// injected by the hmr plugin when served\ndeclare const __BASE__: string\ndeclare const __HMR_CONFIG_NAME__: string\n\nconst hmrConfigName = __HMR_CONFIG_NAME__\nconst base = __BASE__ || '/'\n\n// set :host styles to make playwright detect the element as visible\nconst template = /*html*/ `\n\n
\n
\n
\n
\n    
\n    
\n    
\n Click outside, press Esc key, or fix the code to dismiss.
\n You can also disable this overlay by setting\n server.hmr.overlay to false in ${hmrConfigName}.\n
\n
\n
\n`\n\nconst fileRE = /(?:[a-zA-Z]:\\\\|\\/).*?:\\d+:\\d+/g\nconst codeframeRE = /^(?:>?\\s*\\d+\\s+\\|.*|\\s+\\|\\s*\\^.*)\\r?\\n/gm\n\n// Allow `ErrorOverlay` to extend `HTMLElement` even in environments where\n// `HTMLElement` was not originally defined.\nconst { HTMLElement = class {} as typeof globalThis.HTMLElement } = globalThis\nexport class ErrorOverlay extends HTMLElement {\n root: ShadowRoot\n closeOnEsc: (e: KeyboardEvent) => void\n\n constructor(err: ErrorPayload['err'], links = true) {\n super()\n this.root = this.attachShadow({ mode: 'open' })\n this.root.innerHTML = template\n\n codeframeRE.lastIndex = 0\n const hasFrame = err.frame && codeframeRE.test(err.frame)\n const message = hasFrame\n ? err.message.replace(codeframeRE, '')\n : err.message\n if (err.plugin) {\n this.text('.plugin', `[plugin:${err.plugin}] `)\n }\n this.text('.message-body', message.trim())\n\n const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)\n if (err.loc) {\n this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links)\n } else if (err.id) {\n this.text('.file', file)\n }\n\n if (hasFrame) {\n this.text('.frame', err.frame!.trim())\n }\n this.text('.stack', err.stack, links)\n\n this.root.querySelector('.window')!.addEventListener('click', (e) => {\n e.stopPropagation()\n })\n\n this.addEventListener('click', () => {\n this.close()\n })\n\n this.closeOnEsc = (e: KeyboardEvent) => {\n if (e.key === 'Escape' || e.code === 'Escape') {\n this.close()\n }\n }\n\n document.addEventListener('keydown', this.closeOnEsc)\n }\n\n text(selector: string, text: string, linkFiles = false): void {\n const el = this.root.querySelector(selector)!\n if (!linkFiles) {\n el.textContent = text\n } else {\n let curIndex = 0\n let match: RegExpExecArray | null\n fileRE.lastIndex = 0\n while ((match = fileRE.exec(text))) {\n const { 0: file, index } = match\n if (index != null) {\n const frag = text.slice(curIndex, index)\n el.appendChild(document.createTextNode(frag))\n const link = document.createElement('a')\n link.textContent = file\n link.className = 'file-link'\n link.onclick = () => {\n fetch(\n new URL(\n `${base}__open-in-editor?file=${encodeURIComponent(file)}`,\n import.meta.url,\n ),\n )\n }\n el.appendChild(link)\n curIndex += frag.length + file.length\n }\n }\n }\n }\n close(): void {\n this.parentNode?.removeChild(this)\n document.removeEventListener('keydown', this.closeOnEsc)\n }\n}\n\nexport const overlayId = 'vite-error-overlay'\nconst { customElements } = globalThis // Ensure `customElements` is defined before the next line.\nif (customElements && !customElements.get(overlayId)) {\n customElements.define(overlayId, ErrorOverlay)\n}\n","import type { ErrorPayload, HMRPayload } from 'types/hmrPayload'\nimport type { ViteHotContext } from 'types/hot'\nimport type { InferCustomEventPayload } from 'types/customEvent'\nimport { HMRClient, HMRContext } from '../shared/hmr'\nimport { ErrorOverlay, overlayId } from './overlay'\nimport '@vite/env'\n\n// injected by the hmr plugin when served\ndeclare const __BASE__: string\ndeclare const __SERVER_HOST__: string\ndeclare const __HMR_PROTOCOL__: string | null\ndeclare const __HMR_HOSTNAME__: string | null\ndeclare const __HMR_PORT__: number | null\ndeclare const __HMR_DIRECT_TARGET__: string\ndeclare const __HMR_BASE__: string\ndeclare const __HMR_TIMEOUT__: number\ndeclare const __HMR_ENABLE_OVERLAY__: boolean\n\nconsole.debug('[vite] connecting...')\n\nconst importMetaUrl = new URL(import.meta.url)\n\n// use server configuration, then fallback to inference\nconst serverHost = __SERVER_HOST__\nconst socketProtocol =\n __HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws')\nconst hmrPort = __HMR_PORT__\nconst socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${\n hmrPort || importMetaUrl.port\n}${__HMR_BASE__}`\nconst directSocketHost = __HMR_DIRECT_TARGET__\nconst base = __BASE__ || '/'\n\nlet socket: WebSocket\ntry {\n let fallback: (() => void) | undefined\n // only use fallback when port is inferred to prevent confusion\n if (!hmrPort) {\n fallback = () => {\n // fallback to connecting directly to the hmr server\n // for servers which does not support proxying websocket\n socket = setupWebSocket(socketProtocol, directSocketHost, () => {\n const currentScriptHostURL = new URL(import.meta.url)\n const currentScriptHost =\n currentScriptHostURL.host +\n currentScriptHostURL.pathname.replace(/@vite\\/client$/, '')\n console.error(\n '[vite] failed to connect to websocket.\\n' +\n 'your current setup:\\n' +\n ` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\\n` +\n ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\\n` +\n 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .',\n )\n })\n socket.addEventListener(\n 'open',\n () => {\n console.info(\n '[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.',\n )\n },\n { once: true },\n )\n }\n }\n\n socket = setupWebSocket(socketProtocol, socketHost, fallback)\n} catch (error) {\n console.error(`[vite] failed to connect to websocket (${error}). `)\n}\n\nfunction setupWebSocket(\n protocol: string,\n hostAndPath: string,\n onCloseWithoutOpen?: () => void,\n) {\n const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr')\n let isOpened = false\n\n socket.addEventListener(\n 'open',\n () => {\n isOpened = true\n notifyListeners('vite:ws:connect', { webSocket: socket })\n },\n { once: true },\n )\n\n // Listen for messages\n socket.addEventListener('message', async ({ data }) => {\n handleMessage(JSON.parse(data))\n })\n\n // ping server\n socket.addEventListener('close', async ({ wasClean }) => {\n if (wasClean) return\n\n if (!isOpened && onCloseWithoutOpen) {\n onCloseWithoutOpen()\n return\n }\n\n notifyListeners('vite:ws:disconnect', { webSocket: socket })\n\n console.log(`[vite] server connection lost. polling for restart...`)\n await waitForSuccessfulPing(protocol, hostAndPath)\n location.reload()\n })\n\n return socket\n}\n\nfunction cleanUrl(pathname: string): string {\n const url = new URL(pathname, location.toString())\n url.searchParams.delete('direct')\n return url.pathname + url.search\n}\n\nlet isFirstUpdate = true\nconst outdatedLinkTags = new WeakSet()\n\nconst debounceReload = (time: number) => {\n let timer: ReturnType | null\n return () => {\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n timer = setTimeout(() => {\n location.reload()\n }, time)\n }\n}\nconst pageReload = debounceReload(50)\n\nconst hmrClient = new HMRClient(\n console,\n {\n isReady: () => socket && socket.readyState === 1,\n send: (message) => socket.send(message),\n },\n async function importUpdatedModule({\n acceptedPath,\n timestamp,\n explicitImportRequired,\n isWithinCircularImport,\n }) {\n const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`)\n const importPromise = import(\n /* @vite-ignore */\n base +\n acceptedPathWithoutQuery.slice(1) +\n `?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${\n query ? `&${query}` : ''\n }`\n )\n if (isWithinCircularImport) {\n importPromise.catch(() => {\n console.info(\n `[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. ` +\n `To debug and break the circular import, you can run \\`vite --debug hmr\\` to log the circular dependency path if a file change triggered it.`,\n )\n pageReload()\n })\n }\n return await importPromise\n },\n)\n\nasync function handleMessage(payload: HMRPayload) {\n switch (payload.type) {\n case 'connected':\n console.debug(`[vite] connected.`)\n hmrClient.messenger.flush()\n // proxy(nginx, docker) hmr ws maybe caused timeout,\n // so send ping package let ws keep alive.\n setInterval(() => {\n if (socket.readyState === socket.OPEN) {\n socket.send('{\"type\":\"ping\"}')\n }\n }, __HMR_TIMEOUT__)\n break\n case 'update':\n notifyListeners('vite:beforeUpdate', payload)\n // if this is the first update and there's already an error overlay, it\n // means the page opened with existing server compile error and the whole\n // module script failed to load (since one of the nested imports is 500).\n // in this case a normal update won't work and a full reload is needed.\n if (isFirstUpdate && hasErrorOverlay()) {\n window.location.reload()\n return\n } else {\n clearErrorOverlay()\n isFirstUpdate = false\n }\n await Promise.all(\n payload.updates.map(async (update): Promise => {\n if (update.type === 'js-update') {\n return hmrClient.queueUpdate(update)\n }\n\n // css-update\n // this is only sent when a css file referenced with is updated\n const { path, timestamp } = update\n const searchUrl = cleanUrl(path)\n // can't use querySelector with `[href*=]` here since the link may be\n // using relative paths so we need to use link.href to grab the full\n // URL for the include check.\n const el = Array.from(\n document.querySelectorAll('link'),\n ).find(\n (e) =>\n !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl),\n )\n\n if (!el) {\n return\n }\n\n const newPath = `${base}${searchUrl.slice(1)}${\n searchUrl.includes('?') ? '&' : '?'\n }t=${timestamp}`\n\n // rather than swapping the href on the existing tag, we will\n // create a new link tag. Once the new stylesheet has loaded we\n // will remove the existing link tag. This removes a Flash Of\n // Unstyled Content that can occur when swapping out the tag href\n // directly, as the new stylesheet has not yet been loaded.\n return new Promise((resolve) => {\n const newLinkTag = el.cloneNode() as HTMLLinkElement\n newLinkTag.href = new URL(newPath, el.href).href\n const removeOldEl = () => {\n el.remove()\n console.debug(`[vite] css hot updated: ${searchUrl}`)\n resolve()\n }\n newLinkTag.addEventListener('load', removeOldEl)\n newLinkTag.addEventListener('error', removeOldEl)\n outdatedLinkTags.add(el)\n el.after(newLinkTag)\n })\n }),\n )\n notifyListeners('vite:afterUpdate', payload)\n break\n case 'custom': {\n notifyListeners(payload.event, payload.data)\n break\n }\n case 'full-reload':\n notifyListeners('vite:beforeFullReload', payload)\n if (payload.path && payload.path.endsWith('.html')) {\n // if html file is edited, only reload the page if the browser is\n // currently on that page.\n const pagePath = decodeURI(location.pathname)\n const payloadPath = base + payload.path.slice(1)\n if (\n pagePath === payloadPath ||\n payload.path === '/index.html' ||\n (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)\n ) {\n pageReload()\n }\n return\n } else {\n pageReload()\n }\n break\n case 'prune':\n notifyListeners('vite:beforePrune', payload)\n hmrClient.prunePaths(payload.paths)\n break\n case 'error': {\n notifyListeners('vite:error', payload)\n const err = payload.err\n if (enableOverlay) {\n createErrorOverlay(err)\n } else {\n console.error(\n `[vite] Internal Server Error\\n${err.message}\\n${err.stack}`,\n )\n }\n break\n }\n default: {\n const check: never = payload\n return check\n }\n }\n}\n\nfunction notifyListeners(\n event: T,\n data: InferCustomEventPayload,\n): void\nfunction notifyListeners(event: string, data: any): void {\n hmrClient.notifyListeners(event, data)\n}\n\nconst enableOverlay = __HMR_ENABLE_OVERLAY__\n\nfunction createErrorOverlay(err: ErrorPayload['err']) {\n clearErrorOverlay()\n document.body.appendChild(new ErrorOverlay(err))\n}\n\nfunction clearErrorOverlay() {\n document.querySelectorAll(overlayId).forEach((n) => n.close())\n}\n\nfunction hasErrorOverlay() {\n return document.querySelectorAll(overlayId).length\n}\n\nasync function waitForSuccessfulPing(\n socketProtocol: string,\n hostAndPath: string,\n ms = 1000,\n) {\n const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'\n\n const ping = async () => {\n // A fetch on a websocket URL will return a successful promise with status 400,\n // but will reject a networking error.\n // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors\n try {\n await fetch(`${pingHostProtocol}://${hostAndPath}`, {\n mode: 'no-cors',\n headers: {\n // Custom headers won't be included in a request with no-cors so (ab)use one of the\n // safelisted headers to identify the ping request\n Accept: 'text/x-vite-ping',\n },\n })\n return true\n } catch {}\n return false\n }\n\n if (await ping()) {\n return\n }\n await wait(ms)\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (document.visibilityState === 'visible') {\n if (await ping()) {\n break\n }\n await wait(ms)\n } else {\n await waitForWindowShow()\n }\n }\n}\n\nfunction wait(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction waitForWindowShow() {\n return new Promise((resolve) => {\n const onChange = async () => {\n if (document.visibilityState === 'visible') {\n resolve()\n document.removeEventListener('visibilitychange', onChange)\n }\n }\n document.addEventListener('visibilitychange', onChange)\n })\n}\n\nconst sheetsMap = new Map()\n\n// collect existing style elements that may have been inserted during SSR\n// to avoid FOUC or duplicate styles\nif ('document' in globalThis) {\n document\n .querySelectorAll('style[data-vite-dev-id]')\n .forEach((el) => {\n sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)\n })\n}\n\n// all css imports should be inserted at the same position\n// because after build it will be a single css file\nlet lastInsertedStyle: HTMLStyleElement | undefined\n\nexport function updateStyle(id: string, content: string): void {\n let style = sheetsMap.get(id)\n if (!style) {\n style = document.createElement('style')\n style.setAttribute('type', 'text/css')\n style.setAttribute('data-vite-dev-id', id)\n style.textContent = content\n\n if (!lastInsertedStyle) {\n document.head.appendChild(style)\n\n // reset lastInsertedStyle after async\n // because dynamically imported css will be splitted into a different file\n setTimeout(() => {\n lastInsertedStyle = undefined\n }, 0)\n } else {\n lastInsertedStyle.insertAdjacentElement('afterend', style)\n }\n lastInsertedStyle = style\n } else {\n style.textContent = content\n }\n sheetsMap.set(id, style)\n}\n\nexport function removeStyle(id: string): void {\n const style = sheetsMap.get(id)\n if (style) {\n document.head.removeChild(style)\n sheetsMap.delete(id)\n }\n}\n\nexport function createHotContext(ownerPath: string): ViteHotContext {\n return new HMRContext(hmrClient, ownerPath)\n}\n\n/**\n * urls here are dynamic import() urls that couldn't be statically analyzed\n */\nexport function injectQuery(url: string, queryToInject: string): string {\n // skip urls that won't be handled by vite\n if (url[0] !== '.' && url[0] !== '/') {\n return url\n }\n\n // can't use pathname from URL since it may be relative like ../\n const pathname = url.replace(/[?#].*$/, '')\n const { search, hash } = new URL(url, 'http://vitejs.dev')\n\n return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${\n hash || ''\n }`\n}\n\nexport { ErrorOverlay }\n"],"names":["base"],"mappings":";;MAiCa,UAAU,CAAA;IAGrB,WACU,CAAA,SAAoB,EACpB,SAAiB,EAAA;QADjB,IAAS,CAAA,SAAA,GAAT,SAAS,CAAW;QACpB,IAAS,CAAA,SAAA,GAAT,SAAS,CAAQ;QAEzB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YACrC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;AACrC,SAAA;;;QAID,MAAM,GAAG,GAAG,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;AAClD,QAAA,IAAI,GAAG,EAAE;AACP,YAAA,GAAG,CAAC,SAAS,GAAG,EAAE,CAAA;AACnB,SAAA;;QAGD,MAAM,cAAc,GAAG,SAAS,CAAC,iBAAiB,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;AACjE,QAAA,IAAI,cAAc,EAAE;YAClB,KAAK,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,IAAI,cAAc,EAAE;gBAC9C,MAAM,SAAS,GAAG,SAAS,CAAC,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;AACzD,gBAAA,IAAI,SAAS,EAAE;oBACb,SAAS,CAAC,kBAAkB,CAAC,GAAG,CAC9B,KAAK,EACL,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAC/C,CAAA;AACF,iBAAA;AACF,aAAA;AACF,SAAA;AAED,QAAA,IAAI,CAAC,YAAY,GAAG,IAAI,GAAG,EAAE,CAAA;QAC7B,SAAS,CAAC,iBAAiB,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;KAC9D;AAED,IAAA,IAAI,IAAI,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;KAClD;IAED,MAAM,CAAC,IAAU,EAAE,QAAc,EAAA;AAC/B,QAAA,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,CAAC,IAAI,EAAE;;YAEvC,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,KAAJ,IAAA,IAAA,IAAI,KAAJ,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,IAAI,CAAG,GAAG,CAAC,CAAC,CAAA;AAC1D,SAAA;AAAM,aAAA,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;;YAEnC,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,QAAQ,KAAA,IAAA,IAAR,QAAQ,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAR,QAAQ,CAAG,GAAG,CAAC,CAAC,CAAA;AACpD,SAAA;AAAM,aAAA,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;AAC9B,YAAA,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;AAChC,SAAA;AAAM,aAAA;AACL,YAAA,MAAM,IAAI,KAAK,CAAC,CAAA,2BAAA,CAA6B,CAAC,CAAA;AAC/C,SAAA;KACF;;;IAID,aAAa,CACX,CAA6B,EAC7B,QAA6B,EAAA;QAE7B,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,QAAQ,KAAR,IAAA,IAAA,QAAQ,KAAR,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,QAAQ,CAAG,GAAG,CAAC,CAAC,CAAA;KAC9D;AAED,IAAA,OAAO,CAAC,EAAuB,EAAA;AAC7B,QAAA,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;KAClD;AAED,IAAA,KAAK,CAAC,EAAuB,EAAA;AAC3B,QAAA,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;KAChD;;;AAID,IAAA,OAAO,MAAW;AAElB,IAAA,UAAU,CAAC,OAAe,EAAA;AACxB,QAAA,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,iBAAiB,EAAE;YAChD,IAAI,EAAE,IAAI,CAAC,SAAS;YACpB,OAAO;AACR,SAAA,CAAC,CAAA;AACF,QAAA,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,CAAC,CAAA;QAC/D,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CACzB,CAAA,kBAAA,EAAqB,IAAI,CAAC,SAAS,CAAA,EAAG,OAAO,GAAG,CAAA,EAAA,EAAK,OAAO,CAAA,CAAE,GAAG,EAAE,CAAE,CAAA,CACtE,CAAA;KACF;IAED,EAAE,CACA,KAAQ,EACR,EAAiD,EAAA;AAEjD,QAAA,MAAM,QAAQ,GAAG,CAAC,GAAuB,KAAI;YAC3C,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAA;AACrC,YAAA,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;AACjB,YAAA,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;AAC1B,SAAC,CAAA;AACD,QAAA,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAA;AAC3C,QAAA,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;KAC5B;IAED,GAAG,CACD,KAAQ,EACR,EAAiD,EAAA;AAEjD,QAAA,MAAM,aAAa,GAAG,CAAC,GAAuB,KAAI;YAChD,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YAC/B,IAAI,QAAQ,KAAK,SAAS,EAAE;gBAC1B,OAAM;AACP,aAAA;AACD,YAAA,MAAM,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAA;AAC/C,YAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACvB,gBAAA,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;gBACjB,OAAM;AACP,aAAA;AACD,YAAA,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;AACxB,SAAC,CAAA;AACD,QAAA,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAA;AAChD,QAAA,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;KACjC;IAED,IAAI,CAAmB,KAAQ,EAAE,IAAiC,EAAA;QAChE,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,CAC3B,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAChD,CAAA;KACF;AAEO,IAAA,UAAU,CAChB,IAAc,EACd,WAA8B,SAAQ,EAAA;AAEtC,QAAA,MAAM,GAAG,GAAc,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI;YACzE,EAAE,EAAE,IAAI,CAAC,SAAS;AAClB,YAAA,SAAS,EAAE,EAAE;SACd,CAAA;AACD,QAAA,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC;YACjB,IAAI;AACJ,YAAA,EAAE,EAAE,QAAQ;AACb,SAAA,CAAC,CAAA;AACF,QAAA,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;KACtD;AACF,CAAA;AAED,MAAM,YAAY,CAAA;AAChB,IAAA,WAAA,CAAoB,UAAyB,EAAA;QAAzB,IAAU,CAAA,UAAA,GAAV,UAAU,CAAe;QAErC,IAAK,CAAA,KAAA,GAAa,EAAE,CAAA;KAFqB;AAI1C,IAAA,IAAI,CAAC,OAAe,EAAA;AACzB,QAAA,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QACxB,IAAI,CAAC,KAAK,EAAE,CAAA;KACb;IAEM,KAAK,GAAA;AACV,QAAA,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE;AAC7B,YAAA,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,GAAG,KAAK,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AACtD,YAAA,IAAI,CAAC,KAAK,GAAG,EAAE,CAAA;AAChB,SAAA;KACF;AACF,CAAA;MAEY,SAAS,CAAA;IAUpB,WACS,CAAA,MAAiB,EACxB,UAAyB;;IAEjB,mBAAiE,EAAA;QAHlE,IAAM,CAAA,MAAA,GAAN,MAAM,CAAW;QAGhB,IAAmB,CAAA,mBAAA,GAAnB,mBAAmB,CAA8C;AAbpE,QAAA,IAAA,CAAA,aAAa,GAAG,IAAI,GAAG,EAAqB,CAAA;AAC5C,QAAA,IAAA,CAAA,UAAU,GAAG,IAAI,GAAG,EAA+C,CAAA;AACnE,QAAA,IAAA,CAAA,QAAQ,GAAG,IAAI,GAAG,EAA+C,CAAA;AACjE,QAAA,IAAA,CAAA,OAAO,GAAG,IAAI,GAAG,EAAe,CAAA;AAChC,QAAA,IAAA,CAAA,kBAAkB,GAAuB,IAAI,GAAG,EAAE,CAAA;AAClD,QAAA,IAAA,CAAA,iBAAiB,GAAG,IAAI,GAAG,EAA8B,CAAA;QAyDxD,IAAW,CAAA,WAAA,GAAwC,EAAE,CAAA;QACrD,IAAkB,CAAA,kBAAA,GAAG,KAAK,CAAA;QAhDhC,IAAI,CAAC,SAAS,GAAG,IAAI,YAAY,CAAC,UAAU,CAAC,CAAA;KAC9C;AAMM,IAAA,MAAM,eAAe,CAAC,KAAa,EAAE,IAAS,EAAA;QACnD,MAAM,GAAG,GAAG,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;AAC9C,QAAA,IAAI,GAAG,EAAE;AACP,YAAA,MAAM,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,SAAA;KACF;IAEM,KAAK,GAAA;AACV,QAAA,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAA;AAC1B,QAAA,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAA;AACvB,QAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;AACrB,QAAA,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAA;AACpB,QAAA,IAAI,CAAC,kBAAkB,CAAC,KAAK,EAAE,CAAA;AAC/B,QAAA,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAA;KAC/B;;;;;AAMM,IAAA,UAAU,CAAC,KAAe,EAAA;AAC/B,QAAA,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,KAAI;YACrB,MAAM,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;AAClC,YAAA,IAAI,EAAE,EAAE;gBACN,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAA;AAC3B,aAAA;AACH,SAAC,CAAC,CAAA;KACH;IAES,gBAAgB,CAAC,GAAU,EAAE,IAAuB,EAAA;QAC5D,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;AAClC,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AACvB,SAAA;AACD,QAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,CAAA,uBAAA,EAA0B,IAAI,CAAI,EAAA,CAAA;YAChC,CAA+D,6DAAA,CAAA;AAC/D,YAAA,CAAA,2BAAA,CAA6B,CAChC,CAAA;KACF;AAKD;;;;AAIG;IACI,MAAM,WAAW,CAAC,OAAe,EAAA;AACtC,QAAA,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAA;AAChD,QAAA,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE;AAC5B,YAAA,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAA;AAC9B,YAAA,MAAM,OAAO,CAAC,OAAO,EAAE,CAAA;AACvB,YAAA,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAA;YAC/B,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,CAAA;AACrC,YAAA,IAAI,CAAC,WAAW,GAAG,EAAE,CACpB;YAAA,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,CAAA;AAC1D,SAAA;KACF;IAEO,MAAM,WAAW,CAAC,MAAc,EAAA;AACtC,QAAA,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,MAAM,CAAA;QACrC,MAAM,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACxC,IAAI,CAAC,GAAG,EAAE;;;;YAIR,OAAM;AACP,SAAA;AAED,QAAA,IAAI,aAA0C,CAAA;AAC9C,QAAA,MAAM,YAAY,GAAG,IAAI,KAAK,YAAY,CAAA;;QAG1C,MAAM,kBAAkB,GAAG,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,KACvD,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,CAC5B,CAAA;AAED,QAAA,IAAI,YAAY,IAAI,kBAAkB,CAAC,MAAM,GAAG,CAAC,EAAE;YACjD,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,CAAA;AAClD,YAAA,IAAI,QAAQ;gBAAE,MAAM,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAA;YAC5D,IAAI;gBACF,aAAa,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAA;AACvD,aAAA;AAAC,YAAA,OAAO,CAAC,EAAE;AACV,gBAAA,IAAI,CAAC,gBAAgB,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AACvC,aAAA;AACF,SAAA;AAED,QAAA,OAAO,MAAK;YACV,KAAK,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,kBAAkB,EAAE;gBAC7C,EAAE,CACA,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,GAAG,KAAK,YAAY,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC,CACtE,CAAA;AACF,aAAA;AACD,YAAA,MAAM,UAAU,GAAG,YAAY,GAAG,IAAI,GAAG,CAAG,EAAA,YAAY,CAAQ,KAAA,EAAA,IAAI,EAAE,CAAA;YACtE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAuB,oBAAA,EAAA,UAAU,CAAE,CAAA,CAAC,CAAA;AACxD,SAAC,CAAA;KACF;AACF;;ACnTD,MAAM,aAAa,GAAG,mBAAmB,CAAA;AACzC,MAAMA,MAAI,GAAG,QAAQ,IAAI,GAAG,CAAA;AAE5B;AACA,MAAM,QAAQ,YAAY,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oJAsJ0H,aAAa,CAAA;;;;CAIhK,CAAA;AAED,MAAM,MAAM,GAAG,gCAAgC,CAAA;AAC/C,MAAM,WAAW,GAAG,0CAA0C,CAAA;AAE9D;AACA;AACA,MAAM,EAAE,WAAW,GAAG,MAAA;CAAyC,EAAE,GAAG,UAAU,CAAA;AACxE,MAAO,YAAa,SAAQ,WAAW,CAAA;AAI3C,IAAA,WAAA,CAAY,GAAwB,EAAE,KAAK,GAAG,IAAI,EAAA;;AAChD,QAAA,KAAK,EAAE,CAAA;AACP,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;AAC/C,QAAA,IAAI,CAAC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;AAE9B,QAAA,WAAW,CAAC,SAAS,GAAG,CAAC,CAAA;AACzB,QAAA,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,IAAI,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACzD,MAAM,OAAO,GAAG,QAAQ;cACpB,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;AACtC,cAAE,GAAG,CAAC,OAAO,CAAA;QACf,IAAI,GAAG,CAAC,MAAM,EAAE;YACd,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAW,QAAA,EAAA,GAAG,CAAC,MAAM,CAAI,EAAA,CAAA,CAAC,CAAA;AAChD,SAAA;QACD,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;QAE1C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA,CAAA,EAAA,GAAA,GAAG,CAAC,GAAG,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAI,KAAI,GAAG,CAAC,EAAE,IAAI,cAAc,EAAE,KAAK,CAAC,CAAG,CAAA,CAAA,CAAC,CAAA;QACrE,IAAI,GAAG,CAAC,GAAG,EAAE;YACX,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAG,EAAA,IAAI,CAAI,CAAA,EAAA,GAAG,CAAC,GAAG,CAAC,IAAI,CAAA,CAAA,EAAI,GAAG,CAAC,GAAG,CAAC,MAAM,CAAE,CAAA,EAAE,KAAK,CAAC,CAAA;AACvE,SAAA;aAAM,IAAI,GAAG,CAAC,EAAE,EAAE;AACjB,YAAA,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACzB,SAAA;AAED,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,KAAM,CAAC,IAAI,EAAE,CAAC,CAAA;AACvC,SAAA;QACD,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAErC,QAAA,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,SAAS,CAAE,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC,KAAI;YAClE,CAAC,CAAC,eAAe,EAAE,CAAA;AACrB,SAAC,CAAC,CAAA;AAEF,QAAA,IAAI,CAAC,gBAAgB,CAAC,OAAO,EAAE,MAAK;YAClC,IAAI,CAAC,KAAK,EAAE,CAAA;AACd,SAAC,CAAC,CAAA;AAEF,QAAA,IAAI,CAAC,UAAU,GAAG,CAAC,CAAgB,KAAI;YACrC,IAAI,CAAC,CAAC,GAAG,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE;gBAC7C,IAAI,CAAC,KAAK,EAAE,CAAA;AACb,aAAA;AACH,SAAC,CAAA;QAED,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;KACtD;AAED,IAAA,IAAI,CAAC,QAAgB,EAAE,IAAY,EAAE,SAAS,GAAG,KAAK,EAAA;QACpD,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAE,CAAA;QAC7C,IAAI,CAAC,SAAS,EAAE;AACd,YAAA,EAAE,CAAC,WAAW,GAAG,IAAI,CAAA;AACtB,SAAA;AAAM,aAAA;YACL,IAAI,QAAQ,GAAG,CAAC,CAAA;AAChB,YAAA,IAAI,KAA6B,CAAA;AACjC,YAAA,MAAM,CAAC,SAAS,GAAG,CAAC,CAAA;YACpB,QAAQ,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;gBAClC,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,KAAK,CAAA;gBAChC,IAAI,KAAK,IAAI,IAAI,EAAE;oBACjB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;oBACxC,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAA;oBAC7C,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;AACxC,oBAAA,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;AACvB,oBAAA,IAAI,CAAC,SAAS,GAAG,WAAW,CAAA;AAC5B,oBAAA,IAAI,CAAC,OAAO,GAAG,MAAK;wBAClB,KAAK,CACH,IAAI,GAAG,CACL,GAAGA,MAAI,CAAA,sBAAA,EAAyB,kBAAkB,CAAC,IAAI,CAAC,CAAE,CAAA,EAC1D,MAAM,CAAC,IAAI,CAAC,GAAG,CAChB,CACF,CAAA;AACH,qBAAC,CAAA;AACD,oBAAA,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;oBACpB,QAAQ,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;AACtC,iBAAA;AACF,aAAA;AACF,SAAA;KACF;IACD,KAAK,GAAA;;QACH,CAAA,EAAA,GAAA,IAAI,CAAC,UAAU,MAAA,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAE,WAAW,CAAC,IAAI,CAAC,CAAA;QAClC,QAAQ,CAAC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;KACzD;AACF,CAAA;AAEM,MAAM,SAAS,GAAG,oBAAoB,CAAA;AAC7C,MAAM,EAAE,cAAc,EAAE,GAAG,UAAU,CAAA;AACrC,IAAI,cAAc,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;AACpD,IAAA,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,CAAA;AAC/C;;AClPD,OAAO,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAA;AAErC,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAE9C;AACA,MAAM,UAAU,GAAG,eAAe,CAAA;AAClC,MAAM,cAAc,GAClB,gBAAgB,KAAK,aAAa,CAAC,QAAQ,KAAK,QAAQ,GAAG,KAAK,GAAG,IAAI,CAAC,CAAA;AAC1E,MAAM,OAAO,GAAG,YAAY,CAAA;AAC5B,MAAM,UAAU,GAAG,CAAA,EAAG,gBAAgB,IAAI,aAAa,CAAC,QAAQ,CAC9D,CAAA,EAAA,OAAO,IAAI,aAAa,CAAC,IAC3B,CAAG,EAAA,YAAY,EAAE,CAAA;AACjB,MAAM,gBAAgB,GAAG,qBAAqB,CAAA;AAC9C,MAAM,IAAI,GAAG,QAAQ,IAAI,GAAG,CAAA;AAE5B,IAAI,MAAiB,CAAA;AACrB,IAAI;AACF,IAAA,IAAI,QAAkC,CAAA;;IAEtC,IAAI,CAAC,OAAO,EAAE;QACZ,QAAQ,GAAG,MAAK;;;YAGd,MAAM,GAAG,cAAc,CAAC,cAAc,EAAE,gBAAgB,EAAE,MAAK;gBAC7D,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACrD,gBAAA,MAAM,iBAAiB,GACrB,oBAAoB,CAAC,IAAI;oBACzB,oBAAoB,CAAC,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAA;gBAC7D,OAAO,CAAC,KAAK,CACX,0CAA0C;oBACxC,uBAAuB;oBACvB,CAAe,YAAA,EAAA,iBAAiB,CAAiB,cAAA,EAAA,UAAU,CAAa,WAAA,CAAA;oBACxE,CAAe,YAAA,EAAA,UAAU,CAAgC,6BAAA,EAAA,gBAAgB,CAAa,WAAA,CAAA;AACtF,oBAAA,4GAA4G,CAC/G,CAAA;AACH,aAAC,CAAC,CAAA;AACF,YAAA,MAAM,CAAC,gBAAgB,CACrB,MAAM,EACN,MAAK;AACH,gBAAA,OAAO,CAAC,IAAI,CACV,0JAA0J,CAC3J,CAAA;AACH,aAAC,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CACf,CAAA;AACH,SAAC,CAAA;AACF,KAAA;IAED,MAAM,GAAG,cAAc,CAAC,cAAc,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAA;AAC9D,CAAA;AAAC,OAAO,KAAK,EAAE;AACd,IAAA,OAAO,CAAC,KAAK,CAAC,0CAA0C,KAAK,CAAA,GAAA,CAAK,CAAC,CAAA;AACpE,CAAA;AAED,SAAS,cAAc,CACrB,QAAgB,EAChB,WAAmB,EACnB,kBAA+B,EAAA;AAE/B,IAAA,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,CAAA,EAAG,QAAQ,CAAA,GAAA,EAAM,WAAW,CAAA,CAAE,EAAE,UAAU,CAAC,CAAA;IACxE,IAAI,QAAQ,GAAG,KAAK,CAAA;AAEpB,IAAA,MAAM,CAAC,gBAAgB,CACrB,MAAM,EACN,MAAK;QACH,QAAQ,GAAG,IAAI,CAAA;QACf,eAAe,CAAC,iBAAiB,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAA;AAC3D,KAAC,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CACf,CAAA;;IAGD,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,KAAI;QACpD,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;AACjC,KAAC,CAAC,CAAA;;IAGF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAI;AACtD,QAAA,IAAI,QAAQ;YAAE,OAAM;AAEpB,QAAA,IAAI,CAAC,QAAQ,IAAI,kBAAkB,EAAE;AACnC,YAAA,kBAAkB,EAAE,CAAA;YACpB,OAAM;AACP,SAAA;QAED,eAAe,CAAC,oBAAoB,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAA;AAE5D,QAAA,OAAO,CAAC,GAAG,CAAC,CAAA,qDAAA,CAAuD,CAAC,CAAA;AACpE,QAAA,MAAM,qBAAqB,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;QAClD,QAAQ,CAAC,MAAM,EAAE,CAAA;AACnB,KAAC,CAAC,CAAA;AAEF,IAAA,OAAO,MAAM,CAAA;AACf,CAAC;AAED,SAAS,QAAQ,CAAC,QAAgB,EAAA;AAChC,IAAA,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAA;AAClD,IAAA,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;AACjC,IAAA,OAAO,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAA;AAClC,CAAC;AAED,IAAI,aAAa,GAAG,IAAI,CAAA;AACxB,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAmB,CAAA;AAEvD,MAAM,cAAc,GAAG,CAAC,IAAY,KAAI;AACtC,IAAA,IAAI,KAA2C,CAAA;AAC/C,IAAA,OAAO,MAAK;AACV,QAAA,IAAI,KAAK,EAAE;YACT,YAAY,CAAC,KAAK,CAAC,CAAA;YACnB,KAAK,GAAG,IAAI,CAAA;AACb,SAAA;AACD,QAAA,KAAK,GAAG,UAAU,CAAC,MAAK;YACtB,QAAQ,CAAC,MAAM,EAAE,CAAA;SAClB,EAAE,IAAI,CAAC,CAAA;AACV,KAAC,CAAA;AACH,CAAC,CAAA;AACD,MAAM,UAAU,GAAG,cAAc,CAAC,EAAE,CAAC,CAAA;AAErC,MAAM,SAAS,GAAG,IAAI,SAAS,CAC7B,OAAO,EACP;IACE,OAAO,EAAE,MAAM,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,CAAC;IAChD,IAAI,EAAE,CAAC,OAAO,KAAK,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC;AACxC,CAAA,EACD,eAAe,mBAAmB,CAAC,EACjC,YAAY,EACZ,SAAS,EACT,sBAAsB,EACtB,sBAAsB,GACvB,EAAA;AACC,IAAA,MAAM,CAAC,wBAAwB,EAAE,KAAK,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,CAAG,CAAA,CAAA,CAAC,CAAA;IACjE,MAAM,aAAa,GAAG;;IAEpB,IAAI;AACF,QAAA,wBAAwB,CAAC,KAAK,CAAC,CAAC,CAAC;QACjC,CAAI,CAAA,EAAA,sBAAsB,GAAG,SAAS,GAAG,EAAE,CAAA,EAAA,EAAK,SAAS,CAAA,EACvD,KAAK,GAAG,CAAA,CAAA,EAAI,KAAK,CAAA,CAAE,GAAG,EACxB,CAAE,CAAA,CACL,CAAA;AACD,IAAA,IAAI,sBAAsB,EAAE;AAC1B,QAAA,aAAa,CAAC,KAAK,CAAC,MAAK;AACvB,YAAA,OAAO,CAAC,IAAI,CACV,CAAA,MAAA,EAAS,YAAY,CAAsG,oGAAA,CAAA;AACzH,gBAAA,CAAA,2IAAA,CAA6I,CAChJ,CAAA;AACD,YAAA,UAAU,EAAE,CAAA;AACd,SAAC,CAAC,CAAA;AACH,KAAA;IACD,OAAO,MAAM,aAAa,CAAA;AAC5B,CAAC,CACF,CAAA;AAED,eAAe,aAAa,CAAC,OAAmB,EAAA;IAC9C,QAAQ,OAAO,CAAC,IAAI;AAClB,QAAA,KAAK,WAAW;AACd,YAAA,OAAO,CAAC,KAAK,CAAC,CAAA,iBAAA,CAAmB,CAAC,CAAA;AAClC,YAAA,SAAS,CAAC,SAAS,CAAC,KAAK,EAAE,CAAA;;;YAG3B,WAAW,CAAC,MAAK;AACf,gBAAA,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM,CAAC,IAAI,EAAE;AACrC,oBAAA,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAA;AAC/B,iBAAA;aACF,EAAE,eAAe,CAAC,CAAA;YACnB,MAAK;AACP,QAAA,KAAK,QAAQ;AACX,YAAA,eAAe,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAA;;;;;AAK7C,YAAA,IAAI,aAAa,IAAI,eAAe,EAAE,EAAE;AACtC,gBAAA,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAA;gBACxB,OAAM;AACP,aAAA;AAAM,iBAAA;AACL,gBAAA,iBAAiB,EAAE,CAAA;gBACnB,aAAa,GAAG,KAAK,CAAA;AACtB,aAAA;AACD,YAAA,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,MAAM,KAAmB;AAClD,gBAAA,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW,EAAE;AAC/B,oBAAA,OAAO,SAAS,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;AACrC,iBAAA;;;AAID,gBAAA,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,CAAA;AAClC,gBAAA,MAAM,SAAS,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAA;;;;AAIhC,gBAAA,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CACnB,QAAQ,CAAC,gBAAgB,CAAkB,MAAM,CAAC,CACnD,CAAC,IAAI,CACJ,CAAC,CAAC,KACA,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,CACnE,CAAA;gBAED,IAAI,CAAC,EAAE,EAAE;oBACP,OAAM;AACP,iBAAA;AAED,gBAAA,MAAM,OAAO,GAAG,CAAG,EAAA,IAAI,CAAG,EAAA,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA,EAC1C,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,GAAG,GAClC,CAAK,EAAA,EAAA,SAAS,EAAE,CAAA;;;;;;AAOhB,gBAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAI;AAC7B,oBAAA,MAAM,UAAU,GAAG,EAAE,CAAC,SAAS,EAAqB,CAAA;AACpD,oBAAA,UAAU,CAAC,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,CAAA;oBAChD,MAAM,WAAW,GAAG,MAAK;wBACvB,EAAE,CAAC,MAAM,EAAE,CAAA;AACX,wBAAA,OAAO,CAAC,KAAK,CAAC,2BAA2B,SAAS,CAAA,CAAE,CAAC,CAAA;AACrD,wBAAA,OAAO,EAAE,CAAA;AACX,qBAAC,CAAA;AACD,oBAAA,UAAU,CAAC,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;AAChD,oBAAA,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAA;AACjD,oBAAA,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;AACxB,oBAAA,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;AACtB,iBAAC,CAAC,CAAA;aACH,CAAC,CACH,CAAA;AACD,YAAA,eAAe,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAA;YAC5C,MAAK;QACP,KAAK,QAAQ,EAAE;YACb,eAAe,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;YAC5C,MAAK;AACN,SAAA;AACD,QAAA,KAAK,aAAa;AAChB,YAAA,eAAe,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAA;AACjD,YAAA,IAAI,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;;;gBAGlD,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;AAC7C,gBAAA,MAAM,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;gBAChD,IACE,QAAQ,KAAK,WAAW;oBACxB,OAAO,CAAC,IAAI,KAAK,aAAa;AAC9B,qBAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,QAAQ,GAAG,YAAY,KAAK,WAAW,CAAC,EACnE;AACA,oBAAA,UAAU,EAAE,CAAA;AACb,iBAAA;gBACD,OAAM;AACP,aAAA;AAAM,iBAAA;AACL,gBAAA,UAAU,EAAE,CAAA;AACb,aAAA;YACD,MAAK;AACP,QAAA,KAAK,OAAO;AACV,YAAA,eAAe,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAA;AAC5C,YAAA,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;YACnC,MAAK;QACP,KAAK,OAAO,EAAE;AACZ,YAAA,eAAe,CAAC,YAAY,EAAE,OAAO,CAAC,CAAA;AACtC,YAAA,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAA;AACvB,YAAA,IAAI,aAAa,EAAE;gBACjB,kBAAkB,CAAC,GAAG,CAAC,CAAA;AACxB,aAAA;AAAM,iBAAA;AACL,gBAAA,OAAO,CAAC,KAAK,CACX,CAAA,8BAAA,EAAiC,GAAG,CAAC,OAAO,CAAA,EAAA,EAAK,GAAG,CAAC,KAAK,CAAA,CAAE,CAC7D,CAAA;AACF,aAAA;YACD,MAAK;AACN,SAAA;AACD,QAAA,SAAS;YACP,MAAM,KAAK,GAAU,OAAO,CAAA;AAC5B,YAAA,OAAO,KAAK,CAAA;AACb,SAAA;AACF,KAAA;AACH,CAAC;AAMD,SAAS,eAAe,CAAC,KAAa,EAAE,IAAS,EAAA;AAC/C,IAAA,SAAS,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;AACxC,CAAC;AAED,MAAM,aAAa,GAAG,sBAAsB,CAAA;AAE5C,SAAS,kBAAkB,CAAC,GAAwB,EAAA;AAClD,IAAA,iBAAiB,EAAE,CAAA;IACnB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,YAAY,CAAC,GAAG,CAAC,CAAC,CAAA;AAClD,CAAC;AAED,SAAS,iBAAiB,GAAA;AACxB,IAAA,QAAQ,CAAC,gBAAgB,CAAe,SAAS,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;AAC9E,CAAC;AAED,SAAS,eAAe,GAAA;IACtB,OAAO,QAAQ,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAA;AACpD,CAAC;AAED,eAAe,qBAAqB,CAClC,cAAsB,EACtB,WAAmB,EACnB,EAAE,GAAG,IAAI,EAAA;AAET,IAAA,MAAM,gBAAgB,GAAG,cAAc,KAAK,KAAK,GAAG,OAAO,GAAG,MAAM,CAAA;AAEpE,IAAA,MAAM,IAAI,GAAG,YAAW;;;;QAItB,IAAI;AACF,YAAA,MAAM,KAAK,CAAC,CAAA,EAAG,gBAAgB,CAAM,GAAA,EAAA,WAAW,EAAE,EAAE;AAClD,gBAAA,IAAI,EAAE,SAAS;AACf,gBAAA,OAAO,EAAE;;;AAGP,oBAAA,MAAM,EAAE,kBAAkB;AAC3B,iBAAA;AACF,aAAA,CAAC,CAAA;AACF,YAAA,OAAO,IAAI,CAAA;AACZ,SAAA;AAAC,QAAA,MAAM,GAAE;AACV,QAAA,OAAO,KAAK,CAAA;AACd,KAAC,CAAA;IAED,IAAI,MAAM,IAAI,EAAE,EAAE;QAChB,OAAM;AACP,KAAA;AACD,IAAA,MAAM,IAAI,CAAC,EAAE,CAAC,CAAA;;AAGd,IAAA,OAAO,IAAI,EAAE;AACX,QAAA,IAAI,QAAQ,CAAC,eAAe,KAAK,SAAS,EAAE;YAC1C,IAAI,MAAM,IAAI,EAAE,EAAE;gBAChB,MAAK;AACN,aAAA;AACD,YAAA,MAAM,IAAI,CAAC,EAAE,CAAC,CAAA;AACf,SAAA;AAAM,aAAA;YACL,MAAM,iBAAiB,EAAE,CAAA;AAC1B,SAAA;AACF,KAAA;AACH,CAAC;AAED,SAAS,IAAI,CAAC,EAAU,EAAA;AACtB,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAA;AAC1D,CAAC;AAED,SAAS,iBAAiB,GAAA;AACxB,IAAA,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,KAAI;AACnC,QAAA,MAAM,QAAQ,GAAG,YAAW;AAC1B,YAAA,IAAI,QAAQ,CAAC,eAAe,KAAK,SAAS,EAAE;AAC1C,gBAAA,OAAO,EAAE,CAAA;AACT,gBAAA,QAAQ,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAA;AAC3D,aAAA;AACH,SAAC,CAAA;AACD,QAAA,QAAQ,CAAC,gBAAgB,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAA;AACzD,KAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,SAAS,GAAG,IAAI,GAAG,EAA4B,CAAA;AAErD;AACA;AACA,IAAI,UAAU,IAAI,UAAU,EAAE;IAC5B,QAAQ;SACL,gBAAgB,CAAmB,yBAAyB,CAAC;AAC7D,SAAA,OAAO,CAAC,CAAC,EAAE,KAAI;AACd,QAAA,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,YAAY,CAAC,kBAAkB,CAAE,EAAE,EAAE,CAAC,CAAA;AACzD,KAAC,CAAC,CAAA;AACL,CAAA;AAED;AACA;AACA,IAAI,iBAA+C,CAAA;AAEnC,SAAA,WAAW,CAAC,EAAU,EAAE,OAAe,EAAA;IACrD,IAAI,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC7B,IAAI,CAAC,KAAK,EAAE;AACV,QAAA,KAAK,GAAG,QAAQ,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;AACvC,QAAA,KAAK,CAAC,YAAY,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;AACtC,QAAA,KAAK,CAAC,YAAY,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAA;AAC1C,QAAA,KAAK,CAAC,WAAW,GAAG,OAAO,CAAA;QAE3B,IAAI,CAAC,iBAAiB,EAAE;AACtB,YAAA,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;;;YAIhC,UAAU,CAAC,MAAK;gBACd,iBAAiB,GAAG,SAAS,CAAA;aAC9B,EAAE,CAAC,CAAC,CAAA;AACN,SAAA;AAAM,aAAA;AACL,YAAA,iBAAiB,CAAC,qBAAqB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;AAC3D,SAAA;QACD,iBAAiB,GAAG,KAAK,CAAA;AAC1B,KAAA;AAAM,SAAA;AACL,QAAA,KAAK,CAAC,WAAW,GAAG,OAAO,CAAA;AAC5B,KAAA;AACD,IAAA,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAEK,SAAU,WAAW,CAAC,EAAU,EAAA;IACpC,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;AAC/B,IAAA,IAAI,KAAK,EAAE;AACT,QAAA,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;AAChC,QAAA,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;AACrB,KAAA;AACH,CAAC;AAEK,SAAU,gBAAgB,CAAC,SAAiB,EAAA;AAChD,IAAA,OAAO,IAAI,UAAU,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AAC7C,CAAC;AAED;;AAEG;AACa,SAAA,WAAW,CAAC,GAAW,EAAE,aAAqB,EAAA;;AAE5D,IAAA,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;AACpC,QAAA,OAAO,GAAG,CAAA;AACX,KAAA;;IAGD,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;AAC3C,IAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAA;IAE1D,OAAO,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,aAAa,CAAA,EAAG,MAAM,GAAG,CAAG,CAAA,CAAA,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,CAAA,EACvE,IAAI,IAAI,EACV,CAAA,CAAE,CAAA;AACJ;;;;","x_google_ignoreList":[0,1,2]} \ No newline at end of file diff --git a/web/node_modules/vite/dist/client/env.mjs b/web/node_modules/vite/dist/client/env.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1b3a7d26e9ea51f99199160b6a522958f41e9c55 --- /dev/null +++ b/web/node_modules/vite/dist/client/env.mjs @@ -0,0 +1,30 @@ +const context = (() => { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else { + return Function('return this')(); + } +})(); +// assign defines +const defines = __DEFINES__; +Object.keys(defines).forEach((key) => { + const segments = key.split('.'); + let target = context; + for (let i = 0; i < segments.length; i++) { + const segment = segments[i]; + if (i === segments.length - 1) { + target[segment] = defines[key]; + } + else { + target = target[segment] || (target[segment] = {}); + } + } +}); +//# sourceMappingURL=env.mjs.map diff --git a/web/node_modules/vite/dist/client/env.mjs.map b/web/node_modules/vite/dist/client/env.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..95e027da8adf02ea628b42e7d7facd6a1a4897f0 --- /dev/null +++ b/web/node_modules/vite/dist/client/env.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"env.mjs","sources":["env.ts"],"sourcesContent":["declare const __MODE__: string\ndeclare const __DEFINES__: Record\n\nconst context = (() => {\n if (typeof globalThis !== 'undefined') {\n return globalThis\n } else if (typeof self !== 'undefined') {\n return self\n } else if (typeof window !== 'undefined') {\n return window\n } else {\n return Function('return this')()\n }\n})()\n\n// assign defines\nconst defines = __DEFINES__\nObject.keys(defines).forEach((key) => {\n const segments = key.split('.')\n let target = context\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n if (i === segments.length - 1) {\n target[segment] = defines[key]\n } else {\n target = target[segment] || (target[segment] = {})\n }\n }\n})\n"],"names":[],"mappings":"AAGA,MAAM,OAAO,GAAG,CAAC,MAAK;AACpB,IAAA,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;AACrC,QAAA,OAAO,UAAU,CAAA;AAClB,KAAA;AAAM,SAAA,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;AACtC,QAAA,OAAO,IAAI,CAAA;AACZ,KAAA;AAAM,SAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACxC,QAAA,OAAO,MAAM,CAAA;AACd,KAAA;AAAM,SAAA;AACL,QAAA,OAAO,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAA;AACjC,KAAA;AACH,CAAC,GAAG,CAAA;AAEJ;AACA,MAAM,OAAO,GAAG,WAAW,CAAA;AAC3B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,KAAI;IACnC,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,MAAM,GAAG,OAAO,CAAA;AACpB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;AAC3B,QAAA,IAAI,CAAC,KAAK,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YAC7B,MAAM,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;AAC/B,SAAA;AAAM,aAAA;AACL,YAAA,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;AACnD,SAAA;AACF,KAAA;AACH,CAAC,CAAC","x_google_ignoreList":[0]} \ No newline at end of file diff --git a/web/node_modules/vite/dist/node-cjs/publicUtils.cjs b/web/node_modules/vite/dist/node-cjs/publicUtils.cjs new file mode 100644 index 0000000000000000000000000000000000000000..e744a157c54dda106c27c5ca41737bcabc36e396 --- /dev/null +++ b/web/node_modules/vite/dist/node-cjs/publicUtils.cjs @@ -0,0 +1,6187 @@ +'use strict'; + +var path$3 = require('node:path'); +var node_url = require('node:url'); +var fs$1 = require('node:fs'); +var esbuild = require('esbuild'); +var os$1 = require('node:os'); +var node_module = require('node:module'); +var require$$0 = require('tty'); +var require$$1 = require('util'); +var require$$0$1 = require('path'); +var require$$0$2 = require('crypto'); +var fs$2 = require('fs'); +var readline = require('node:readline'); +var require$$2 = require('os'); + +var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +const { version: version$2 } = JSON.parse(fs$1.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString()); +const VERSION = version$2; +/** + * Prefix for resolved fs paths, since windows paths may not be valid as URLs. + */ +const FS_PREFIX = `/@fs/`; +const VITE_PACKAGE_DIR = path$3.resolve( +// import.meta.url is `dist/node/constants.js` after bundle +node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..'); +const CLIENT_ENTRY = path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs'); +path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs'); +path$3.dirname(CLIENT_ENTRY); + +const comma = ','.charCodeAt(0); +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; +} +// Provide a fallback for older environments. +const 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; + }, + }; +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +// Matches the scheme of a URL, eg "http://" +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var picocolors = {exports: {}}; + +let tty = require$$0; + +let isColorSupported = + !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && + ("FORCE_COLOR" in process.env || + process.argv.includes("--color") || + process.platform === "win32" || + (tty.isatty(1) && process.env.TERM !== "dumb") || + "CI" in process.env); + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input; + let 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 start = string.substring(0, index) + replace; + let end = string.substring(index + close.length); + let nextIndex = end.indexOf(close); + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +}; + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}); + +picocolors.exports = createColors(); +picocolors.exports.createColors = createColors; + +var picocolorsExports = picocolors.exports; +var colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); + +var src = {exports: {}}; + +var node = {exports: {}}; + +/** + * Helpers. + */ + +var ms; +var hasRequiredMs; + +function requireMs () { + if (hasRequiredMs) return ms; + hasRequiredMs = 1; + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + return ms; +} + +var common; +var hasRequiredCommon; + +function requireCommon () { + if (hasRequiredCommon) return common; + hasRequiredCommon = 1; + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs(); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + common = setup; + return common; +} + +/** + * Module dependencies. + */ + +var hasRequiredNode; + +function requireNode () { + if (hasRequiredNode) return node.exports; + hasRequiredNode = 1; + (function (module, exports) { + const tty = require$$0; + const util = require$$1; + + /** + * This is the Node.js implementation of `debug()`. + */ + + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' + ); + + /** + * Colors. + */ + + exports.colors = [6, 2, 3, 4, 5, 1]; + + try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. + } + + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; + }, {}); + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + + function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); + } + + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } + } + + function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; + } + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); + } + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + function load() { + return process.env.DEBUG; + } + + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %o to `util.inspect()`, all on a single line. + */ + + formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); + }; + + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + } (node, node.exports)); + return node.exports; +} + +var browser$1 = {exports: {}}; + +/* eslint-env browser */ + +var hasRequiredBrowser; + +function requireBrowser () { + if (hasRequiredBrowser) return browser$1.exports; + hasRequiredBrowser = 1; + (function (module, exports) { + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + } (browser$1, browser$1.exports)); + return browser$1.exports; +} + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + src.exports = requireBrowser(); +} else { + src.exports = requireNode(); +} + +var srcExports = src.exports; +var debug$2 = /*@__PURE__*/getDefaultExportFromCjs(srcExports); + +var utils$3 = {}; + +const path$2 = require$$0$1; +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$1 = { + 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' +}; + +var constants$2 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + + // 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$2.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; + } +}; + +(function (exports) { + + const path = require$$0$1; + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$2; + + 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; + }; +} (utils$3)); + +const utils$2 = utils$3; +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 /* ] */ +} = constants$2; + +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$1 = (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$2.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$2.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; +}; + +var scan_1 = scan$1; + +const constants$1 = constants$2; +const utils$1 = utils$3; + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$1; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.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$2 = (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$1.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants$1.globChars(win32); + const EXTGLOB_CHARS = constants$1.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$1.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$2(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$1.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$1.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$1.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$1.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$1.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$1.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$1.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$1.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$2.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$1.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$1.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$1.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$2; + +const path$1 = require$$0$1; +const scan = scan_1; +const parse$1 = parse_1$1; +const utils = utils$3; +const constants = constants$2; +const isObject$2 = 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$1 = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch$1(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$2(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$1.compileRe(glob, options) + : picomatch$1.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$1(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch$1.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$1.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$1.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$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options); + return regex.test(path$1.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$1.isMatch = (str, patterns, options) => picomatch$1(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$1.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options)); + return parse$1(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$1.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$1.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$1.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$1.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$1.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse$1(input, options); + } + + return picomatch$1.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$1.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$1.constants = constants; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch$1; + +var picomatch = picomatch_1; + +var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch); + +// Helper since Typescript can't detect readonly arrays with Array.isArray +function isArray(arg) { + return Array.isArray(arg); +} +function ensureArray(thing) { + if (isArray(thing)) + return thing; + if (thing == null) + return []; + return [thing]; +} + +const normalizePath$1 = function normalizePath(filename) { + return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep); +}; + +function getMatcherString(id, resolutionBase) { + if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) { + return normalizePath$1(id); + } + // resolve('') is valid and will default to process.cwd() + const basePath = normalizePath$1(require$$0$1.resolve(resolutionBase || '')) + // escape all possible (posix + win) path characters that might interfere with regex + .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); + // Note that we use posix.join because: + // 1. the basePath has been normalized to use / + // 2. the incoming glob (id) matcher, also uses / + // otherwise Node will force backslash (\) on windows + return require$$0$1.posix.join(basePath, normalizePath$1(id)); +} +const createFilter$1 = function createFilter(include, exclude, options) { + const resolutionBase = options && options.resolve; + const getMatcher = (id) => id instanceof RegExp + ? id + : { + test: (what) => { + // this refactor is a tad overly verbose but makes for easy debugging + const pattern = getMatcherString(id, resolutionBase); + const fn = pm(pattern, { dot: true }); + const result = fn(what); + return result; + } + }; + const includeMatchers = ensureArray(include).map(getMatcher); + const excludeMatchers = ensureArray(exclude).map(getMatcher); + return function result(id) { + if (typeof id !== 'string') + return false; + if (/\0/.test(id)) + return false; + const pathId = normalizePath$1(id); + for (let i = 0; i < excludeMatchers.length; ++i) { + const matcher = excludeMatchers[i]; + if (matcher.test(pathId)) + return false; + } + for (let i = 0; i < includeMatchers.length; ++i) { + const matcher = includeMatchers[i]; + if (matcher.test(pathId)) + return true; + } + return !includeMatchers.length; + }; +}; + +const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; +const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; +const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' ')); +forbiddenIdentifiers.add(''); + +if (process.versions.pnp) { + try { + node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))('pnpapi'); + } + catch { } +} + +const createFilter = createFilter$1; +const windowsSlashRE = /\\/g; +function slash(p) { + return p.replace(windowsSlashRE, '/'); +} +// Some runtimes like Bun injects namespaced modules here, which is not a node builtin +node_module.builtinModules.filter((id) => !id.includes(':')); +function isInNodeModules(id) { + return id.includes('node_modules'); +} +// TODO: use import() +const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))); +function resolveDependencyVersion(dep, pkgRelativePath = '../../package.json') { + const pkgPath = path$3.resolve(_require.resolve(dep), pkgRelativePath); + return JSON.parse(fs$1.readFileSync(pkgPath, 'utf-8')).version; +} +const rollupVersion = resolveDependencyVersion('rollup'); +// set in bin/vite.js +const filter = process.env.VITE_DEBUG_FILTER; +const DEBUG = process.env.DEBUG; +function createDebugger(namespace, options = {}) { + const log = debug$2(namespace); + const { onlyWhenFocused } = options; + let enabled = log.enabled; + if (enabled && onlyWhenFocused) { + const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; + enabled = !!DEBUG?.includes(ns); + } + if (enabled) { + return (...args) => { + if (!filter || args.some((a) => a?.includes?.(filter))) { + log(...args); + } + }; + } +} +function testCaseInsensitiveFS() { + if (!CLIENT_ENTRY.endsWith('client.mjs')) { + throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); + } + if (!fs$1.existsSync(CLIENT_ENTRY)) { + throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + + CLIENT_ENTRY); + } + return fs$1.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')); +} +const isCaseInsensitiveFS = testCaseInsensitiveFS(); +const isWindows = os$1.platform() === 'win32'; +const VOLUME_RE = /^[A-Z]:/i; +function normalizePath(id) { + return path$3.posix.normalize(isWindows ? slash(id) : id); +} +function fsPathFromId(id) { + const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); + return fsPath[0] === '/' || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`; +} +function fsPathFromUrl(url) { + return fsPathFromId(cleanUrl(url)); +} +function withTrailingSlash(path) { + if (path[path.length - 1] !== '/') { + return `${path}/`; + } + return path; +} +/** + * Check if dir is a parent of file + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param dir - normalized absolute path + * @param file - normalized absolute path + * @returns true if dir is a parent of file + */ +function isParentDirectory(dir, file) { + dir = withTrailingSlash(dir); + return (file.startsWith(dir) || + (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))); +} +/** + * Check if 2 file name are identical + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param file1 - normalized absolute path + * @param file2 - normalized absolute path + * @returns true if both files url are identical + */ +function isSameFileUri(file1, file2) { + return (file1 === file2 || + (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase())); +} +const postfixRE = /[?#].*$/; +function cleanUrl(url) { + return url.replace(postfixRE, ''); +} +const trailingSeparatorRE = /[?&]$/; +const timestampRE = /\bt=\d{13}&?\b/; +function removeTimestampQuery(url) { + return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); +} +function isObject$1(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +function tryStatSync(file) { + try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist + return fs$1.statSync(file, { throwIfNoEntry: false }); + } + catch { + // Ignore errors + } +} +function isFileReadable(filename) { + if (!tryStatSync(filename)) { + return false; + } + try { + // Check if current process has read permission to the file + fs$1.accessSync(filename, fs$1.constants.R_OK); + return true; + } + catch { + return false; + } +} +function arraify(target) { + return Array.isArray(target) ? target : [target]; +} +path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))); +function backwardCompatibleWorkerPlugins(plugins) { + if (Array.isArray(plugins)) { + return plugins; + } + if (typeof plugins === 'function') { + return plugins(); + } + return []; +} +function mergeConfigRecursively(defaults, overrides, rootPath) { + const merged = { ...defaults }; + for (const key in overrides) { + const value = overrides[key]; + if (value == null) { + continue; + } + const existing = merged[key]; + if (existing == null) { + merged[key] = value; + continue; + } + // fields that require special handling + if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) { + merged[key] = mergeAlias(existing, value); + continue; + } + else if (key === 'assetsInclude' && rootPath === '') { + merged[key] = [].concat(existing, value); + continue; + } + else if (key === 'noExternal' && + rootPath === 'ssr' && + (existing === true || value === true)) { + merged[key] = true; + continue; + } + else if (key === 'plugins' && rootPath === 'worker') { + merged[key] = () => [ + ...backwardCompatibleWorkerPlugins(existing), + ...backwardCompatibleWorkerPlugins(value), + ]; + continue; + } + if (Array.isArray(existing) || Array.isArray(value)) { + merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])]; + continue; + } + if (isObject$1(existing) && isObject$1(value)) { + merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key); + continue; + } + merged[key] = value; + } + return merged; +} +function mergeConfig(defaults, overrides, isRoot = true) { + if (typeof defaults === 'function' || typeof overrides === 'function') { + throw new Error(`Cannot merge config in form of callback`); + } + return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); +} +function mergeAlias(a, b) { + if (!a) + return b; + if (!b) + return a; + if (isObject$1(a) && isObject$1(b)) { + return { ...a, ...b }; + } + // the order is flipped because the alias is resolved from top-down, + // where the later should have higher priority + return [...normalizeAlias(b), ...normalizeAlias(a)]; +} +function normalizeAlias(o = []) { + return Array.isArray(o) + ? o.map(normalizeSingleAlias) + : Object.keys(o).map((find) => normalizeSingleAlias({ + find, + replacement: o[find], + })); +} +// https://github.com/vitejs/vite/issues/1363 +// work around https://github.com/rollup/plugins/issues/759 +function normalizeSingleAlias({ find, replacement, customResolver, }) { + if (typeof find === 'string' && + find[find.length - 1] === '/' && + replacement[replacement.length - 1] === '/') { + find = find.slice(0, find.length - 1); + replacement = replacement.slice(0, replacement.length - 1); + } + const alias = { + find, + replacement, + }; + if (customResolver) { + alias.customResolver = customResolver; + } + return alias; +} + +// This file will be built for both ESM and CJS. Avoid relying on other modules as possible. +// copy from constants.ts +const CSS_LANGS_RE = +// eslint-disable-next-line regexp/no-unused-capturing-group +/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; +const isCSSRequest = (request) => CSS_LANGS_RE.test(request); +// Use splitVendorChunkPlugin() to get the same manualChunks strategy as Vite 2.7 +// We don't recommend using this strategy as a general solution moving forward +// splitVendorChunk is a simple index/vendor strategy that was used in Vite +// until v2.8. It is exposed to let people continue to use it in case it was +// working well for their setups. +// The cache needs to be reset on buildStart for watch mode to work correctly +// Don't use this manualChunks strategy for ssr, lib mode, and 'umd' or 'iife' +class SplitVendorChunkCache { + cache; + constructor() { + this.cache = new Map(); + } + reset() { + this.cache = new Map(); + } +} +function splitVendorChunk(options = {}) { + const cache = options.cache ?? new SplitVendorChunkCache(); + return (id, { getModuleInfo }) => { + if (isInNodeModules(id) && + !isCSSRequest(id) && + staticImportedByEntry(id, getModuleInfo, cache.cache)) { + return 'vendor'; + } + }; +} +function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) { + if (cache.has(id)) { + return cache.get(id); + } + if (importStack.includes(id)) { + // circular deps! + cache.set(id, false); + return false; + } + const mod = getModuleInfo(id); + if (!mod) { + cache.set(id, false); + return false; + } + if (mod.isEntry) { + cache.set(id, true); + return true; + } + const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id))); + cache.set(id, someImporterIs); + return someImporterIs; +} +function splitVendorChunkPlugin() { + const caches = []; + function createSplitVendorChunk(output, config) { + const cache = new SplitVendorChunkCache(); + caches.push(cache); + const build = config.build ?? {}; + const format = output?.format; + if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') { + return splitVendorChunk({ cache }); + } + } + return { + name: 'vite:split-vendor-chunk', + config(config) { + let outputs = config?.build?.rollupOptions?.output; + if (outputs) { + outputs = arraify(outputs); + for (const output of outputs) { + const viteManualChunks = createSplitVendorChunk(output, config); + if (viteManualChunks) { + if (output.manualChunks) { + if (typeof output.manualChunks === 'function') { + const userManualChunks = output.manualChunks; + output.manualChunks = (id, api) => { + return userManualChunks(id, api) ?? viteManualChunks(id, api); + }; + } + else { + // else, leave the object form of manualChunks untouched, as + // we can't safely replicate rollup handling. + // eslint-disable-next-line no-console + console.warn("(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead."); + } + } + else { + output.manualChunks = viteManualChunks; + } + } + } + } + else { + return { + build: { + rollupOptions: { + output: { + manualChunks: createSplitVendorChunk({}, config), + }, + }, + }, + }; + } + }, + buildStart() { + caches.forEach((cache) => cache.reset()); + }, + }; +} + +var convertSourceMap$1 = {}; + +(function (exports) { + + Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + } + }); + + + Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + } + }); + + var decodeBase64; + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + decodeBase64 = decodeBase64WithBufferFrom; + } else { + decodeBase64 = decodeBase64WithNewBuffer; + } + } else { + decodeBase64 = decodeBase64WithAtob; + } + + function decodeBase64WithBufferFrom(base64) { + return Buffer.from(base64, 'base64').toString(); + } + + function decodeBase64WithNewBuffer(base64) { + if (typeof value === 'number') { + throw new TypeError('The value to decode must not be of type number.'); + } + return new Buffer(base64, 'base64').toString(); + } + + function decodeBase64WithAtob(base64) { + return decodeURIComponent(escape(atob(base64))); + } + + function stripComment(sm) { + return sm.split(',').pop(); + } + + function readFromFileMap(sm, read) { + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + + try { + var sm = read(filename); + if (sm != null && typeof sm.catch === 'function') { + return sm.catch(throwError); + } else { + return sm; + } + } catch (e) { + throwError(e); + } + + function throwError(e) { + throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + } + } + + function Converter (sm, opts) { + opts = opts || {}; + + if (opts.hasComment) { + sm = stripComment(sm); + } + + if (opts.encoding === 'base64') { + sm = decodeBase64(sm); + } else if (opts.encoding === 'uri') { + sm = decodeURIComponent(sm); + } + + if (opts.isJSON || opts.encoding) { + sm = JSON.parse(sm); + } + + this.sourcemap = sm; + } + + Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); + }; + + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + Converter.prototype.toBase64 = encodeBase64WithBufferFrom; + } else { + Converter.prototype.toBase64 = encodeBase64WithNewBuffer; + } + } else { + Converter.prototype.toBase64 = encodeBase64WithBtoa; + } + + function encodeBase64WithBufferFrom() { + var json = this.toJSON(); + return Buffer.from(json, 'utf8').toString('base64'); + } + + function encodeBase64WithNewBuffer() { + var json = this.toJSON(); + if (typeof json === 'number') { + throw new TypeError('The json to encode must not be of type number.'); + } + return new Buffer(json, 'utf8').toString('base64'); + } + + function encodeBase64WithBtoa() { + var json = this.toJSON(); + return btoa(unescape(encodeURIComponent(json))); + } + + Converter.prototype.toURI = function () { + var json = this.toJSON(); + return encodeURIComponent(json); + }; + + Converter.prototype.toComment = function (options) { + var encoding, content, data; + if (options != null && options.encoding === 'uri') { + encoding = ''; + content = this.toURI(); + } else { + encoding = ';base64'; + content = this.toBase64(); + } + data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; + return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; + + // returns copy instead of original + Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); + }; + + Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); + }; + + Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; + }; + + Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; + }; + + exports.fromObject = function (obj) { + return new Converter(obj); + }; + + exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); + }; + + exports.fromURI = function (uri) { + return new Converter(uri, { encoding: 'uri' }); + }; + + exports.fromBase64 = function (base64) { + return new Converter(base64, { encoding: 'base64' }); + }; + + exports.fromComment = function (comment) { + var m, encoding; + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + m = exports.commentRegex.exec(comment); + encoding = m && m[4] || 'uri'; + return new Converter(comment, { encoding: encoding, hasComment: true }); + }; + + function makeConverter(sm) { + return new Converter(sm, { isJSON: true }); + } + + exports.fromMapFileComment = function (comment, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileComment`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + + var sm = readFromFileMap(comment, read); + if (sm != null && typeof sm.then === 'function') { + return sm.then(makeConverter); + } else { + return makeConverter(sm); + } + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromMapFileSource = function (content, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileSource`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), read) : null; + }; + + exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); + }; + + exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); + }; + + exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; +} (convertSourceMap$1)); + +var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1); + +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +var etag_1 = etag; + +/** + * Module dependencies. + * @private + */ + +var crypto$1 = require$$0$2; +var Stats = fs$2.Stats; + +/** + * Module variables. + * @private + */ + +var toString$1 = Object.prototype.toString; + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto$1 + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27); + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length; + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity); + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats; + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity); + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString$1.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString$1.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16); + var size = stat.size.toString(16); + + return '"' + size + '-' + mtime + '"' +} + +var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1); + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + reset() { + this.intro = ''; + this.outro = ''; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa$1 = /*#__PURE__*/ getBtoa(); + +class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); + } +} + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + reset(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.reset(); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +const debug$1 = createDebugger('vite:sourcemap', { + onlyWhenFocused: true, +}); +function genSourceMapUrl(map) { + if (typeof map !== 'string') { + map = JSON.stringify(map); + } + return `data:application/json;base64,${Buffer.from(map).toString('base64')}`; +} +function getCodeWithSourcemap(type, code, map) { + if (debug$1) { + code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; + } + if (type === 'js') { + code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; + } + else if (type === 'css') { + code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; + } + return code; +} + +const debug = createDebugger('vite:send', { + onlyWhenFocused: true, +}); +const alias = { + js: 'text/javascript', + css: 'text/css', + html: 'text/html', + json: 'application/json', +}; +function send(req, res, content, type, options) { + const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options; + if (res.writableEnded) { + return; + } + if (req.headers['if-none-match'] === etag) { + res.statusCode = 304; + res.end(); + return; + } + res.setHeader('Content-Type', alias[type] || type); + res.setHeader('Cache-Control', cacheControl); + res.setHeader('Etag', etag); + if (headers) { + for (const name in headers) { + res.setHeader(name, headers[name]); + } + } + // inject source map reference + if (map && 'version' in map && map.mappings) { + if (type === 'js' || type === 'css') { + content = getCodeWithSourcemap(type, content.toString(), map); + } + } + // inject fallback sourcemap for js for improved debugging + // https://github.com/vitejs/vite/pull/13514#issuecomment-1592431496 + else if (type === 'js' && (!map || map.mappings !== '')) { + const code = content.toString(); + // if the code has existing inline sourcemap, assume it's correct and skip + if (convertSourceMap.mapFileCommentRegex.test(code)) { + debug?.(`Skipped injecting fallback sourcemap for ${req.url}`); + } + else { + const urlWithoutTimestamp = removeTimestampQuery(req.url); + const ms = new MagicString(code); + content = getCodeWithSourcemap(type, code, ms.generateMap({ + source: path$3.basename(urlWithoutTimestamp), + hires: 'boundary', + includeContent: true, + })); + } + } + res.statusCode = 200; + res.end(content); + return; +} + +/* eslint no-console: 0 */ +const LogLevels = { + silent: 0, + error: 1, + warn: 2, + info: 3, +}; +let lastType; +let lastMsg; +let sameCount = 0; +function clearScreen() { + const repeatCount = process.stdout.rows - 2; + const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; + console.log(blank); + readline.cursorTo(process.stdout, 0, 0); + readline.clearScreenDown(process.stdout); +} +// Only initialize the timeFormatter when the timestamp option is used, and +// reuse it across all loggers +let timeFormatter; +function getTimeFormatter() { + timeFormatter ??= new Intl.DateTimeFormat(undefined, { + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + }); + return timeFormatter; +} +function createLogger(level = 'info', options = {}) { + if (options.customLogger) { + return options.customLogger; + } + const loggedErrors = new WeakSet(); + const { prefix = '[vite]', allowClearScreen = true } = options; + const thresh = LogLevels[level]; + const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; + const clear = canClearScreen ? clearScreen : () => { }; + function format(type, msg, options = {}) { + if (options.timestamp) { + const tag = type === 'info' + ? colors.cyan(colors.bold(prefix)) + : type === 'warn' + ? colors.yellow(colors.bold(prefix)) + : colors.red(colors.bold(prefix)); + return `${colors.dim(getTimeFormatter().format(new Date()))} ${tag} ${msg}`; + } + else { + return msg; + } + } + function output(type, msg, options = {}) { + if (thresh >= LogLevels[type]) { + const method = type === 'info' ? 'log' : type; + if (options.error) { + loggedErrors.add(options.error); + } + if (canClearScreen) { + if (type === lastType && msg === lastMsg) { + sameCount++; + clear(); + console[method](format(type, msg, options), colors.yellow(`(x${sameCount + 1})`)); + } + else { + sameCount = 0; + lastMsg = msg; + lastType = type; + if (options.clear) { + clear(); + } + console[method](format(type, msg, options)); + } + } + else { + console[method](format(type, msg, options)); + } + } + } + const warnedMessages = new Set(); + const logger = { + hasWarned: false, + info(msg, opts) { + output('info', msg, opts); + }, + warn(msg, opts) { + logger.hasWarned = true; + output('warn', msg, opts); + }, + warnOnce(msg, opts) { + if (warnedMessages.has(msg)) + return; + logger.hasWarned = true; + output('warn', msg, opts); + warnedMessages.add(msg); + }, + error(msg, opts) { + logger.hasWarned = true; + output('error', msg, opts); + }, + clearScreen(type) { + if (thresh >= LogLevels[type]) { + clear(); + } + }, + hasErrorLogged(error) { + return loggedErrors.has(error); + }, + }; + return logger; +} + +// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 +const ROOT_FILES = [ + // '.git', + // https://pnpm.io/workspaces/ + 'pnpm-workspace.yaml', + // https://rushjs.io/pages/advanced/config_files/ + // 'rush.json', + // https://nx.dev/latest/react/getting-started/nx-setup + // 'workspace.json', + // 'nx.json', + // https://github.com/lerna/lerna#lernajson + 'lerna.json', +]; +// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces +// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it +function hasWorkspacePackageJSON(root) { + const path = path$3.join(root, 'package.json'); + if (!isFileReadable(path)) { + return false; + } + try { + const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {}; + return !!content.workspaces; + } + catch { + return false; + } +} +function hasRootFile(root) { + return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file))); +} +function hasPackageJSON(root) { + const path = path$3.join(root, 'package.json'); + return fs$1.existsSync(path); +} +/** + * Search up for the nearest `package.json` + */ +function searchForPackageRoot(current, root = current) { + if (hasPackageJSON(current)) + return current; + const dir = path$3.dirname(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForPackageRoot(dir, root); +} +/** + * Search up for the nearest workspace root + */ +function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { + if (hasRootFile(current)) + return current; + if (hasWorkspacePackageJSON(current)) + return current; + const dir = path$3.dirname(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForWorkspaceRoot(dir, root); +} + +/** + * Check if the url is allowed to be served, via the `server.fs` config. + */ +function isFileServingAllowed(url, server) { + if (!server.config.server.fs.strict) + return true; + const file = fsPathFromUrl(url); + if (server._fsDenyGlob(file)) + return false; + if (server.moduleGraph.safeModulesPath.has(file)) + return true; + if (server.config.server.fs.allow.some((uri) => isSameFileUri(uri, file) || isParentDirectory(uri, file))) + return true; + return false; +} + +var main$1 = {exports: {}}; + +var name = "dotenv"; +var version$1 = "16.4.4"; +var description = "Loads environment variables from .env file"; +var main = "lib/main.js"; +var types = "lib/main.d.ts"; +var exports$1 = { + ".": { + types: "./lib/main.d.ts", + require: "./lib/main.js", + "default": "./lib/main.js" + }, + "./config": "./config.js", + "./config.js": "./config.js", + "./lib/env-options": "./lib/env-options.js", + "./lib/env-options.js": "./lib/env-options.js", + "./lib/cli-options": "./lib/cli-options.js", + "./lib/cli-options.js": "./lib/cli-options.js", + "./package.json": "./package.json" +}; +var scripts = { + "dts-check": "tsc --project tests/types/tsconfig.json", + lint: "standard", + "lint-readme": "standard-markdown", + pretest: "npm run lint && npm run dts-check", + test: "tap tests/*.js --100 -Rspec", + "test:coverage": "tap --coverage-report=lcov", + prerelease: "npm test", + release: "standard-version" +}; +var repository = { + type: "git", + url: "git://github.com/motdotla/dotenv.git" +}; +var funding = "https://dotenvx.com"; +var keywords = [ + "dotenv", + "env", + ".env", + "environment", + "variables", + "config", + "settings" +]; +var readmeFilename = "README.md"; +var license = "BSD-2-Clause"; +var devDependencies = { + "@definitelytyped/dtslint": "^0.0.133", + "@types/node": "^18.11.3", + decache: "^4.6.1", + sinon: "^14.0.1", + standard: "^17.0.0", + "standard-markdown": "^7.1.0", + "standard-version": "^9.5.0", + tap: "^16.3.0", + tar: "^6.1.11", + typescript: "^4.8.4" +}; +var engines = { + node: ">=12" +}; +var browser = { + fs: false +}; +var require$$4 = { + name: name, + version: version$1, + description: description, + main: main, + types: types, + exports: exports$1, + scripts: scripts, + repository: repository, + funding: funding, + keywords: keywords, + readmeFilename: readmeFilename, + license: license, + devDependencies: devDependencies, + engines: engines, + browser: browser +}; + +const fs = fs$2; +const path = require$$0$1; +const os = require$$2; +const crypto = require$$0$2; +const packageJson = require$$4; + +const version = packageJson.version; + +const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + +// Parse src into an Object +function parse (src) { + const obj = {}; + + // Convert buffer to string + let lines = src.toString(); + + // Convert line breaks to same format + lines = lines.replace(/\r\n?/mg, '\n'); + + let match; + while ((match = LINE.exec(lines)) != null) { + const key = match[1]; + + // Default undefined or null to empty string + let value = (match[2] || ''); + + // Remove whitespace + value = value.trim(); + + // Check if double quoted + const maybeQuote = value[0]; + + // Remove surrounding quotes + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'); + + // Expand newlines if double quoted + if (maybeQuote === '"') { + value = value.replace(/\\n/g, '\n'); + value = value.replace(/\\r/g, '\r'); + } + + // Add to object + obj[key] = value; + } + + return obj +} + +function _parseVault (options) { + const vaultPath = _vaultPath(options); + + // Parse .env.vault + const result = DotenvModule.configDotenv({ path: vaultPath }); + if (!result.parsed) { + const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); + err.code = 'MISSING_DATA'; + throw err + } + + // handle scenario for comma separated keys - for use with key rotation + // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" + const keys = _dotenvKey(options).split(','); + const length = keys.length; + + let decrypted; + for (let i = 0; i < length; i++) { + try { + // Get full key + const key = keys[i].trim(); + + // Get instructions for decrypt + const attrs = _instructions(result, key); + + // Decrypt + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); + + break + } catch (error) { + // last key + if (i + 1 >= length) { + throw error + } + // try next key + } + } + + // Parse decrypted .env string + return DotenvModule.parse(decrypted) +} + +function _log (message) { + console.log(`[dotenv@${version}][INFO] ${message}`); +} + +function _warn (message) { + console.log(`[dotenv@${version}][WARN] ${message}`); +} + +function _debug (message) { + console.log(`[dotenv@${version}][DEBUG] ${message}`); +} + +function _dotenvKey (options) { + // prioritize developer directly setting options.DOTENV_KEY + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY + } + + // secondary infra already contains a DOTENV_KEY environment variable + if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { + return process.env.DOTENV_KEY + } + + // fallback to empty string + return '' +} + +function _instructions (result, dotenvKey) { + // Parse DOTENV_KEY. Format is a URI + let uri; + try { + uri = new URL(dotenvKey); + } catch (error) { + if (error.code === 'ERR_INVALID_URL') { + const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } + + throw error + } + + // Get decrypt key + const key = uri.password; + if (!key) { + const err = new Error('INVALID_DOTENV_KEY: Missing key part'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } + + // Get environment + const environment = uri.searchParams.get('environment'); + if (!environment) { + const err = new Error('INVALID_DOTENV_KEY: Missing environment part'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } + + // Get ciphertext payload + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; + const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION + if (!ciphertext) { + const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); + err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'; + throw err + } + + return { ciphertext, key } +} + +function _vaultPath (options) { + let possibleVaultPath = null; + + if (options && options.path && options.path.length > 0) { + if (Array.isArray(options.path)) { + for (const filepath of options.path) { + if (fs.existsSync(filepath)) { + possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`; + } + } + } else { + possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`; + } + } else { + possibleVaultPath = path.resolve(process.cwd(), '.env.vault'); + } + + if (fs.existsSync(possibleVaultPath)) { + return possibleVaultPath + } + + return null +} + +function _resolveHome (envPath) { + return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath +} + +function _configVault (options) { + _log('Loading env from encrypted .env.vault'); + + const parsed = DotenvModule._parseVault(options); + + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + DotenvModule.populate(processEnv, parsed, options); + + return { parsed } +} + +function configDotenv (options) { + const dotenvPath = path.resolve(process.cwd(), '.env'); + let encoding = 'utf8'; + const debug = Boolean(options && options.debug); + + if (options && options.encoding) { + encoding = options.encoding; + } else { + if (debug) { + _debug('No encoding is specified. UTF-8 is used by default'); + } + } + + let optionPathsThatExist = []; + if (options && options.path) { + if (!Array.isArray(options.path)) { + if (fs.existsSync(options.path)) { + optionPathsThatExist = [_resolveHome(options.path)]; + } + } else { + for (const filepath of options.path) { + if (fs.existsSync(filepath)) { + optionPathsThatExist.push(_resolveHome(filepath)); + } + } + } + + if (!optionPathsThatExist.length) { + optionPathsThatExist = [dotenvPath]; + } + } + + // If we have options.path, and it had valid paths, use them. Else fall back to .env + const pathsToProcess = optionPathsThatExist.length ? optionPathsThatExist : [dotenvPath]; + + // Build the parsed data in a temporary object (because we need to return it). Once we have the final + // parsed data, we will combine it with process.env (or options.processEnv if provided). + + const parsed = {}; + try { + for (const path of pathsToProcess) { + // Specifying an encoding returns a string instead of a buffer + const singleFileParsed = DotenvModule.parse(fs.readFileSync(path, { encoding })); + DotenvModule.populate(parsed, singleFileParsed, options); + } + + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + DotenvModule.populate(processEnv, parsed, options); + } catch (e) { + if (debug) { + _debug(`Failed to load ${pathsToProcess} ${e.message}`); + } + return { error: e } + } + return { parsed } +} + +// Populates process.env from .env file +function config (options) { + // fallback to original dotenv if DOTENV_KEY is not set + if (_dotenvKey(options).length === 0) { + return DotenvModule.configDotenv(options) + } + + const vaultPath = _vaultPath(options); + + // dotenvKey exists but .env.vault file does not exist + if (!vaultPath) { + _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); + + return DotenvModule.configDotenv(options) + } + + return DotenvModule._configVault(options) +} + +function decrypt (encrypted, keyStr) { + const key = Buffer.from(keyStr.slice(-64), 'hex'); + let ciphertext = Buffer.from(encrypted, 'base64'); + + const nonce = ciphertext.subarray(0, 12); + const authTag = ciphertext.subarray(-16); + ciphertext = ciphertext.subarray(12, -16); + + try { + const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce); + aesgcm.setAuthTag(authTag); + return `${aesgcm.update(ciphertext)}${aesgcm.final()}` + } catch (error) { + const isRange = error instanceof RangeError; + const invalidKeyLength = error.message === 'Invalid key length'; + const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'; + + if (isRange || invalidKeyLength) { + const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } else if (decryptionFailed) { + const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY'); + err.code = 'DECRYPTION_FAILED'; + throw err + } else { + throw error + } + } +} + +// Populate process.env with parsed values +function populate (processEnv, parsed, options = {}) { + const debug = Boolean(options && options.debug); + const override = Boolean(options && options.override); + + if (typeof parsed !== 'object') { + const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate'); + err.code = 'OBJECT_REQUIRED'; + throw err + } + + // Set process.env + for (const key of Object.keys(parsed)) { + if (Object.prototype.hasOwnProperty.call(processEnv, key)) { + if (override === true) { + processEnv[key] = parsed[key]; + } + + if (debug) { + if (override === true) { + _debug(`"${key}" is already defined and WAS overwritten`); + } else { + _debug(`"${key}" is already defined and was NOT overwritten`); + } + } + } else { + processEnv[key] = parsed[key]; + } + } +} + +const DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config, + decrypt, + parse, + populate +}; + +main$1.exports.configDotenv = DotenvModule.configDotenv; +main$1.exports._configVault = DotenvModule._configVault; +main$1.exports._parseVault = DotenvModule._parseVault; +main$1.exports.config = DotenvModule.config; +main$1.exports.decrypt = DotenvModule.decrypt; +var parse_1 = main$1.exports.parse = DotenvModule.parse; +main$1.exports.populate = DotenvModule.populate; + +main$1.exports = DotenvModule; + +// * / +// * (\\)? # is it escaped with a backslash? +// * (\$) # literal $ +// * (?!\() # shouldnt be followed by parenthesis +// * (\{?) # first brace wrap opening +// * ([\w.]+) # key +// * (?::-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))? # optional default nested 3 times +// * (\}?) # last brace warp closing +// * /xi + +const DOTENV_SUBSTITUTION_REGEX = /(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi; + +function _resolveEscapeSequences (value) { + return value.replace(/\\\$/g, '$') +} + +function interpolate (value, processEnv, parsed) { + return value.replace(DOTENV_SUBSTITUTION_REGEX, (match, escaped, dollarSign, openBrace, key, defaultValue, closeBrace) => { + if (escaped === '\\') { + return match.slice(1) + } else { + if (processEnv[key]) { + if (processEnv[key] === parsed[key]) { + return processEnv[key] + } else { + // scenario: PASSWORD_EXPAND_NESTED=${PASSWORD_EXPAND} + return interpolate(processEnv[key], processEnv, parsed) + } + } + + if (parsed[key]) { + // avoid recursion from EXPAND_SELF=$EXPAND_SELF + if (parsed[key] === value) { + return parsed[key] + } else { + return interpolate(parsed[key], processEnv, parsed) + } + } + + if (defaultValue) { + if (defaultValue.startsWith('$')) { + return interpolate(defaultValue, processEnv, parsed) + } else { + return defaultValue + } + } + + return '' + } + }) +} + +function expand (options) { + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + for (const key in options.parsed) { + let value = options.parsed[key]; + + const inProcessEnv = Object.prototype.hasOwnProperty.call(processEnv, key); + if (inProcessEnv) { + if (processEnv[key] === options.parsed[key]) { + // assume was set to processEnv from the .env file if the values match and therefore interpolate + value = interpolate(value, processEnv, options.parsed); + } else { + // do not interpolate - assume processEnv had the intended value even if containing a $. + value = processEnv[key]; + } + } else { + // not inProcessEnv so assume interpolation for this .env key + value = interpolate(value, processEnv, options.parsed); + } + + options.parsed[key] = _resolveEscapeSequences(value); + } + + for (const processKey in options.parsed) { + processEnv[processKey] = options.parsed[processKey]; + } + + return options +} + +var expand_1 = expand; + +function getEnvFilesForMode(mode, envDir) { + return [ + /** default file */ `.env`, + /** local file */ `.env.local`, + /** mode file */ `.env.${mode}`, + /** mode local file */ `.env.${mode}.local`, + ].map((file) => normalizePath(path$3.join(envDir, file))); +} +function loadEnv(mode, envDir, prefixes = 'VITE_') { + if (mode === 'local') { + throw new Error(`"local" cannot be used as a mode name because it conflicts with ` + + `the .local postfix for .env files.`); + } + prefixes = arraify(prefixes); + const env = {}; + const envFiles = getEnvFilesForMode(mode, envDir); + const parsed = Object.fromEntries(envFiles.flatMap((filePath) => { + if (!tryStatSync(filePath)?.isFile()) + return []; + return Object.entries(parse_1(fs$1.readFileSync(filePath))); + })); + // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this + if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) { + process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV; + } + // support BROWSER and BROWSER_ARGS env variables + if (parsed.BROWSER && process.env.BROWSER === undefined) { + process.env.BROWSER = parsed.BROWSER; + } + if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) { + process.env.BROWSER_ARGS = parsed.BROWSER_ARGS; + } + // let environment variables use each other. make a copy of `process.env` so that `dotenv-expand` + // doesn't re-assign the expanded values to the global `process.env`. + const processEnv = { ...process.env }; + expand_1({ parsed, processEnv }); + // only keys that start with prefix are exposed to client + for (const [key, value] of Object.entries(parsed)) { + if (prefixes.some((prefix) => key.startsWith(prefix))) { + env[key] = value; + } + } + // check if there are actual env variables starting with VITE_* + // these are typically provided inline and should be prioritized + for (const key in process.env) { + if (prefixes.some((prefix) => key.startsWith(prefix))) { + env[key] = process.env[key]; + } + } + return env; +} +function resolveEnvPrefix({ envPrefix = 'VITE_', }) { + envPrefix = arraify(envPrefix); + if (envPrefix.includes('')) { + throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`); + } + return envPrefix; +} + +exports.esbuildVersion = esbuild.version; +exports.createFilter = createFilter; +exports.createLogger = createLogger; +exports.isCSSRequest = isCSSRequest; +exports.isFileServingAllowed = isFileServingAllowed; +exports.loadEnv = loadEnv; +exports.mergeAlias = mergeAlias; +exports.mergeConfig = mergeConfig; +exports.normalizePath = normalizePath; +exports.resolveEnvPrefix = resolveEnvPrefix; +exports.rollupVersion = rollupVersion; +exports.searchForWorkspaceRoot = searchForWorkspaceRoot; +exports.send = send; +exports.splitVendorChunk = splitVendorChunk; +exports.splitVendorChunkPlugin = splitVendorChunkPlugin; +exports.version = VERSION; diff --git a/web/node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js b/web/node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js new file mode 100644 index 0000000000000000000000000000000000000000..b471e601ae4ec1aa4833eb07e3c8d04d0222f5ab --- /dev/null +++ b/web/node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js @@ -0,0 +1,561 @@ +import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; +import { dirname as __cjs_dirname } from 'node:path'; +import { createRequire as __cjs_createRequire } from 'node:module'; + +const __filename = __cjs_fileURLToPath(import.meta.url); +const __dirname = __cjs_dirname(__filename); +const require = __cjs_createRequire(import.meta.url); +const __require = require; +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; + +var parse$1 = 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; +}; + +var walk$1 = 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); + } + } +}; + +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$1(node.nodes, custom); + if (type !== "function") { + return buf; + } + return ( + value + + "(" + + (node.before || "") + + buf + + (node.after || "") + + (node.unclosed ? "" : ")") + ); + } + return value; +} + +function stringify$1(nodes, custom) { + var result, i; + + if (Array.isArray(nodes)) { + result = ""; + for (i = nodes.length - 1; ~i; i -= 1) { + result = stringifyNode(nodes[i], custom) + result; + } + return result; + } + return stringifyNode(nodes, custom); +} + +var stringify_1 = stringify$1; + +var unit; +var hasRequiredUnit; + +function requireUnit () { + if (hasRequiredUnit) return unit; + hasRequiredUnit = 1; + 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 + unit = 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) + }; + }; + return unit; +} + +var parse = parse$1; +var walk = walk$1; +var stringify = stringify_1; + +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 = requireUnit(); + +ValueParser.walk = walk; + +ValueParser.stringify = stringify; + +var lib = ValueParser; + +export { lib as l }; diff --git a/web/node_modules/vite/dist/node/chunks/dep-g6LmopN4.js b/web/node_modules/vite/dist/node/chunks/dep-g6LmopN4.js new file mode 100644 index 0000000000000000000000000000000000000000..8bfa43cd8797faf977b1f6a4d456ff8127781caf --- /dev/null +++ b/web/node_modules/vite/dist/node/chunks/dep-g6LmopN4.js @@ -0,0 +1,7646 @@ +import { C as commonjsGlobal, B as getDefaultExportFromCjs } from './dep-jDlpJiMN.js'; +import require$$0__default from 'fs'; +import require$$0 from 'postcss'; +import require$$0$1 from 'path'; +import require$$0$2 from 'crypto'; +import require$$0$3 from 'util'; +import { l as lib } from './dep-8a-6Quh6.js'; + +import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; +import { dirname as __cjs_dirname } from 'node:path'; +import { createRequire as __cjs_createRequire } from 'node:module'; + +const __filename = __cjs_fileURLToPath(import.meta.url); +const __dirname = __cjs_dirname(__filename); +const require = __cjs_createRequire(import.meta.url); +const __require = require; +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + var e = m[i]; + if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) { + if (k !== 'default' && !(k in n)) { + n[k] = e[k]; + } + } } + } + return n; +} + +var build = {exports: {}}; + +var fs = {}; + +Object.defineProperty(fs, "__esModule", { + value: true +}); +fs.getFileSystem = getFileSystem; +fs.setFileSystem = setFileSystem; +let fileSystem = { + readFile: () => { + throw Error("readFile not implemented"); + }, + writeFile: () => { + throw Error("writeFile not implemented"); + } +}; + +function setFileSystem(fs) { + fileSystem.readFile = fs.readFile; + fileSystem.writeFile = fs.writeFile; +} + +function getFileSystem() { + return fileSystem; +} + +var pluginFactory = {}; + +var unquote$1 = {}; + +Object.defineProperty(unquote$1, "__esModule", { + value: true +}); +unquote$1.default = unquote; +// copied from https://github.com/lakenen/node-unquote +const reg = /['"]/; + +function unquote(str) { + if (!str) { + return ""; + } + + if (reg.test(str.charAt(0))) { + str = str.substr(1); + } + + if (reg.test(str.charAt(str.length - 1))) { + str = str.substr(0, str.length - 1); + } + + return str; +} + +var Parser$1 = {}; + +const matchValueName = /[$]?[\w-]+/g; + +const replaceValueSymbols$2 = (value, replacements) => { + let matches; + + while ((matches = matchValueName.exec(value))) { + const replacement = replacements[matches[0]]; + + if (replacement) { + value = + value.slice(0, matches.index) + + replacement + + value.slice(matchValueName.lastIndex); + + matchValueName.lastIndex -= matches[0].length - replacement.length; + } + } + + return value; +}; + +var replaceValueSymbols_1 = replaceValueSymbols$2; + +const replaceValueSymbols$1 = replaceValueSymbols_1; + +const replaceSymbols$1 = (css, replacements) => { + css.walk((node) => { + if (node.type === "decl" && node.value) { + node.value = replaceValueSymbols$1(node.value.toString(), replacements); + } else if (node.type === "rule" && node.selector) { + node.selector = replaceValueSymbols$1( + node.selector.toString(), + replacements + ); + } else if (node.type === "atrule" && node.params) { + node.params = replaceValueSymbols$1(node.params.toString(), replacements); + } + }); +}; + +var replaceSymbols_1 = replaceSymbols$1; + +const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/; +const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/; + +const getDeclsObject = (rule) => { + const object = {}; + + rule.walkDecls((decl) => { + const before = decl.raws.before ? decl.raws.before.trim() : ""; + + object[before + decl.prop] = decl.value; + }); + + return object; +}; +/** + * + * @param {string} css + * @param {boolean} removeRules + * @param {'auto' | 'rule' | 'at-rule'} mode + */ +const extractICSS$2 = (css, removeRules = true, mode = "auto") => { + const icssImports = {}; + const icssExports = {}; + + function addImports(node, path) { + const unquoted = path.replace(/'|"/g, ""); + icssImports[unquoted] = Object.assign( + icssImports[unquoted] || {}, + getDeclsObject(node) + ); + + if (removeRules) { + node.remove(); + } + } + + function addExports(node) { + Object.assign(icssExports, getDeclsObject(node)); + if (removeRules) { + node.remove(); + } + } + + css.each((node) => { + if (node.type === "rule" && mode !== "at-rule") { + if (node.selector.slice(0, 7) === ":import") { + const matches = importPattern.exec(node.selector); + + if (matches) { + addImports(node, matches[1]); + } + } + + if (node.selector === ":export") { + addExports(node); + } + } + + if (node.type === "atrule" && mode !== "rule") { + if (node.name === "icss-import") { + const matches = balancedQuotes.exec(node.params); + + if (matches) { + addImports(node, matches[1]); + } + } + if (node.name === "icss-export") { + addExports(node); + } + } + }); + + return { icssImports, icssExports }; +}; + +var extractICSS_1 = extractICSS$2; + +const createImports = (imports, postcss, mode = "rule") => { + return Object.keys(imports).map((path) => { + const aliases = imports[path]; + const declarations = Object.keys(aliases).map((key) => + postcss.decl({ + prop: key, + value: aliases[key], + raws: { before: "\n " }, + }) + ); + + const hasDeclarations = declarations.length > 0; + + const rule = + mode === "rule" + ? postcss.rule({ + selector: `:import('${path}')`, + raws: { after: hasDeclarations ? "\n" : "" }, + }) + : postcss.atRule({ + name: "icss-import", + params: `'${path}'`, + raws: { after: hasDeclarations ? "\n" : "" }, + }); + + if (hasDeclarations) { + rule.append(declarations); + } + + return rule; + }); +}; + +const createExports = (exports, postcss, mode = "rule") => { + const declarations = Object.keys(exports).map((key) => + postcss.decl({ + prop: key, + value: exports[key], + raws: { before: "\n " }, + }) + ); + + if (declarations.length === 0) { + return []; + } + const rule = + mode === "rule" + ? postcss.rule({ + selector: `:export`, + raws: { after: "\n" }, + }) + : postcss.atRule({ + name: "icss-export", + raws: { after: "\n" }, + }); + + rule.append(declarations); + + return [rule]; +}; + +const createICSSRules$1 = (imports, exports, postcss, mode) => [ + ...createImports(imports, postcss, mode), + ...createExports(exports, postcss, mode), +]; + +var createICSSRules_1 = createICSSRules$1; + +const replaceValueSymbols = replaceValueSymbols_1; +const replaceSymbols = replaceSymbols_1; +const extractICSS$1 = extractICSS_1; +const createICSSRules = createICSSRules_1; + +var src$4 = { + replaceValueSymbols, + replaceSymbols, + extractICSS: extractICSS$1, + createICSSRules, +}; + +Object.defineProperty(Parser$1, "__esModule", { + value: true +}); +Parser$1.default = void 0; + +var _icssUtils = src$4; + +// Initially copied from https://github.com/css-modules/css-modules-loader-core +const importRegexp = /^:import\((.+)\)$/; + +class Parser { + constructor(pathFetcher, trace) { + this.pathFetcher = pathFetcher; + this.plugin = this.plugin.bind(this); + this.exportTokens = {}; + this.translations = {}; + this.trace = trace; + } + + plugin() { + const parser = this; + return { + postcssPlugin: "css-modules-parser", + + async OnceExit(css) { + await Promise.all(parser.fetchAllImports(css)); + parser.linkImportedSymbols(css); + return parser.extractExports(css); + } + + }; + } + + fetchAllImports(css) { + let imports = []; + css.each(node => { + if (node.type == "rule" && node.selector.match(importRegexp)) { + imports.push(this.fetchImport(node, css.source.input.from, imports.length)); + } + }); + return imports; + } + + linkImportedSymbols(css) { + (0, _icssUtils.replaceSymbols)(css, this.translations); + } + + extractExports(css) { + css.each(node => { + if (node.type == "rule" && node.selector == ":export") this.handleExport(node); + }); + } + + handleExport(exportNode) { + exportNode.each(decl => { + if (decl.type == "decl") { + Object.keys(this.translations).forEach(translation => { + decl.value = decl.value.replace(translation, this.translations[translation]); + }); + this.exportTokens[decl.prop] = decl.value; + } + }); + exportNode.remove(); + } + + async fetchImport(importNode, relativeTo, depNr) { + const file = importNode.selector.match(importRegexp)[1]; + const depTrace = this.trace + String.fromCharCode(depNr); + const exports = await this.pathFetcher(file, relativeTo, depTrace); + + try { + importNode.each(decl => { + if (decl.type == "decl") { + this.translations[decl.prop] = exports[decl.value]; + } + }); + importNode.remove(); + } catch (err) { + console.log(err); + } + } + +} + +Parser$1.default = Parser; + +var saveJSON$1 = {}; + +Object.defineProperty(saveJSON$1, "__esModule", { + value: true +}); +saveJSON$1.default = saveJSON; + +var _fs$2 = fs; + +function saveJSON(cssFile, json) { + return new Promise((resolve, reject) => { + const { + writeFile + } = (0, _fs$2.getFileSystem)(); + writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json)); + }); +} + +var localsConvention = {}; + +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange = '\\u20d0-\\u20f0', + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', + rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos, 'g'); + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo, 'g'); + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', + rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, + rsUpper + '+' + rsOptUpperContr, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); + +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 'ss' +}; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root$2 = freeGlobal || freeSelf || Function('return this')(); + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = basePropertyOf(deburredLetters); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var Symbol$1 = root$2.Symbol; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); +}); + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); +} + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +/** + * Converts the first character of `string` to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.upperFirst('fred'); + * // => 'Fred' + * + * _.upperFirst('FRED'); + * // => 'FRED' + */ +var upperFirst = createCaseFirst('toUpperCase'); + +/** + * Splits `string` into an array of its words. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {RegExp|string} [pattern] The pattern to match words. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the words of `string`. + * @example + * + * _.words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * _.words('fred, barney, & pebbles', /[^, ]+/g); + * // => ['fred', 'barney', '&', 'pebbles'] + */ +function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined : pattern; + + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; +} + +var lodash_camelcase = camelCase; + +Object.defineProperty(localsConvention, "__esModule", { + value: true +}); +localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer; + +var _lodash = _interopRequireDefault$5(lodash_camelcase); + +function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function dashesCamelCase(string) { + return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase()); +} + +function makeLocalsConventionReducer(localsConvention, inputFile) { + const isFunc = typeof localsConvention === "function"; + return (tokens, [className, value]) => { + if (isFunc) { + const convention = localsConvention(className, value, inputFile); + tokens[convention] = value; + return tokens; + } + + switch (localsConvention) { + case "camelCase": + tokens[className] = value; + tokens[(0, _lodash.default)(className)] = value; + break; + + case "camelCaseOnly": + tokens[(0, _lodash.default)(className)] = value; + break; + + case "dashes": + tokens[className] = value; + tokens[dashesCamelCase(className)] = value; + break; + + case "dashesOnly": + tokens[dashesCamelCase(className)] = value; + break; + } + + return tokens; + }; +} + +var FileSystemLoader$1 = {}; + +Object.defineProperty(FileSystemLoader$1, "__esModule", { + value: true +}); +FileSystemLoader$1.default = void 0; + +var _postcss$1 = _interopRequireDefault$4(require$$0); + +var _path = _interopRequireDefault$4(require$$0$1); + +var _Parser$1 = _interopRequireDefault$4(Parser$1); + +var _fs$1 = fs; + +function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// Initially copied from https://github.com/css-modules/css-modules-loader-core +class Core { + constructor(plugins) { + this.plugins = plugins || Core.defaultPlugins; + } + + async load(sourceString, sourcePath, trace, pathFetcher) { + const parser = new _Parser$1.default(pathFetcher, trace); + const plugins = this.plugins.concat([parser.plugin()]); + const result = await (0, _postcss$1.default)(plugins).process(sourceString, { + from: sourcePath + }); + return { + injectableSource: result.css, + exportTokens: parser.exportTokens + }; + } + +} // Sorts dependencies in the following way: +// AAA comes before AA and A +// AB comes after AA and before A +// All Bs come after all As +// This ensures that the files are always returned in the following order: +// - In the order they were required, except +// - After all their dependencies + + +const traceKeySorter = (a, b) => { + if (a.length < b.length) { + return a < b.substring(0, a.length) ? -1 : 1; + } + + if (a.length > b.length) { + return a.substring(0, b.length) <= b ? -1 : 1; + } + + return a < b ? -1 : 1; +}; + +class FileSystemLoader { + constructor(root, plugins, fileResolve) { + if (root === "/" && process.platform === "win32") { + const cwdDrive = process.cwd().slice(0, 3); + + if (!/^[A-Za-z]:\\$/.test(cwdDrive)) { + throw new Error(`Failed to obtain root from "${process.cwd()}".`); + } + + root = cwdDrive; + } + + this.root = root; + this.fileResolve = fileResolve; + this.sources = {}; + this.traces = {}; + this.importNr = 0; + this.core = new Core(plugins); + this.tokensByFile = {}; + this.fs = (0, _fs$1.getFileSystem)(); + } + + async fetch(_newPath, relativeTo, _trace) { + const newPath = _newPath.replace(/^["']|["']$/g, ""); + + const trace = _trace || String.fromCharCode(this.importNr++); + + const useFileResolve = typeof this.fileResolve === "function"; + const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve(); + + if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) { + throw new Error('The returned path from the "fileResolve" option must be absolute.'); + } + + const relativeDir = _path.default.dirname(relativeTo); + + const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath); + + let fileRelativePath = fileResolvedPath || _path.default.resolve(_path.default.resolve(this.root, relativeDir), newPath); // if the path is not relative or absolute, try to resolve it in node_modules + + + if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) { + try { + fileRelativePath = require.resolve(newPath); + } catch (e) {// noop + } + } + + const tokens = this.tokensByFile[fileRelativePath]; + if (tokens) return tokens; + return new Promise((resolve, reject) => { + this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => { + if (err) reject(err); + const { + injectableSource, + exportTokens + } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this)); + this.sources[fileRelativePath] = injectableSource; + this.traces[trace] = fileRelativePath; + this.tokensByFile[fileRelativePath] = exportTokens; + resolve(exportTokens); + }); + }); + } + + get finalSource() { + const traces = this.traces; + const sources = this.sources; + let written = new Set(); + return Object.keys(traces).sort(traceKeySorter).map(key => { + const filename = traces[key]; + + if (written.has(filename)) { + return null; + } + + written.add(filename); + return sources[filename]; + }).join(""); + } + +} + +FileSystemLoader$1.default = FileSystemLoader; + +var scoping = {}; + +var src$3 = {exports: {}}; + +const PERMANENT_MARKER = 2; +const TEMPORARY_MARKER = 1; + +function createError(node, graph) { + const er = new Error("Nondeterministic import's order"); + + const related = graph[node]; + const relatedNode = related.find( + (relatedNode) => graph[relatedNode].indexOf(node) > -1 + ); + + er.nodes = [node, relatedNode]; + + return er; +} + +function walkGraph(node, graph, state, result, strict) { + if (state[node] === PERMANENT_MARKER) { + return; + } + + if (state[node] === TEMPORARY_MARKER) { + if (strict) { + return createError(node, graph); + } + + return; + } + + state[node] = TEMPORARY_MARKER; + + const children = graph[node]; + const length = children.length; + + for (let i = 0; i < length; ++i) { + const error = walkGraph(children[i], graph, state, result, strict); + + if (error instanceof Error) { + return error; + } + } + + state[node] = PERMANENT_MARKER; + + result.push(node); +} + +function topologicalSort$1(graph, strict) { + const result = []; + const state = {}; + + const nodes = Object.keys(graph); + const length = nodes.length; + + for (let i = 0; i < length; ++i) { + const er = walkGraph(nodes[i], graph, state, result, strict); + + if (er instanceof Error) { + return er; + } + } + + return result; +} + +var topologicalSort_1 = topologicalSort$1; + +const topologicalSort = topologicalSort_1; + +const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/; +const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/; + +const VISITED_MARKER = 1; + +/** + * :import('G') {} + * + * Rule + * composes: ... from 'A' + * composes: ... from 'B' + + * Rule + * composes: ... from 'A' + * composes: ... from 'A' + * composes: ... from 'C' + * + * Results in: + * + * graph: { + * G: [], + * A: [], + * B: ['A'], + * C: ['A'], + * } + */ +function addImportToGraph(importId, parentId, graph, visited) { + const siblingsId = parentId + "_" + "siblings"; + const visitedId = parentId + "_" + importId; + + if (visited[visitedId] !== VISITED_MARKER) { + if (!Array.isArray(visited[siblingsId])) { + visited[siblingsId] = []; + } + + const siblings = visited[siblingsId]; + + if (Array.isArray(graph[importId])) { + graph[importId] = graph[importId].concat(siblings); + } else { + graph[importId] = siblings.slice(); + } + + visited[visitedId] = VISITED_MARKER; + + siblings.push(importId); + } +} + +src$3.exports = (options = {}) => { + let importIndex = 0; + const createImportedName = + typeof options.createImportedName !== "function" + ? (importName /*, path*/) => + `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}` + : options.createImportedName; + const failOnWrongOrder = options.failOnWrongOrder; + + return { + postcssPlugin: "postcss-modules-extract-imports", + prepare() { + const graph = {}; + const visited = {}; + const existingImports = {}; + const importDecls = {}; + const imports = {}; + + return { + Once(root, postcss) { + // Check the existing imports order and save refs + root.walkRules((rule) => { + const matches = icssImport.exec(rule.selector); + + if (matches) { + const [, /*match*/ doubleQuotePath, singleQuotePath] = matches; + const importPath = doubleQuotePath || singleQuotePath; + + addImportToGraph(importPath, "root", graph, visited); + + existingImports[importPath] = rule; + } + }); + + root.walkDecls(/^composes$/, (declaration) => { + const matches = declaration.value.match(matchImports$1); + + if (!matches) { + return; + } + + let tmpSymbols; + let [ + , + /*match*/ symbols, + doubleQuotePath, + singleQuotePath, + global, + ] = matches; + + if (global) { + // Composing globals simply means changing these classes to wrap them in global(name) + tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`); + } else { + const importPath = doubleQuotePath || singleQuotePath; + + let parent = declaration.parent; + let parentIndexes = ""; + + while (parent.type !== "root") { + parentIndexes = + parent.parent.index(parent) + "_" + parentIndexes; + parent = parent.parent; + } + + const { selector } = declaration.parent; + const parentRule = `_${parentIndexes}${selector}`; + + addImportToGraph(importPath, parentRule, graph, visited); + + importDecls[importPath] = declaration; + imports[importPath] = imports[importPath] || {}; + + tmpSymbols = symbols.split(/\s+/).map((s) => { + if (!imports[importPath][s]) { + imports[importPath][s] = createImportedName(s, importPath); + } + + return imports[importPath][s]; + }); + } + + declaration.value = tmpSymbols.join(" "); + }); + + const importsOrder = topologicalSort(graph, failOnWrongOrder); + + if (importsOrder instanceof Error) { + const importPath = importsOrder.nodes.find((importPath) => + // eslint-disable-next-line no-prototype-builtins + importDecls.hasOwnProperty(importPath) + ); + const decl = importDecls[importPath]; + + throw decl.error( + "Failed to resolve order of composed modules " + + importsOrder.nodes + .map((importPath) => "`" + importPath + "`") + .join(", ") + + ".", + { + plugin: "postcss-modules-extract-imports", + word: "composes", + } + ); + } + + let lastImportRule; + + importsOrder.forEach((path) => { + const importedSymbols = imports[path]; + let rule = existingImports[path]; + + if (!rule && importedSymbols) { + rule = postcss.rule({ + selector: `:import("${path}")`, + raws: { after: "\n" }, + }); + + if (lastImportRule) { + root.insertAfter(lastImportRule, rule); + } else { + root.prepend(rule); + } + } + + lastImportRule = rule; + + if (!importedSymbols) { + return; + } + + Object.keys(importedSymbols).forEach((importedSymbol) => { + rule.append( + postcss.decl({ + value: importedSymbol, + prop: importedSymbols[importedSymbol], + raws: { before: "\n " }, + }) + ); + }); + }); + }, + }; + }, + }; +}; + +src$3.exports.postcss = true; + +var srcExports$2 = src$3.exports; + +var BulkUpdateDecorator_1; +var hasRequiredBulkUpdateDecorator; + +function requireBulkUpdateDecorator () { + if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1; + hasRequiredBulkUpdateDecorator = 1; + const BULK_SIZE = 2000; + + // We are using an object instead of a Map as this will stay static during the runtime + // so access to it can be optimized by v8 + const digestCaches = {}; + + class BulkUpdateDecorator { + /** + * @param {Hash | function(): Hash} hashOrFactory function to create a hash + * @param {string=} hashKey key for caching + */ + constructor(hashOrFactory, hashKey) { + this.hashKey = hashKey; + + if (typeof hashOrFactory === "function") { + this.hashFactory = hashOrFactory; + this.hash = undefined; + } else { + this.hashFactory = undefined; + this.hash = hashOrFactory; + } + + this.buffer = ""; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if ( + inputEncoding !== undefined || + typeof data !== "string" || + data.length > BULK_SIZE + ) { + if (this.hash === undefined) { + this.hash = this.hashFactory(); + } + + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + this.buffer = ""; + } + + this.hash.update(data, inputEncoding); + } else { + this.buffer += data; + + if (this.buffer.length > BULK_SIZE) { + if (this.hash === undefined) { + this.hash = this.hashFactory(); + } + + this.hash.update(this.buffer); + this.buffer = ""; + } + } + + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + let digestCache; + + const buffer = this.buffer; + + if (this.hash === undefined) { + // short data for hash, we can use caching + const cacheKey = `${this.hashKey}-${encoding}`; + + digestCache = digestCaches[cacheKey]; + + if (digestCache === undefined) { + digestCache = digestCaches[cacheKey] = new Map(); + } + + const cacheEntry = digestCache.get(buffer); + + if (cacheEntry !== undefined) { + return cacheEntry; + } + + this.hash = this.hashFactory(); + } + + if (buffer.length > 0) { + this.hash.update(buffer); + } + + const digestResult = this.hash.digest(encoding); + + if (digestCache !== undefined) { + digestCache.set(buffer, digestResult); + } + + return digestResult; + } + } + + BulkUpdateDecorator_1 = BulkUpdateDecorator; + return BulkUpdateDecorator_1; +} + +var wasmHash = {exports: {}}; + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +var hasRequiredWasmHash; + +function requireWasmHash () { + if (hasRequiredWasmHash) return wasmHash.exports; + hasRequiredWasmHash = 1; + + // 65536 is the size of a wasm memory page + // 64 is the maximum chunk size for every possible wasm hash implementation + // 4 is the maximum number of bytes per char for string encoding (max is utf-8) + // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 + const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3; + + class WasmHash { + /** + * @param {WebAssembly.Instance} instance wasm instance + * @param {WebAssembly.Instance[]} instancesPool pool of instances + * @param {number} chunkSize size of data chunks passed to wasm + * @param {number} digestSize size of digest returned by wasm + */ + constructor(instance, instancesPool, chunkSize, digestSize) { + const exports = /** @type {any} */ (instance.exports); + + exports.init(); + + this.exports = exports; + this.mem = Buffer.from(exports.memory.buffer, 0, 65536); + this.buffered = 0; + this.instancesPool = instancesPool; + this.chunkSize = chunkSize; + this.digestSize = digestSize; + } + + reset() { + this.buffered = 0; + this.exports.init(); + } + + /** + * @param {Buffer | string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {this} itself + */ + update(data, encoding) { + if (typeof data === "string") { + while (data.length > MAX_SHORT_STRING) { + this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding); + data = data.slice(MAX_SHORT_STRING); + } + + this._updateWithShortString(data, encoding); + + return this; + } + + this._updateWithBuffer(data); + + return this; + } + + /** + * @param {string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {void} + */ + _updateWithShortString(data, encoding) { + const { exports, buffered, mem, chunkSize } = this; + + let endPos; + + if (data.length < 70) { + if (!encoding || encoding === "utf-8" || encoding === "utf8") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + + if (cc < 0x80) { + mem[endPos++] = cc; + } else if (cc < 0x800) { + mem[endPos] = (cc >> 6) | 0xc0; + mem[endPos + 1] = (cc & 0x3f) | 0x80; + endPos += 2; + } else { + // bail-out for weird chars + endPos += mem.write(data.slice(i), endPos, encoding); + break; + } + } + } else if (encoding === "latin1") { + endPos = buffered; + + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + + mem[endPos++] = cc; + } + } else { + endPos = buffered + mem.write(data, buffered, encoding); + } + } else { + endPos = buffered + mem.write(data, buffered, encoding); + } + + if (endPos < chunkSize) { + this.buffered = endPos; + } else { + const l = endPos & ~(this.chunkSize - 1); + + exports.update(l); + + const newBuffered = endPos - l; + + this.buffered = newBuffered; + + if (newBuffered > 0) { + mem.copyWithin(0, l, endPos); + } + } + } + + /** + * @param {Buffer} data data + * @returns {void} + */ + _updateWithBuffer(data) { + const { exports, buffered, mem } = this; + const length = data.length; + + if (buffered + length < this.chunkSize) { + data.copy(mem, buffered, 0, length); + + this.buffered += length; + } else { + const l = (buffered + length) & ~(this.chunkSize - 1); + + if (l > 65536) { + let i = 65536 - buffered; + + data.copy(mem, buffered, 0, i); + exports.update(65536); + + const stop = l - buffered - 65536; + + while (i < stop) { + data.copy(mem, 0, i, i + 65536); + exports.update(65536); + i += 65536; + } + + data.copy(mem, 0, i, l - buffered); + + exports.update(l - buffered - i); + } else { + data.copy(mem, buffered, 0, l - buffered); + + exports.update(l); + } + + const newBuffered = length + buffered - l; + + this.buffered = newBuffered; + + if (newBuffered > 0) { + data.copy(mem, 0, length - newBuffered, length); + } + } + } + + digest(type) { + const { exports, buffered, mem, digestSize } = this; + + exports.final(buffered); + + this.instancesPool.push(this); + + const hex = mem.toString("latin1", 0, digestSize); + + if (type === "hex") { + return hex; + } + + if (type === "binary" || !type) { + return Buffer.from(hex, "hex"); + } + + return Buffer.from(hex, "hex").toString(type); + } + } + + const create = (wasmModule, instancesPool, chunkSize, digestSize) => { + if (instancesPool.length > 0) { + const old = instancesPool.pop(); + + old.reset(); + + return old; + } else { + return new WasmHash( + new WebAssembly.Instance(wasmModule), + instancesPool, + chunkSize, + digestSize + ); + } + }; + + wasmHash.exports = create; + wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; + return wasmHash.exports; +} + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +var md4_1; +var hasRequiredMd4; + +function requireMd4 () { + if (hasRequiredMd4) return md4_1; + hasRequiredMd4 = 1; + + const create = requireWasmHash(); + + //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1 + const md4 = new WebAssembly.Module( + Buffer.from( + // 2150 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvMCgEYfyMBIQojAiEGIwMhByMEIQgDQCAAIAVLBEAgBSgCCCINIAcgBiAFKAIEIgsgCCAHIAUoAgAiDCAKIAggBiAHIAhzcXNqakEDdyIDIAYgB3Nxc2pqQQd3IgEgAyAGc3FzampBC3chAiAFKAIUIg8gASACIAUoAhAiCSADIAEgBSgCDCIOIAYgAyACIAEgA3Nxc2pqQRN3IgQgASACc3FzampBA3ciAyACIARzcXNqakEHdyEBIAUoAiAiEiADIAEgBSgCHCIRIAQgAyAFKAIYIhAgAiAEIAEgAyAEc3FzampBC3ciAiABIANzcXNqakETdyIEIAEgAnNxc2pqQQN3IQMgBSgCLCIVIAQgAyAFKAIoIhQgAiAEIAUoAiQiEyABIAIgAyACIARzcXNqakEHdyIBIAMgBHNxc2pqQQt3IgIgASADc3FzampBE3chBCAPIBAgCSAVIBQgEyAFKAI4IhYgAiAEIAUoAjQiFyABIAIgBSgCMCIYIAMgASAEIAEgAnNxc2pqQQN3IgEgAiAEc3FzampBB3ciAiABIARzcXNqakELdyIDIAkgAiAMIAEgBSgCPCIJIAQgASADIAEgAnNxc2pqQRN3IgEgAiADcnEgAiADcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyaiASakGZ84nUBWpBCXciAyAPIAQgCyACIBggASADIAIgBHJxIAIgBHFyampBmfOJ1AVqQQ13IgEgAyAEcnEgAyAEcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyampBmfOJ1AVqQQl3IgMgECAEIAIgFyABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmogDWpBmfOJ1AVqQQN3IgIgASADcnEgASADcXJqakGZ84nUBWpBBXciBCABIAJycSABIAJxcmpqQZnzidQFakEJdyIDIBEgBCAOIAIgFiABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmpqQZnzidQFakEDdyICIAEgA3JxIAEgA3FyampBmfOJ1AVqQQV3IgQgASACcnEgASACcXJqakGZ84nUBWpBCXciAyAMIAIgAyAJIAEgAyACIARycSACIARxcmpqQZnzidQFakENdyIBcyAEc2pqQaHX5/YGakEDdyICIAQgASACcyADc2ogEmpBodfn9gZqQQl3IgRzIAFzampBodfn9gZqQQt3IgMgAiADIBggASADIARzIAJzampBodfn9gZqQQ93IgFzIARzaiANakGh1+f2BmpBA3ciAiAUIAQgASACcyADc2pqQaHX5/YGakEJdyIEcyABc2pqQaHX5/YGakELdyIDIAsgAiADIBYgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgIgEyAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3chAyAKIA4gAiADIBcgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgJqIQogBiAJIAEgESADIAIgFSAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3ciAyAEcyACc2pqQaHX5/YGakEPd2ohBiADIAdqIQcgBCAIaiEIIAVBQGshBQwBCwsgCiQBIAYkAiAHJAMgCCQECw0AIAAQASMAIABqJAAL/wQCA38BfiMAIABqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", + "base64" + ) + ); + //#endregion + + md4_1 = create.bind(null, md4, [], 64, 32); + return md4_1; +} + +var BatchedHash_1; +var hasRequiredBatchedHash; + +function requireBatchedHash () { + if (hasRequiredBatchedHash) return BatchedHash_1; + hasRequiredBatchedHash = 1; + const MAX_SHORT_STRING = requireWasmHash().MAX_SHORT_STRING; + + class BatchedHash { + constructor(hash) { + this.string = undefined; + this.encoding = undefined; + this.hash = hash; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if (this.string !== undefined) { + if ( + typeof data === "string" && + inputEncoding === this.encoding && + this.string.length + data.length < MAX_SHORT_STRING + ) { + this.string += data; + + return this; + } + + this.hash.update(this.string, this.encoding); + this.string = undefined; + } + + if (typeof data === "string") { + if ( + data.length < MAX_SHORT_STRING && + // base64 encoding is not valid since it may contain padding chars + (!inputEncoding || !inputEncoding.startsWith("ba")) + ) { + this.string = data; + this.encoding = inputEncoding; + } else { + this.hash.update(data, inputEncoding); + } + } else { + this.hash.update(data); + } + + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + if (this.string !== undefined) { + this.hash.update(this.string, this.encoding); + } + + return this.hash.digest(encoding); + } + } + + BatchedHash_1 = BatchedHash; + return BatchedHash_1; +} + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +var xxhash64_1; +var hasRequiredXxhash64; + +function requireXxhash64 () { + if (hasRequiredXxhash64) return xxhash64_1; + hasRequiredXxhash64 = 1; + + const create = requireWasmHash(); + + //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1 + const xxhash64 = new WebAssembly.Module( + Buffer.from( + // 1173 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", + "base64" + ) + ); + //#endregion + + xxhash64_1 = create.bind(null, xxhash64, [], 32, 16); + return xxhash64_1; +} + +const baseEncodeTables = { + 26: "abcdefghijklmnopqrstuvwxyz", + 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio + 36: "0123456789abcdefghijklmnopqrstuvwxyz", + 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO + 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", + 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO + 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", + 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_", +}; + +/** + * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian + * @param {number} divisor The divisor + * @return {number} Modulo (remainder) of the division + */ +function divmod32(uint32Array, divisor) { + let carry = 0; + for (let i = uint32Array.length - 1; i >= 0; i--) { + const value = carry * 0x100000000 + uint32Array[i]; + carry = value % divisor; + uint32Array[i] = Math.floor(value / divisor); + } + return carry; +} + +function encodeBufferToBase(buffer, base, length) { + const encodeTable = baseEncodeTables[base]; + + if (!encodeTable) { + throw new Error("Unknown encoding base" + base); + } + + // Input bits are only enough to generate this many characters + const limit = Math.ceil((buffer.length * 8) / Math.log2(base)); + length = Math.min(length, limit); + + // Most of the crypto digests (if not all) has length a multiple of 4 bytes. + // Fewer numbers in the array means faster math. + const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4)); + + // Make sure the input buffer data is copied and is not mutated by reference. + // divmod32() would corrupt the BulkUpdateDecorator cache otherwise. + buffer.copy(Buffer.from(uint32Array.buffer)); + + let output = ""; + + for (let i = 0; i < length; i++) { + output = encodeTable[divmod32(uint32Array, base)] + output; + } + + return output; +} + +let crypto = undefined; +let createXXHash64 = undefined; +let createMd4 = undefined; +let BatchedHash = undefined; +let BulkUpdateDecorator = undefined; + +function getHashDigest$1(buffer, algorithm, digestType, maxLength) { + algorithm = algorithm || "xxhash64"; + maxLength = maxLength || 9999; + + let hash; + + if (algorithm === "xxhash64") { + if (createXXHash64 === undefined) { + createXXHash64 = requireXxhash64(); + + if (BatchedHash === undefined) { + BatchedHash = requireBatchedHash(); + } + } + + hash = new BatchedHash(createXXHash64()); + } else if (algorithm === "md4") { + if (createMd4 === undefined) { + createMd4 = requireMd4(); + + if (BatchedHash === undefined) { + BatchedHash = requireBatchedHash(); + } + } + + hash = new BatchedHash(createMd4()); + } else if (algorithm === "native-md4") { + if (typeof crypto === "undefined") { + crypto = require$$0$2; + + if (BulkUpdateDecorator === undefined) { + BulkUpdateDecorator = requireBulkUpdateDecorator(); + } + } + + hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4"); + } else { + if (typeof crypto === "undefined") { + crypto = require$$0$2; + + if (BulkUpdateDecorator === undefined) { + BulkUpdateDecorator = requireBulkUpdateDecorator(); + } + } + + hash = new BulkUpdateDecorator( + () => crypto.createHash(algorithm), + algorithm + ); + } + + hash.update(buffer); + + if ( + digestType === "base26" || + digestType === "base32" || + digestType === "base36" || + digestType === "base49" || + digestType === "base52" || + digestType === "base58" || + digestType === "base62" + ) { + return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength); + } else { + return hash.digest(digestType || "hex").substr(0, maxLength); + } +} + +var getHashDigest_1 = getHashDigest$1; + +const path$1 = require$$0$1; +const getHashDigest = getHashDigest_1; + +function interpolateName$1(loaderContext, name, options = {}) { + let filename; + + const hasQuery = + loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1; + + if (typeof name === "function") { + filename = name( + loaderContext.resourcePath, + hasQuery ? loaderContext.resourceQuery : undefined + ); + } else { + filename = name || "[hash].[ext]"; + } + + const context = options.context; + const content = options.content; + const regExp = options.regExp; + + let ext = "bin"; + let basename = "file"; + let directory = ""; + let folder = ""; + let query = ""; + + if (loaderContext.resourcePath) { + const parsed = path$1.parse(loaderContext.resourcePath); + let resourcePath = loaderContext.resourcePath; + + if (parsed.ext) { + ext = parsed.ext.substr(1); + } + + if (parsed.dir) { + basename = parsed.name; + resourcePath = parsed.dir + path$1.sep; + } + + if (typeof context !== "undefined") { + directory = path$1 + .relative(context, resourcePath + "_") + .replace(/\\/g, "/") + .replace(/\.\.(\/)?/g, "_$1"); + directory = directory.substr(0, directory.length - 1); + } else { + directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1"); + } + + if (directory.length === 1) { + directory = ""; + } else if (directory.length > 1) { + folder = path$1.basename(directory); + } + } + + if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) { + query = loaderContext.resourceQuery; + + const hashIdx = query.indexOf("#"); + + if (hashIdx >= 0) { + query = query.substr(0, hashIdx); + } + } + + let url = filename; + + if (content) { + // Match hash template + url = url + // `hash` and `contenthash` are same in `loader-utils` context + // let's keep `hash` for backward compatibility + .replace( + /\[(?:([^:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi, + (all, hashType, digestType, maxLength) => + getHashDigest(content, hashType, digestType, parseInt(maxLength, 10)) + ); + } + + url = url + .replace(/\[ext\]/gi, () => ext) + .replace(/\[name\]/gi, () => basename) + .replace(/\[path\]/gi, () => directory) + .replace(/\[folder\]/gi, () => folder) + .replace(/\[query\]/gi, () => query); + + if (regExp && loaderContext.resourcePath) { + const match = loaderContext.resourcePath.match(new RegExp(regExp)); + + match && + match.forEach((matched, i) => { + url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched); + }); + } + + if ( + typeof loaderContext.options === "object" && + typeof loaderContext.options.customInterpolateName === "function" + ) { + url = loaderContext.options.customInterpolateName.call( + loaderContext, + url, + name, + options + ); + } + + return url; +} + +var interpolateName_1 = interpolateName$1; + +var interpolateName = interpolateName_1; +var path = require$$0$1; + +/** + * @param {string} pattern + * @param {object} options + * @param {string} options.context + * @param {string} options.hashPrefix + * @return {function} + */ +var genericNames = function createGenerator(pattern, options) { + options = options || {}; + var context = + options && typeof options.context === "string" + ? options.context + : process.cwd(); + var hashPrefix = + options && typeof options.hashPrefix === "string" ? options.hashPrefix : ""; + + /** + * @param {string} localName Usually a class name + * @param {string} filepath Absolute path + * @return {string} + */ + return function generate(localName, filepath) { + var name = pattern.replace(/\[local\]/gi, localName); + var loaderContext = { + resourcePath: filepath, + }; + + var loaderOptions = { + content: + hashPrefix + + path.relative(context, filepath).replace(/\\/g, "/") + + "\x00" + + localName, + context: context, + }; + + var genericName = interpolateName(loaderContext, name, loaderOptions); + return genericName + .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-") + .replace(/^((-?[0-9])|--)/, "_$1"); + }; +}; + +var src$2 = {exports: {}}; + +var dist = {exports: {}}; + +var processor = {exports: {}}; + +var parser = {exports: {}}; + +var root$1 = {exports: {}}; + +var container = {exports: {}}; + +var node$1 = {exports: {}}; + +var util = {}; + +var unesc = {exports: {}}; + +(function (module, exports) { + + 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; +} (unesc, unesc.exports)); + +var unescExports = unesc.exports; + +var getProp = {exports: {}}; + +(function (module, exports) { + + 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; +} (getProp, getProp.exports)); + +var getPropExports = getProp.exports; + +var ensureObject = {exports: {}}; + +(function (module, exports) { + + 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; +} (ensureObject, ensureObject.exports)); + +var ensureObjectExports = ensureObject.exports; + +var stripComments = {exports: {}}; + +(function (module, exports) { + + 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; +} (stripComments, stripComments.exports)); + +var stripCommentsExports = stripComments.exports; + +util.__esModule = true; +util.stripComments = util.ensureObject = util.getProp = util.unesc = void 0; + +var _unesc = _interopRequireDefault$3(unescExports); + +util.unesc = _unesc["default"]; + +var _getProp = _interopRequireDefault$3(getPropExports); + +util.getProp = _getProp["default"]; + +var _ensureObject = _interopRequireDefault$3(ensureObjectExports); + +util.ensureObject = _ensureObject["default"]; + +var _stripComments = _interopRequireDefault$3(stripCommentsExports); + +util.stripComments = _stripComments["default"]; + +function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _util = 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); 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; +} (node$1, node$1.exports)); + +var nodeExports = node$1.exports; + +var types = {}; + +types.__esModule = true; +types.UNIVERSAL = types.ATTRIBUTE = types.CLASS = types.COMBINATOR = types.COMMENT = types.ID = types.NESTING = types.PSEUDO = types.ROOT = types.SELECTOR = types.STRING = types.TAG = void 0; +var TAG = 'tag'; +types.TAG = TAG; +var STRING = 'string'; +types.STRING = STRING; +var SELECTOR = 'selector'; +types.SELECTOR = SELECTOR; +var ROOT = 'root'; +types.ROOT = ROOT; +var PSEUDO = 'pseudo'; +types.PSEUDO = PSEUDO; +var NESTING = 'nesting'; +types.NESTING = NESTING; +var ID = 'id'; +types.ID = ID; +var COMMENT = 'comment'; +types.COMMENT = COMMENT; +var COMBINATOR = 'combinator'; +types.COMBINATOR = COMBINATOR; +var CLASS = 'class'; +types.CLASS = CLASS; +var ATTRIBUTE = 'attribute'; +types.ATTRIBUTE = ATTRIBUTE; +var UNIVERSAL = 'universal'; +types.UNIVERSAL = UNIVERSAL; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _node = _interopRequireDefault(nodeExports); + + var types$1 = _interopRequireWildcard(types); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { 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."); } it = o[Symbol.iterator](); return it.next.bind(it); } + + 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); 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 || 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$1.ATTRIBUTE) { + return callback.call(_this2, selector); + } + }); + }; + + _proto.walkClasses = function walkClasses(callback) { + var _this3 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.CLASS) { + return callback.call(_this3, selector); + } + }); + }; + + _proto.walkCombinators = function walkCombinators(callback) { + var _this4 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.COMBINATOR) { + return callback.call(_this4, selector); + } + }); + }; + + _proto.walkComments = function walkComments(callback) { + var _this5 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.COMMENT) { + return callback.call(_this5, selector); + } + }); + }; + + _proto.walkIds = function walkIds(callback) { + var _this6 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.ID) { + return callback.call(_this6, selector); + } + }); + }; + + _proto.walkNesting = function walkNesting(callback) { + var _this7 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.NESTING) { + return callback.call(_this7, selector); + } + }); + }; + + _proto.walkPseudos = function walkPseudos(callback) { + var _this8 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.PSEUDO) { + return callback.call(_this8, selector); + } + }); + }; + + _proto.walkTags = function walkTags(callback) { + var _this9 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.TAG) { + return callback.call(_this9, selector); + } + }); + }; + + _proto.walkUniversals = function walkUniversals(callback) { + var _this10 = this; + + return this.walk(function (selector) { + if (selector.type === types$1.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; +} (container, container.exports)); + +var containerExports = container.exports; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _container = _interopRequireDefault(containerExports); + + var _types = 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); 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 || 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; +} (root$1, root$1.exports)); + +var rootExports = root$1.exports; + +var selector$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _container = _interopRequireDefault(containerExports); + + var _types = 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 || 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; +} (selector$1, selector$1.exports)); + +var selectorExports = selector$1.exports; + +var className$1 = {exports: {}}; + +/*! https://mths.be/cssesc v3.0.0 by @mathias */ + +var object = {}; +var hasOwnProperty$1 = 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$1.call(options, key) ? options[key] : defaults[key]; + } + return result; +}; + +var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; +var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; +var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; + +// 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'; + +var cssesc_1 = cssesc; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _cssesc = _interopRequireDefault(cssesc_1); + + var _util = util; + + var _node = _interopRequireDefault(nodeExports); + + var _types = 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); 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 || 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; +} (className$1, className$1.exports)); + +var classNameExports = className$1.exports; + +var comment$2 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _node = _interopRequireDefault(nodeExports); + + var _types = 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 || 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; +} (comment$2, comment$2.exports)); + +var commentExports = comment$2.exports; + +var id$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _node = _interopRequireDefault(nodeExports); + + var _types = 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 || 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; +} (id$1, id$1.exports)); + +var idExports = id$1.exports; + +var tag$1 = {exports: {}}; + +var namespace = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _cssesc = _interopRequireDefault(cssesc_1); + + var _util = util; + + var _node = _interopRequireDefault(nodeExports); + + 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); 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 || 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; +} (namespace, namespace.exports)); + +var namespaceExports = namespace.exports; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _namespace = _interopRequireDefault(namespaceExports); + + var _types = 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 || 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; +} (tag$1, tag$1.exports)); + +var tagExports = tag$1.exports; + +var string$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _node = _interopRequireDefault(nodeExports); + + var _types = 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 || 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; +} (string$1, string$1.exports)); + +var stringExports = string$1.exports; + +var pseudo$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _container = _interopRequireDefault(containerExports); + + var _types = 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 || 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; +} (pseudo$1, pseudo$1.exports)); + +var pseudoExports = pseudo$1.exports; + +var attribute$1 = {}; + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +var node = require$$0$3.deprecate; + +(function (exports) { + + exports.__esModule = true; + exports.unescapeValue = unescapeValue; + exports["default"] = void 0; + + var _cssesc = _interopRequireDefault(cssesc_1); + + var _unesc = _interopRequireDefault(unescExports); + + var _namespace = _interopRequireDefault(namespaceExports); + + var _types = 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); 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 || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + + var deprecate = node; + + var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/; + var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead."); + var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."); + var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now."); + + function unescapeValue(value) { + var deprecatedUsage = false; + var quoteMark = null; + var unescaped = value; + var m = unescaped.match(WRAPPED_IN_QUOTES); + + if (m) { + quoteMark = m[1]; + unescaped = m[2]; + } + + unescaped = (0, _unesc["default"])(unescaped); + + if (unescaped !== value) { + deprecatedUsage = true; + } + + return { + deprecatedUsage: 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; + } +} (attribute$1)); + +var universal$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _namespace = _interopRequireDefault(namespaceExports); + + var _types = 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 || 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; +} (universal$1, universal$1.exports)); + +var universalExports = universal$1.exports; + +var combinator$2 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _node = _interopRequireDefault(nodeExports); + + var _types = 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 || 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; +} (combinator$2, combinator$2.exports)); + +var combinatorExports = combinator$2.exports; + +var nesting$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _node = _interopRequireDefault(nodeExports); + + var _types = 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 || 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; +} (nesting$1, nesting$1.exports)); + +var nestingExports = nesting$1.exports; + +var sortAscending = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = sortAscending; + + function sortAscending(list) { + return list.sort(function (a, b) { + return a - b; + }); + } + module.exports = exports.default; +} (sortAscending, sortAscending.exports)); + +var sortAscendingExports = sortAscending.exports; + +var tokenize = {}; + +var tokenTypes = {}; + +tokenTypes.__esModule = true; +tokenTypes.combinator = tokenTypes.word = tokenTypes.comment = tokenTypes.str = tokenTypes.tab = tokenTypes.newline = tokenTypes.feed = tokenTypes.cr = tokenTypes.backslash = tokenTypes.bang = tokenTypes.slash = tokenTypes.doubleQuote = tokenTypes.singleQuote = tokenTypes.space = tokenTypes.greaterThan = tokenTypes.pipe = tokenTypes.equals = tokenTypes.plus = tokenTypes.caret = tokenTypes.tilde = tokenTypes.dollar = tokenTypes.closeSquare = tokenTypes.openSquare = tokenTypes.closeParenthesis = tokenTypes.openParenthesis = tokenTypes.semicolon = tokenTypes.colon = tokenTypes.comma = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0; +var ampersand = 38; // `&`.charCodeAt(0); + +tokenTypes.ampersand = ampersand; +var asterisk = 42; // `*`.charCodeAt(0); + +tokenTypes.asterisk = asterisk; +var at = 64; // `@`.charCodeAt(0); + +tokenTypes.at = at; +var comma = 44; // `,`.charCodeAt(0); + +tokenTypes.comma = comma; +var colon = 58; // `:`.charCodeAt(0); + +tokenTypes.colon = colon; +var semicolon = 59; // `;`.charCodeAt(0); + +tokenTypes.semicolon = semicolon; +var openParenthesis = 40; // `(`.charCodeAt(0); + +tokenTypes.openParenthesis = openParenthesis; +var closeParenthesis = 41; // `)`.charCodeAt(0); + +tokenTypes.closeParenthesis = closeParenthesis; +var openSquare = 91; // `[`.charCodeAt(0); + +tokenTypes.openSquare = openSquare; +var closeSquare = 93; // `]`.charCodeAt(0); + +tokenTypes.closeSquare = closeSquare; +var dollar = 36; // `$`.charCodeAt(0); + +tokenTypes.dollar = dollar; +var tilde = 126; // `~`.charCodeAt(0); + +tokenTypes.tilde = tilde; +var caret = 94; // `^`.charCodeAt(0); + +tokenTypes.caret = caret; +var plus = 43; // `+`.charCodeAt(0); + +tokenTypes.plus = plus; +var equals = 61; // `=`.charCodeAt(0); + +tokenTypes.equals = equals; +var pipe = 124; // `|`.charCodeAt(0); + +tokenTypes.pipe = pipe; +var greaterThan = 62; // `>`.charCodeAt(0); + +tokenTypes.greaterThan = greaterThan; +var space = 32; // ` `.charCodeAt(0); + +tokenTypes.space = space; +var singleQuote = 39; // `'`.charCodeAt(0); + +tokenTypes.singleQuote = singleQuote; +var doubleQuote = 34; // `"`.charCodeAt(0); + +tokenTypes.doubleQuote = doubleQuote; +var slash = 47; // `/`.charCodeAt(0); + +tokenTypes.slash = slash; +var bang = 33; // `!`.charCodeAt(0); + +tokenTypes.bang = bang; +var backslash = 92; // '\\'.charCodeAt(0); + +tokenTypes.backslash = backslash; +var cr = 13; // '\r'.charCodeAt(0); + +tokenTypes.cr = cr; +var feed = 12; // '\f'.charCodeAt(0); + +tokenTypes.feed = feed; +var newline = 10; // '\n'.charCodeAt(0); + +tokenTypes.newline = newline; +var tab = 9; // '\t'.charCodeAt(0); +// Expose aliases primarily for readability. + +tokenTypes.tab = tab; +var str = singleQuote; // No good single character representation! + +tokenTypes.str = str; +var comment$1 = -1; +tokenTypes.comment = comment$1; +var word = -2; +tokenTypes.word = word; +var combinator$1 = -3; +tokenTypes.combinator = combinator$1; + +(function (exports) { + + exports.__esModule = true; + exports["default"] = tokenize; + exports.FIELDS = void 0; + + var t = _interopRequireWildcard(tokenTypes); + + var _unescapable, _wordDelimiters; + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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]) ; 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; + } +} (tokenize)); + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _root = _interopRequireDefault(rootExports); + + var _selector = _interopRequireDefault(selectorExports); + + var _className = _interopRequireDefault(classNameExports); + + var _comment = _interopRequireDefault(commentExports); + + var _id = _interopRequireDefault(idExports); + + var _tag = _interopRequireDefault(tagExports); + + var _string = _interopRequireDefault(stringExports); + + var _pseudo = _interopRequireDefault(pseudoExports); + + var _attribute = _interopRequireWildcard(attribute$1); + + var _universal = _interopRequireDefault(universalExports); + + var _combinator = _interopRequireDefault(combinatorExports); + + var _nesting = _interopRequireDefault(nestingExports); + + var _sortAscending = _interopRequireDefault(sortAscendingExports); + + var _tokenize = _interopRequireWildcard(tokenize); + + var tokens = _interopRequireWildcard(tokenTypes); + + var types$1 = _interopRequireWildcard(types); + + var _util = util; + + var _WHITESPACE_TOKENS, _Object$assign; + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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); 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 + } + } + }); + 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) { + 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]]) ; 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]) + } + }); + 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.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); + } + }; + + _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$1.PSEUDO) { + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position - 1]) + } + }); + 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; +} (parser, parser.exports)); + +var parserExports = parser.exports; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _parser = _interopRequireDefault(parserExports); + + 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; +} (processor, processor.exports)); + +var processorExports = processor.exports; + +var selectors = {}; + +var constructors = {}; + +constructors.__esModule = true; +constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0; + +var _attribute = _interopRequireDefault$2(attribute$1); + +var _className = _interopRequireDefault$2(classNameExports); + +var _combinator = _interopRequireDefault$2(combinatorExports); + +var _comment = _interopRequireDefault$2(commentExports); + +var _id = _interopRequireDefault$2(idExports); + +var _nesting = _interopRequireDefault$2(nestingExports); + +var _pseudo = _interopRequireDefault$2(pseudoExports); + +var _root = _interopRequireDefault$2(rootExports); + +var _selector = _interopRequireDefault$2(selectorExports); + +var _string = _interopRequireDefault$2(stringExports); + +var _tag = _interopRequireDefault$2(tagExports); + +var _universal = _interopRequireDefault$2(universalExports); + +function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var attribute = function attribute(opts) { + return new _attribute["default"](opts); +}; + +constructors.attribute = attribute; + +var className = function className(opts) { + return new _className["default"](opts); +}; + +constructors.className = className; + +var combinator = function combinator(opts) { + return new _combinator["default"](opts); +}; + +constructors.combinator = combinator; + +var comment = function comment(opts) { + return new _comment["default"](opts); +}; + +constructors.comment = comment; + +var id = function id(opts) { + return new _id["default"](opts); +}; + +constructors.id = id; + +var nesting = function nesting(opts) { + return new _nesting["default"](opts); +}; + +constructors.nesting = nesting; + +var pseudo = function pseudo(opts) { + return new _pseudo["default"](opts); +}; + +constructors.pseudo = pseudo; + +var root = function root(opts) { + return new _root["default"](opts); +}; + +constructors.root = root; + +var selector = function selector(opts) { + return new _selector["default"](opts); +}; + +constructors.selector = selector; + +var string = function string(opts) { + return new _string["default"](opts); +}; + +constructors.string = string; + +var tag = function tag(opts) { + return new _tag["default"](opts); +}; + +constructors.tag = tag; + +var universal = function universal(opts) { + return new _universal["default"](opts); +}; + +constructors.universal = universal; + +var guards = {}; + +guards.__esModule = true; +guards.isNode = isNode; +guards.isPseudoElement = isPseudoElement; +guards.isPseudoClass = isPseudoClass; +guards.isContainer = isContainer; +guards.isNamespace = isNamespace; +guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = guards.isPseudo = guards.isNesting = guards.isIdentifier = guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0; + +var _types = 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); +guards.isAttribute = isAttribute; +var isClassName = isNodeType.bind(null, _types.CLASS); +guards.isClassName = isClassName; +var isCombinator = isNodeType.bind(null, _types.COMBINATOR); +guards.isCombinator = isCombinator; +var isComment = isNodeType.bind(null, _types.COMMENT); +guards.isComment = isComment; +var isIdentifier = isNodeType.bind(null, _types.ID); +guards.isIdentifier = isIdentifier; +var isNesting = isNodeType.bind(null, _types.NESTING); +guards.isNesting = isNesting; +var isPseudo = isNodeType.bind(null, _types.PSEUDO); +guards.isPseudo = isPseudo; +var isRoot = isNodeType.bind(null, _types.ROOT); +guards.isRoot = isRoot; +var isSelector = isNodeType.bind(null, _types.SELECTOR); +guards.isSelector = isSelector; +var isString = isNodeType.bind(null, _types.STRING); +guards.isString = isString; +var isTag = isNodeType.bind(null, _types.TAG); +guards.isTag = isTag; +var isUniversal = isNodeType.bind(null, _types.UNIVERSAL); +guards.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); +} + +(function (exports) { + + exports.__esModule = true; + + var _types = 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 = 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 = 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]; + }); +} (selectors)); + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + + var _processor = _interopRequireDefault(processorExports); + + var selectors$1 = _interopRequireWildcard(selectors); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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$1); + delete parser.__esModule; + var _default = parser; + exports["default"] = _default; + module.exports = exports.default; +} (dist, dist.exports)); + +var distExports = dist.exports; + +const selectorParser$1 = distExports; +const valueParser = lib; +const { extractICSS } = src$4; + +const isSpacing = (node) => node.type === "combinator" && node.value === " "; + +function normalizeNodeArray(nodes) { + const array = []; + + nodes.forEach((x) => { + if (Array.isArray(x)) { + normalizeNodeArray(x).forEach((item) => { + array.push(item); + }); + } else if (x) { + array.push(x); + } + }); + + if (array.length > 0 && isSpacing(array[array.length - 1])) { + array.pop(); + } + return array; +} + +function localizeNode(rule, mode, localAliasMap) { + const transform = (node, context) => { + if (context.ignoreNextSpacing && !isSpacing(node)) { + throw new Error("Missing whitespace after " + context.ignoreNextSpacing); + } + + if (context.enforceNoSpacing && isSpacing(node)) { + throw new Error("Missing whitespace before " + context.enforceNoSpacing); + } + + let newNodes; + + switch (node.type) { + case "root": { + let resultingGlobal; + + context.hasPureGlobals = false; + + newNodes = node.nodes.map((n) => { + const nContext = { + global: context.global, + lastWasSpacing: true, + hasLocals: false, + explicit: false, + }; + + n = transform(n, nContext); + + if (typeof resultingGlobal === "undefined") { + resultingGlobal = nContext.global; + } else if (resultingGlobal !== nContext.global) { + throw new Error( + 'Inconsistent rule global/local result in rule "' + + node + + '" (multiple selectors must result in the same mode for the rule)' + ); + } + + if (!nContext.hasLocals) { + context.hasPureGlobals = true; + } + + return n; + }); + + context.global = resultingGlobal; + + node.nodes = normalizeNodeArray(newNodes); + break; + } + case "selector": { + newNodes = node.map((childNode) => transform(childNode, context)); + + node = node.clone(); + node.nodes = normalizeNodeArray(newNodes); + break; + } + case "combinator": { + if (isSpacing(node)) { + if (context.ignoreNextSpacing) { + context.ignoreNextSpacing = false; + context.lastWasSpacing = false; + context.enforceNoSpacing = false; + return null; + } + context.lastWasSpacing = true; + return node; + } + break; + } + case "pseudo": { + let childContext; + const isNested = !!node.length; + const isScoped = node.value === ":local" || node.value === ":global"; + const isImportExport = + node.value === ":import" || node.value === ":export"; + + if (isImportExport) { + context.hasLocals = true; + // :local(.foo) + } else if (isNested) { + if (isScoped) { + if (node.nodes.length === 0) { + throw new Error(`${node.value}() can't be empty`); + } + + if (context.inside) { + throw new Error( + `A ${node.value} is not allowed inside of a ${context.inside}(...)` + ); + } + + childContext = { + global: node.value === ":global", + inside: node.value, + hasLocals: false, + explicit: true, + }; + + newNodes = node + .map((childNode) => transform(childNode, childContext)) + .reduce((acc, next) => acc.concat(next.nodes), []); + + if (newNodes.length) { + const { before, after } = node.spaces; + + const first = newNodes[0]; + const last = newNodes[newNodes.length - 1]; + + first.spaces = { before, after: first.spaces.after }; + last.spaces = { before: last.spaces.before, after }; + } + + node = newNodes; + + break; + } else { + childContext = { + global: context.global, + inside: context.inside, + lastWasSpacing: true, + hasLocals: false, + explicit: context.explicit, + }; + newNodes = node.map((childNode) => + transform(childNode, childContext) + ); + + node = node.clone(); + node.nodes = normalizeNodeArray(newNodes); + + if (childContext.hasLocals) { + context.hasLocals = true; + } + } + break; + + //:local .foo .bar + } else if (isScoped) { + if (context.inside) { + throw new Error( + `A ${node.value} is not allowed inside of a ${context.inside}(...)` + ); + } + + const addBackSpacing = !!node.spaces.before; + + context.ignoreNextSpacing = context.lastWasSpacing + ? node.value + : false; + + context.enforceNoSpacing = context.lastWasSpacing + ? false + : node.value; + + context.global = node.value === ":global"; + context.explicit = true; + + // because this node has spacing that is lost when we remove it + // we make up for it by adding an extra combinator in since adding + // spacing on the parent selector doesn't work + return addBackSpacing + ? selectorParser$1.combinator({ value: " " }) + : null; + } + break; + } + case "id": + case "class": { + if (!node.value) { + throw new Error("Invalid class or id selector syntax"); + } + + if (context.global) { + break; + } + + const isImportedValue = localAliasMap.has(node.value); + const isImportedWithExplicitScope = isImportedValue && context.explicit; + + if (!isImportedValue || isImportedWithExplicitScope) { + const innerNode = node.clone(); + innerNode.spaces = { before: "", after: "" }; + + node = selectorParser$1.pseudo({ + value: ":local", + nodes: [innerNode], + spaces: node.spaces, + }); + + context.hasLocals = true; + } + + break; + } + } + + context.lastWasSpacing = false; + context.ignoreNextSpacing = false; + context.enforceNoSpacing = false; + + return node; + }; + + const rootContext = { + global: mode === "global", + hasPureGlobals: false, + }; + + rootContext.selector = selectorParser$1((root) => { + transform(root, rootContext); + }).processSync(rule, { updateSelector: false, lossless: true }); + + return rootContext; +} + +function localizeDeclNode(node, context) { + switch (node.type) { + case "word": + if (context.localizeNextItem) { + if (!context.localAliasMap.has(node.value)) { + node.value = ":local(" + node.value + ")"; + context.localizeNextItem = false; + } + } + break; + + case "function": + if ( + context.options && + context.options.rewriteUrl && + node.value.toLowerCase() === "url" + ) { + node.nodes.map((nestedNode) => { + if (nestedNode.type !== "string" && nestedNode.type !== "word") { + return; + } + + let newUrl = context.options.rewriteUrl( + context.global, + nestedNode.value + ); + + switch (nestedNode.type) { + case "string": + if (nestedNode.quote === "'") { + newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'"); + } + + if (nestedNode.quote === '"') { + newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"'); + } + + break; + case "word": + newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1"); + break; + } + + nestedNode.value = newUrl; + }); + } + break; + } + return node; +} + +function isWordAFunctionArgument(wordNode, functionNode) { + return functionNode + ? functionNode.nodes.some( + (functionNodeChild) => + functionNodeChild.sourceIndex === wordNode.sourceIndex + ) + : false; +} + +function localizeDeclarationValues(localize, declaration, context) { + const valueNodes = valueParser(declaration.value); + + valueNodes.walk((node, index, nodes) => { + const subContext = { + options: context.options, + global: context.global, + localizeNextItem: localize && !context.global, + localAliasMap: context.localAliasMap, + }; + nodes[index] = localizeDeclNode(node, subContext); + }); + + declaration.value = valueNodes.toString(); +} + +function localizeDeclaration(declaration, context) { + const isAnimation = /animation$/i.test(declaration.prop); + + if (isAnimation) { + const validIdent = /^-?[_a-z][_a-z0-9-]*$/i; + + /* + The spec defines some keywords that you can use to describe properties such as the timing + function. These are still valid animation names, so as long as there is a property that accepts + a keyword, it is given priority. Only when all the properties that can take a keyword are + exhausted can the animation name be set to the keyword. I.e. + + animation: infinite infinite; + + The animation will repeat an infinite number of times from the first argument, and will have an + animation name of infinite from the second. + */ + const animationKeywords = { + $alternate: 1, + "$alternate-reverse": 1, + $backwards: 1, + $both: 1, + $ease: 1, + "$ease-in": 1, + "$ease-in-out": 1, + "$ease-out": 1, + $forwards: 1, + $infinite: 1, + $linear: 1, + $none: Infinity, // No matter how many times you write none, it will never be an animation name + $normal: 1, + $paused: 1, + $reverse: 1, + $running: 1, + "$step-end": 1, + "$step-start": 1, + $initial: Infinity, + $inherit: Infinity, + $unset: Infinity, + }; + let parsedAnimationKeywords = {}; + let stepsFunctionNode = null; + const valueNodes = valueParser(declaration.value).walk((node) => { + /* If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh. */ + if (node.type === "div") { + parsedAnimationKeywords = {}; + } + if (node.type === "function" && node.value.toLowerCase() === "steps") { + stepsFunctionNode = node; + } + const value = + node.type === "word" && + !isWordAFunctionArgument(node, stepsFunctionNode) + ? node.value.toLowerCase() + : null; + + let shouldParseAnimationName = false; + + if (value && validIdent.test(value)) { + if ("$" + value in animationKeywords) { + parsedAnimationKeywords["$" + value] = + "$" + value in parsedAnimationKeywords + ? parsedAnimationKeywords["$" + value] + 1 + : 0; + + shouldParseAnimationName = + parsedAnimationKeywords["$" + value] >= + animationKeywords["$" + value]; + } else { + shouldParseAnimationName = true; + } + } + + const subContext = { + options: context.options, + global: context.global, + localizeNextItem: shouldParseAnimationName && !context.global, + localAliasMap: context.localAliasMap, + }; + return localizeDeclNode(node, subContext); + }); + + declaration.value = valueNodes.toString(); + + return; + } + + const isAnimationName = /animation(-name)?$/i.test(declaration.prop); + + if (isAnimationName) { + return localizeDeclarationValues(true, declaration, context); + } + + const hasUrl = /url\(/i.test(declaration.value); + + if (hasUrl) { + return localizeDeclarationValues(false, declaration, context); + } +} + +src$2.exports = (options = {}) => { + if ( + options && + options.mode && + options.mode !== "global" && + options.mode !== "local" && + options.mode !== "pure" + ) { + throw new Error( + 'options.mode must be either "global", "local" or "pure" (default "local")' + ); + } + + const pureMode = options && options.mode === "pure"; + const globalMode = options && options.mode === "global"; + + return { + postcssPlugin: "postcss-modules-local-by-default", + prepare() { + const localAliasMap = new Map(); + + return { + Once(root) { + const { icssImports } = extractICSS(root, false); + + Object.keys(icssImports).forEach((key) => { + Object.keys(icssImports[key]).forEach((prop) => { + localAliasMap.set(prop, icssImports[key][prop]); + }); + }); + + root.walkAtRules((atRule) => { + if (/keyframes$/i.test(atRule.name)) { + const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec( + atRule.params + ); + const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec( + atRule.params + ); + + let globalKeyframes = globalMode; + + if (globalMatch) { + if (pureMode) { + throw atRule.error( + "@keyframes :global(...) is not allowed in pure mode" + ); + } + atRule.params = globalMatch[1]; + globalKeyframes = true; + } else if (localMatch) { + atRule.params = localMatch[0]; + globalKeyframes = false; + } else if (!globalMode) { + if (atRule.params && !localAliasMap.has(atRule.params)) { + atRule.params = ":local(" + atRule.params + ")"; + } + } + + atRule.walkDecls((declaration) => { + localizeDeclaration(declaration, { + localAliasMap, + options: options, + global: globalKeyframes, + }); + }); + } else if (atRule.nodes) { + atRule.nodes.forEach((declaration) => { + if (declaration.type === "decl") { + localizeDeclaration(declaration, { + localAliasMap, + options: options, + global: globalMode, + }); + } + }); + } + }); + + root.walkRules((rule) => { + if ( + rule.parent && + rule.parent.type === "atrule" && + /keyframes$/i.test(rule.parent.name) + ) { + // ignore keyframe rules + return; + } + + const context = localizeNode(rule, options.mode, localAliasMap); + + context.options = options; + context.localAliasMap = localAliasMap; + + if (pureMode && context.hasPureGlobals) { + throw rule.error( + 'Selector "' + + rule.selector + + '" is not pure ' + + "(pure selectors must contain at least one local class or id)" + ); + } + + rule.selector = context.selector; + + // Less-syntax mixins parse as rules with no nodes + if (rule.nodes) { + rule.nodes.forEach((declaration) => + localizeDeclaration(declaration, context) + ); + } + }); + }, + }; + }, + }; +}; +src$2.exports.postcss = true; + +var srcExports$1 = src$2.exports; + +const selectorParser = distExports; + +const hasOwnProperty = Object.prototype.hasOwnProperty; + +function getSingleLocalNamesForComposes(root) { + return root.nodes.map((node) => { + if (node.type !== "selector" || node.nodes.length !== 1) { + throw new Error( + `composition is only allowed when selector is single :local class name not in "${root}"` + ); + } + + node = node.nodes[0]; + + if ( + node.type !== "pseudo" || + node.value !== ":local" || + node.nodes.length !== 1 + ) { + throw new Error( + 'composition is only allowed when selector is single :local class name not in "' + + root + + '", "' + + node + + '" is weird' + ); + } + + node = node.first; + + if (node.type !== "selector" || node.length !== 1) { + throw new Error( + 'composition is only allowed when selector is single :local class name not in "' + + root + + '", "' + + node + + '" is weird' + ); + } + + node = node.first; + + if (node.type !== "class") { + // 'id' is not possible, because you can't compose ids + throw new Error( + 'composition is only allowed when selector is single :local class name not in "' + + root + + '", "' + + node + + '" is weird' + ); + } + + return node.value; + }); +} + +const whitespace = "[\\x20\\t\\r\\n\\f]"; +const unescapeRegExp = new RegExp( + "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", + "ig" +); + +function unescape(str) { + return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => { + const high = "0x" + escaped - 0x10000; + + // NaN means non-codepoint + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace + ? escaped + : high < 0 + ? // BMP codepoint + String.fromCharCode(high + 0x10000) + : // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00); + }); +} + +const plugin = (options = {}) => { + const generateScopedName = + (options && options.generateScopedName) || plugin.generateScopedName; + const generateExportEntry = + (options && options.generateExportEntry) || plugin.generateExportEntry; + const exportGlobals = options && options.exportGlobals; + + return { + postcssPlugin: "postcss-modules-scope", + Once(root, { rule }) { + const exports = Object.create(null); + + function exportScopedName(name, rawName) { + const scopedName = generateScopedName( + rawName ? rawName : name, + root.source.input.from, + root.source.input.css + ); + const exportEntry = generateExportEntry( + rawName ? rawName : name, + scopedName, + root.source.input.from, + root.source.input.css + ); + const { key, value } = exportEntry; + + exports[key] = exports[key] || []; + + if (exports[key].indexOf(value) < 0) { + exports[key].push(value); + } + + return scopedName; + } + + function localizeNode(node) { + switch (node.type) { + case "selector": + node.nodes = node.map(localizeNode); + return node; + case "class": + return selectorParser.className({ + value: exportScopedName( + node.value, + node.raws && node.raws.value ? node.raws.value : null + ), + }); + case "id": { + return selectorParser.id({ + value: exportScopedName( + node.value, + node.raws && node.raws.value ? node.raws.value : null + ), + }); + } + } + + throw new Error( + `${node.type} ("${node}") is not allowed in a :local block` + ); + } + + function traverseNode(node) { + switch (node.type) { + case "pseudo": + if (node.value === ":local") { + if (node.nodes.length !== 1) { + throw new Error('Unexpected comma (",") in :local block'); + } + + const selector = localizeNode(node.first); + // move the spaces that were around the psuedo selector to the first + // non-container node + selector.first.spaces = node.spaces; + + const nextNode = node.next(); + + if ( + nextNode && + nextNode.type === "combinator" && + nextNode.value === " " && + /\\[A-F0-9]{1,6}$/.test(selector.last.value) + ) { + selector.last.spaces.after = " "; + } + + node.replaceWith(selector); + + return; + } + /* falls through */ + case "root": + case "selector": { + node.each(traverseNode); + break; + } + case "id": + case "class": + if (exportGlobals) { + exports[node.value] = [node.value]; + } + break; + } + return node; + } + + // Find any :import and remember imported names + const importedNames = {}; + + root.walkRules(/^:import\(.+\)$/, (rule) => { + rule.walkDecls((decl) => { + importedNames[decl.prop] = true; + }); + }); + + // Find any :local selectors + root.walkRules((rule) => { + let parsedSelector = selectorParser().astSync(rule); + + rule.selector = traverseNode(parsedSelector.clone()).toString(); + + rule.walkDecls(/composes|compose-with/i, (decl) => { + const localNames = getSingleLocalNamesForComposes(parsedSelector); + const classes = decl.value.split(/\s+/); + + classes.forEach((className) => { + const global = /^global\(([^)]+)\)$/.exec(className); + + if (global) { + localNames.forEach((exportedName) => { + exports[exportedName].push(global[1]); + }); + } else if (hasOwnProperty.call(importedNames, className)) { + localNames.forEach((exportedName) => { + exports[exportedName].push(className); + }); + } else if (hasOwnProperty.call(exports, className)) { + localNames.forEach((exportedName) => { + exports[className].forEach((item) => { + exports[exportedName].push(item); + }); + }); + } else { + throw decl.error( + `referenced class name "${className}" in ${decl.prop} not found` + ); + } + }); + + decl.remove(); + }); + + // Find any :local values + rule.walkDecls((decl) => { + if (!/:local\s*\((.+?)\)/.test(decl.value)) { + return; + } + + let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/); + + tokens = tokens.map((token, idx) => { + if (idx === 0 || tokens[idx - 1] === ",") { + let result = token; + + const localMatch = /:local\s*\((.+?)\)/.exec(token); + + if (localMatch) { + const input = localMatch.input; + const matchPattern = localMatch[0]; + const matchVal = localMatch[1]; + const newVal = exportScopedName(matchVal); + + result = input.replace(matchPattern, newVal); + } else { + return token; + } + + return result; + } else { + return token; + } + }); + + decl.value = tokens.join(""); + }); + }); + + // Find any :local keyframes + root.walkAtRules(/keyframes$/i, (atRule) => { + const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params); + + if (!localMatch) { + return; + } + + atRule.params = exportScopedName(localMatch[1]); + }); + + // If we found any :locals, insert an :export rule + const exportedNames = Object.keys(exports); + + if (exportedNames.length > 0) { + const exportRule = rule({ selector: ":export" }); + + exportedNames.forEach((exportedName) => + exportRule.append({ + prop: exportedName, + value: exports[exportedName].join(" "), + raws: { before: "\n " }, + }) + ); + + root.append(exportRule); + } + }, + }; +}; + +plugin.postcss = true; + +plugin.generateScopedName = function (name, path) { + const sanitisedPath = path + .replace(/\.[^./\\]+$/, "") + .replace(/[\W_]+/g, "_") + .replace(/^_|_$/g, ""); + + return `_${sanitisedPath}__${name}`.trim(); +}; + +plugin.generateExportEntry = function (name, scopedName) { + return { + key: unescape(name), + value: unescape(scopedName), + }; +}; + +var src$1 = plugin; + +function hash(str) { + var hash = 5381, + i = str.length; + + while(i) { + hash = (hash * 33) ^ str.charCodeAt(--i); + } + + /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed + * integers. Since we want the results to be always positive, convert the + * signed int to an unsigned by doing an unsigned bitshift. */ + return hash >>> 0; +} + +var stringHash = hash; + +var src = {exports: {}}; + +const ICSSUtils = src$4; + +const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/; +const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/; +const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/; + +src.exports = (options) => { + let importIndex = 0; + const createImportedName = + (options && options.createImportedName) || + ((importName /*, path*/) => + `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`); + + return { + postcssPlugin: "postcss-modules-values", + prepare(result) { + const importAliases = []; + const definitions = {}; + + return { + Once(root, postcss) { + root.walkAtRules(/value/i, (atRule) => { + const matches = atRule.params.match(matchImports); + + if (matches) { + let [, /*match*/ aliases, path] = matches; + + // We can use constants for path names + if (definitions[path]) { + path = definitions[path]; + } + + const imports = aliases + .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1") + .split(/\s*,\s*/) + .map((alias) => { + const tokens = matchImport.exec(alias); + + if (tokens) { + const [, /*match*/ theirName, myName = theirName] = tokens; + const importedName = createImportedName(myName); + definitions[myName] = importedName; + return { theirName, importedName }; + } else { + throw new Error(`@import statement "${alias}" is invalid!`); + } + }); + + importAliases.push({ path, imports }); + + atRule.remove(); + + return; + } + + if (atRule.params.indexOf("@value") !== -1) { + result.warn("Invalid value definition: " + atRule.params); + } + + let [, key, value] = `${atRule.params}${atRule.raws.between}`.match( + matchValueDefinition + ); + + const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, ""); + + if (normalizedValue.length === 0) { + result.warn("Invalid value definition: " + atRule.params); + atRule.remove(); + + return; + } + + let isOnlySpace = /^\s+$/.test(normalizedValue); + + if (!isOnlySpace) { + value = value.trim(); + } + + // Add to the definitions, knowing that values can refer to each other + definitions[key] = ICSSUtils.replaceValueSymbols( + value, + definitions + ); + + atRule.remove(); + }); + + /* If we have no definitions, don't continue */ + if (!Object.keys(definitions).length) { + return; + } + + /* Perform replacements */ + ICSSUtils.replaceSymbols(root, definitions); + + /* We want to export anything defined by now, but don't add it to the CSS yet or it well get picked up by the replacement stuff */ + const exportDeclarations = Object.keys(definitions).map((key) => + postcss.decl({ + value: definitions[key], + prop: key, + raws: { before: "\n " }, + }) + ); + + /* Add export rules if any */ + if (exportDeclarations.length > 0) { + const exportRule = postcss.rule({ + selector: ":export", + raws: { after: "\n" }, + }); + + exportRule.append(exportDeclarations); + + root.prepend(exportRule); + } + + /* Add import rules */ + importAliases.reverse().forEach(({ path, imports }) => { + const importRule = postcss.rule({ + selector: `:import(${path})`, + raws: { after: "\n" }, + }); + + imports.forEach(({ theirName, importedName }) => { + importRule.append({ + value: theirName, + prop: importedName, + raws: { before: "\n " }, + }); + }); + + root.prepend(importRule); + }); + }, + }; + }, + }; +}; + +src.exports.postcss = true; + +var srcExports = src.exports; + +Object.defineProperty(scoping, "__esModule", { + value: true +}); +scoping.behaviours = void 0; +scoping.getDefaultPlugins = getDefaultPlugins; +scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour; +scoping.getScopedNameGenerator = getScopedNameGenerator; + +var _postcssModulesExtractImports = _interopRequireDefault$1(srcExports$2); + +var _genericNames = _interopRequireDefault$1(genericNames); + +var _postcssModulesLocalByDefault = _interopRequireDefault$1(srcExports$1); + +var _postcssModulesScope = _interopRequireDefault$1(src$1); + +var _stringHash = _interopRequireDefault$1(stringHash); + +var _postcssModulesValues = _interopRequireDefault$1(srcExports); + +function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const behaviours = { + LOCAL: "local", + GLOBAL: "global" +}; +scoping.behaviours = behaviours; + +function getDefaultPlugins({ + behaviour, + generateScopedName, + exportGlobals +}) { + const scope = (0, _postcssModulesScope.default)({ + generateScopedName, + exportGlobals + }); + const plugins = { + [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({ + mode: "local" + }), _postcssModulesExtractImports.default, scope], + [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({ + mode: "global" + }), _postcssModulesExtractImports.default, scope] + }; + return plugins[behaviour]; +} + +function isValidBehaviour(behaviour) { + return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1; +} + +function getDefaultScopeBehaviour(scopeBehaviour) { + return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL; +} + +function generateScopedNameDefault(name, filename, css) { + const i = css.indexOf(`.${name}`); + const lineNumber = css.substr(0, i).split(/[\r\n]/).length; + const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5); + return `_${name}_${hash}_${lineNumber}`; +} + +function getScopedNameGenerator(generateScopedName, hashPrefix) { + const scopedNameGenerator = generateScopedName || generateScopedNameDefault; + + if (typeof scopedNameGenerator === "function") { + return scopedNameGenerator; + } + + return (0, _genericNames.default)(scopedNameGenerator, { + context: process.cwd(), + hashPrefix: hashPrefix + }); +} + +Object.defineProperty(pluginFactory, "__esModule", { + value: true +}); +pluginFactory.makePlugin = makePlugin; + +var _postcss = _interopRequireDefault(require$$0); + +var _unquote = _interopRequireDefault(unquote$1); + +var _Parser = _interopRequireDefault(Parser$1); + +var _saveJSON = _interopRequireDefault(saveJSON$1); + +var _localsConvention = localsConvention; + +var _FileSystemLoader = _interopRequireDefault(FileSystemLoader$1); + +var _scoping = scoping; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const PLUGIN_NAME = "postcss-modules"; + +function isGlobalModule(globalModules, inputFile) { + return globalModules.some(regex => inputFile.match(regex)); +} + +function getDefaultPluginsList(opts, inputFile) { + const globalModulesList = opts.globalModulePaths || null; + const exportGlobals = opts.exportGlobals || false; + const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour); + const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix); + + if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) { + return (0, _scoping.getDefaultPlugins)({ + behaviour: _scoping.behaviours.GLOBAL, + generateScopedName, + exportGlobals + }); + } + + return (0, _scoping.getDefaultPlugins)({ + behaviour: defaultBehaviour, + generateScopedName, + exportGlobals + }); +} + +function getLoader(opts, plugins) { + const root = typeof opts.root === "undefined" ? "/" : opts.root; + return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve); +} + +function isOurPlugin(plugin) { + return plugin.postcssPlugin === PLUGIN_NAME; +} + +function makePlugin(opts) { + return { + postcssPlugin: PLUGIN_NAME, + + async OnceExit(css, { + result + }) { + const getJSON = opts.getJSON || _saveJSON.default; + const inputFile = css.source.input.file; + const pluginList = getDefaultPluginsList(opts, inputFile); + const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin)); + + if (resultPluginIndex === -1) { + throw new Error("Plugin missing from options."); + } + + const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex); + const loaderPlugins = [...earlierPlugins, ...pluginList]; + const loader = getLoader(opts, loaderPlugins); + + const fetcher = async (file, relativeTo, depTrace) => { + const unquoteFile = (0, _unquote.default)(file); + return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace); + }; + + const parser = new _Parser.default(fetcher); + await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, { + from: inputFile + }); + const out = loader.finalSource; + if (out) css.prepend(out); + + if (opts.localsConvention) { + const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile); + parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {}); + } + + result.messages.push({ + type: "export", + plugin: "postcss-modules", + exportTokens: parser.exportTokens + }); // getJSON may return a promise + + return getJSON(css.source.input.file, parser.exportTokens, result.opts.to); + } + + }; +} + +var _fs = require$$0__default; + +var _fs2 = fs; + +var _pluginFactory = pluginFactory; + +(0, _fs2.setFileSystem)({ + readFile: _fs.readFile, + writeFile: _fs.writeFile +}); + +build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts); + +var postcss = build.exports.postcss = true; + +var buildExports = build.exports; +var index = /*@__PURE__*/getDefaultExportFromCjs(buildExports); + +var index$1 = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + default: index, + postcss: postcss +}, [buildExports]); + +export { index$1 as i }; diff --git a/web/node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js b/web/node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js new file mode 100644 index 0000000000000000000000000000000000000000..741fe7a5e92ebbc1c38eb4044f73079f9bbdaeb4 --- /dev/null +++ b/web/node_modules/vite/dist/node/chunks/dep-jDlpJiMN.js @@ -0,0 +1,68234 @@ +import fs$l, { promises as promises$1 } from 'node:fs'; +import fsp from 'node:fs/promises'; +import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, dirname as dirname$2, join as join$2, extname as extname$1, relative as relative$2, basename as basename$2 } from 'node:path'; +import { fileURLToPath, URL as URL$3, parse as parse$i, pathToFileURL } from 'node:url'; +import { promisify as promisify$4, format as format$2, inspect } from 'node:util'; +import { performance } from 'node:perf_hooks'; +import { createRequire as createRequire$1, builtinModules } from 'node:module'; +import require$$0$3 from 'tty'; +import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep, normalize } from 'path'; +import esbuild, { transform as transform$1, formatMessages, build as build$3 } from 'esbuild'; +import * as require$$0$2 from 'fs'; +import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, readdirSync } from 'fs'; +import require$$0$5 from 'events'; +import require$$5 from 'assert'; +import { createServer as createServer$3, STATUS_CODES, get as get$2 } from 'node:http'; +import { createServer as createServer$2, get as get$1 } from 'node:https'; +import require$$0$6 from 'util'; +import require$$4$1 from 'net'; +import require$$0$9 from 'url'; +import require$$1 from 'http'; +import require$$0$7 from 'stream'; +import require$$2 from 'os'; +import require$$2$1 from 'child_process'; +import os$4 from 'node:os'; +import { exec } from 'node:child_process'; +import { createHash as createHash$2 } from 'node:crypto'; +import { promises } from 'node:dns'; +import { CLIENT_ENTRY, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, CSS_LANGS_RE, ESBUILD_MODULES_TARGET, SPECIAL_QUERY_RE, ENV_ENTRY, DEP_VERSION_RE, DEFAULT_MAIN_FIELDS, DEFAULT_EXTENSIONS, KNOWN_ASSET_TYPES, JS_TYPES_RE, METADATA_FILENAME, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, CLIENT_DIR, VERSION, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js'; +import require$$0$a from 'crypto'; +import require$$0$8, { createRequire as createRequire$2 } from 'module'; +import assert$1 from 'node:assert'; +import v8 from 'node:v8'; +import { Worker as Worker$1 } from 'node:worker_threads'; +import { Buffer as Buffer$1 } from 'node:buffer'; +import { EventEmitter as EventEmitter$4 } from 'node:events'; +import { parseAst, parseAstAsync } from 'rollup/parseAst'; +import * as qs from 'querystring'; +import readline from 'node:readline'; +import require$$0$b from 'zlib'; +import require$$0$c from 'buffer'; +import require$$1$1 from 'https'; +import require$$4$2 from 'tls'; +import zlib$1, { gzip } from 'node:zlib'; + +import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; +import { dirname as __cjs_dirname } from 'node:path'; +import { createRequire as __cjs_createRequire } from 'node:module'; + +const __filename = __cjs_fileURLToPath(import.meta.url); +const __dirname = __cjs_dirname(__filename); +const require = __cjs_createRequire(import.meta.url); +const __require = require; +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var picocolors = {exports: {}}; + +let tty = require$$0$3; + +let isColorSupported = + !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && + ("FORCE_COLOR" in process.env || + process.argv.includes("--color") || + process.platform === "win32" || + (tty.isatty(1) && process.env.TERM !== "dumb") || + "CI" in process.env); + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input; + let 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 start = string.substring(0, index) + replace; + let end = string.substring(index + close.length); + let nextIndex = end.indexOf(close); + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +}; + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}); + +picocolors.exports = createColors(); +picocolors.exports.createColors = createColors; + +var picocolorsExports = picocolors.exports; +var colors$1 = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); + +function matches$1(pattern, importee) { + if (pattern instanceof RegExp) { + return pattern.test(importee); + } + if (importee.length < pattern.length) { + return false; + } + if (importee === pattern) { + return true; + } + // eslint-disable-next-line prefer-template + return importee.startsWith(pattern + '/'); +} +function getEntries({ entries, customResolver }) { + if (!entries) { + return []; + } + const resolverFunctionFromOptions = resolveCustomResolver(customResolver); + if (Array.isArray(entries)) { + return entries.map((entry) => { + return { + find: entry.find, + replacement: entry.replacement, + resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions + }; + }); + } + return Object.entries(entries).map(([key, value]) => { + return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions }; + }); +} +function getHookFunction(hook) { + if (typeof hook === 'function') { + return hook; + } + if (hook && 'handler' in hook && typeof hook.handler === 'function') { + return hook.handler; + } + return null; +} +function resolveCustomResolver(customResolver) { + if (typeof customResolver === 'function') { + return customResolver; + } + if (customResolver) { + return getHookFunction(customResolver.resolveId); + } + return null; +} +function alias$1(options = {}) { + const entries = getEntries(options); + if (entries.length === 0) { + return { + name: 'alias', + resolveId: () => null + }; + } + return { + name: 'alias', + async buildStart(inputOptions) { + await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); })); + }, + resolveId(importee, importer, resolveOptions) { + // First match is supposed to be the correct one + const matchedEntry = entries.find((entry) => matches$1(entry.find, importee)); + if (!matchedEntry) { + return null; + } + const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement); + if (matchedEntry.resolverFunction) { + return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions); + } + return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => { + if (resolved) + return resolved; + if (!require$$0$4.isAbsolute(updatedId)) { + this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` + + `This will lead to duplicated modules for the same path. ` + + `To avoid duplicating modules, you should resolve to an absolute path.`); + } + return { id: updatedId }; + }); + } + }; +} + +// @ts-check +/** @typedef { import('estree').BaseNode} BaseNode */ + +/** @typedef {{ + skip: () => void; + remove: () => void; + replace: (node: BaseNode) => void; +}} WalkerContext */ + +let WalkerBase$1 = class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {BaseNode | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + * @param {BaseNode} node + */ + replace(parent, prop, index, node) { + if (parent) { + if (index !== null) { + parent[prop][index] = node; + } else { + parent[prop] = node; + } + } + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + */ + remove(parent, prop, index) { + if (parent) { + if (index !== null) { + parent[prop].splice(index, 1); + } else { + delete parent[prop]; + } + } + } +}; + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./walker.js').WalkerContext} WalkerContext */ + +/** @typedef {( + * this: WalkerContext, + * node: BaseNode, + * parent: BaseNode, + * key: string, + * index: number + * ) => void} SyncHandler */ + +let SyncWalker$1 = class SyncWalker extends WalkerBase$1 { + /** + * + * @param {SyncHandler} enter + * @param {SyncHandler} leave + */ + constructor(enter, leave) { + super(); + + /** @type {SyncHandler} */ + this.enter = enter; + + /** @type {SyncHandler} */ + this.leave = leave; + } + + /** + * + * @param {BaseNode} node + * @param {BaseNode} parent + * @param {string} [prop] + * @param {number} [index] + * @returns {BaseNode} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + for (const key in node) { + const value = node[key]; + + if (typeof value !== "object") { + continue; + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + if (value[i] !== null && typeof value[i].type === 'string') { + if (!this.visit(value[i], node, key, i)) { + // removed + i--; + } + } + } + } else if (value !== null && typeof value.type === "string") { + this.visit(value, node, key, null); + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +}; + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./sync.js').SyncHandler} SyncHandler */ +/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ + +/** + * + * @param {BaseNode} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {BaseNode} + */ +function walk$3(ast, { enter, leave }) { + const instance = new SyncWalker$1(enter, leave); + return instance.visit(ast, null); +} + +var utils$k = {}; + +const path$n = require$$0$4; +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$1 = `${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: STAR$1, + 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$1 = { + 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' +}; + +var constants$6 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + + // 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$n.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; + } +}; + +(function (exports) { + + const path = require$$0$4; + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$6; + + 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; + }; +} (utils$k)); + +const utils$j = utils$k; +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA: CHAR_COMMA$1, /* , */ + CHAR_DOT: CHAR_DOT$1, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ +} = constants$6; + +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$2 = (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$1) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE$1) { + 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$1 && 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$1) { + 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$1) { + 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$1) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + 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$1) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES$1) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + 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$j.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$j.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; +}; + +var scan_1 = scan$2; + +const constants$5 = constants$6; +const utils$i = utils$k; + +/** + * Constants + */ + +const { + MAX_LENGTH: MAX_LENGTH$1, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$5; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.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$h = (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$1, opts.maxLength) : MAX_LENGTH$1; + + 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$i.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants$5.globChars(win32); + const EXTGLOB_CHARS = constants$5.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$i.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$h(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$i.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$i.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$i.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$i.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$i.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$i.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$i.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$i.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$h.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + 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$i.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$5.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$i.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$3 = parse$h; + +const path$m = require$$0$4; +const scan$1 = scan_1; +const parse$g = parse_1$3; +const utils$h = utils$k; +const constants$4 = constants$6; +const isObject$3 = 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$5 = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch$5(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$3(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$h.isWindows(options); + const regex = isState + ? picomatch$5.compileRe(glob, options) + : picomatch$5.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$5(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch$5.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$5.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$h.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$5.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$5.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options); + return regex.test(path$m.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$5.isMatch = (str, patterns, options) => picomatch$5(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$5.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options)); + return parse$g(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$5.scan = (input, options) => scan$1(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$5.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$5.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$5.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$g.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse$g(input, options); + } + + return picomatch$5.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$5.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$5.constants = constants$4; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch$5; + +var picomatch$3 = picomatch_1; + +var picomatch$4 = /*@__PURE__*/getDefaultExportFromCjs(picomatch$3); + +const extractors = { + ArrayPattern(names, param) { + for (const element of param.elements) { + if (element) + extractors[element.type](names, element); + } + }, + AssignmentPattern(names, param) { + extractors[param.left.type](names, param.left); + }, + Identifier(names, param) { + names.push(param.name); + }, + MemberExpression() { }, + ObjectPattern(names, param) { + for (const prop of param.properties) { + // @ts-ignore Typescript reports that this is not a valid type + if (prop.type === 'RestElement') { + extractors.RestElement(names, prop); + } + else { + extractors[prop.value.type](names, prop.value); + } + } + }, + RestElement(names, param) { + extractors[param.argument.type](names, param.argument); + } +}; +const extractAssignedNames = function extractAssignedNames(param) { + const names = []; + extractors[param.type](names, param); + return names; +}; + +const blockDeclarations = { + const: true, + let: true +}; +let Scope$1 = class Scope { + constructor(options = {}) { + this.parent = options.parent; + this.isBlockScope = !!options.block; + this.declarations = Object.create(null); + if (options.params) { + options.params.forEach((param) => { + extractAssignedNames(param).forEach((name) => { + this.declarations[name] = true; + }); + }); + } + } + addDeclaration(node, isBlockDeclaration, isVar) { + if (!isBlockDeclaration && this.isBlockScope) { + // it's a `var` or function node, and this + // is a block scope, so we need to go up + this.parent.addDeclaration(node, isBlockDeclaration, isVar); + } + else if (node.id) { + extractAssignedNames(node.id).forEach((name) => { + this.declarations[name] = true; + }); + } + } + contains(name) { + return this.declarations[name] || (this.parent ? this.parent.contains(name) : false); + } +}; +const attachScopes = function attachScopes(ast, propertyName = 'scope') { + let scope = new Scope$1(); + walk$3(ast, { + enter(n, parent) { + const node = n; + // function foo () {...} + // class Foo {...} + if (/(Function|Class)Declaration/.test(node.type)) { + scope.addDeclaration(node, false, false); + } + // var foo = 1 + if (node.type === 'VariableDeclaration') { + const { kind } = node; + const isBlockDeclaration = blockDeclarations[kind]; + node.declarations.forEach((declaration) => { + scope.addDeclaration(declaration, isBlockDeclaration, true); + }); + } + let newScope; + // create new function scope + if (/Function/.test(node.type)) { + const func = node; + newScope = new Scope$1({ + parent: scope, + block: false, + params: func.params + }); + // named function expressions - the name is considered + // part of the function's scope + if (func.type === 'FunctionExpression' && func.id) { + newScope.addDeclaration(func, false, false); + } + } + // create new for scope + if (/For(In|Of)?Statement/.test(node.type)) { + newScope = new Scope$1({ + parent: scope, + block: true + }); + } + // create new block scope + if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) { + newScope = new Scope$1({ + parent: scope, + block: true + }); + } + // catch clause has its own block scope + if (node.type === 'CatchClause') { + newScope = new Scope$1({ + parent: scope, + params: node.param ? [node.param] : [], + block: true + }); + } + if (newScope) { + Object.defineProperty(node, propertyName, { + value: newScope, + configurable: true + }); + scope = newScope; + } + }, + leave(n) { + const node = n; + if (node[propertyName]) + scope = scope.parent; + } + }); + return scope; +}; + +// Helper since Typescript can't detect readonly arrays with Array.isArray +function isArray$1(arg) { + return Array.isArray(arg); +} +function ensureArray(thing) { + if (isArray$1(thing)) + return thing; + if (thing == null) + return []; + return [thing]; +} + +const normalizePath$5 = function normalizePath(filename) { + return filename.split(win32.sep).join(posix.sep); +}; + +function getMatcherString(id, resolutionBase) { + if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('**')) { + return normalizePath$5(id); + } + // resolve('') is valid and will default to process.cwd() + const basePath = normalizePath$5(resolve$3(resolutionBase || '')) + // escape all possible (posix + win) path characters that might interfere with regex + .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); + // Note that we use posix.join because: + // 1. the basePath has been normalized to use / + // 2. the incoming glob (id) matcher, also uses / + // otherwise Node will force backslash (\) on windows + return posix.join(basePath, normalizePath$5(id)); +} +const createFilter$1 = function createFilter(include, exclude, options) { + const resolutionBase = options && options.resolve; + const getMatcher = (id) => id instanceof RegExp + ? id + : { + test: (what) => { + // this refactor is a tad overly verbose but makes for easy debugging + const pattern = getMatcherString(id, resolutionBase); + const fn = picomatch$4(pattern, { dot: true }); + const result = fn(what); + return result; + } + }; + const includeMatchers = ensureArray(include).map(getMatcher); + const excludeMatchers = ensureArray(exclude).map(getMatcher); + return function result(id) { + if (typeof id !== 'string') + return false; + if (/\0/.test(id)) + return false; + const pathId = normalizePath$5(id); + for (let i = 0; i < excludeMatchers.length; ++i) { + const matcher = excludeMatchers[i]; + if (matcher.test(pathId)) + return false; + } + for (let i = 0; i < includeMatchers.length; ++i) { + const matcher = includeMatchers[i]; + if (matcher.test(pathId)) + return true; + } + return !includeMatchers.length; + }; +}; + +const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; +const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; +const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' ')); +forbiddenIdentifiers.add(''); +const makeLegalIdentifier = function makeLegalIdentifier(str) { + let identifier = str + .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) + .replace(/[^$_a-zA-Z0-9]/g, '_'); + if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) { + identifier = `_${identifier}`; + } + return identifier || '_'; +}; + +function stringify$8(obj) { + return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); +} +function serializeArray(arr, indent, baseIndent) { + let output = '['; + const separator = indent ? `\n${baseIndent}${indent}` : ''; + for (let i = 0; i < arr.length; i++) { + const key = arr[i]; + output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`; + } + return `${output}${indent ? `\n${baseIndent}` : ''}]`; +} +function serializeObject(obj, indent, baseIndent) { + let output = '{'; + const separator = indent ? `\n${baseIndent}${indent}` : ''; + const entries = Object.entries(obj); + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + const stringKey = makeLegalIdentifier(key) === key ? key : stringify$8(key); + output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`; + } + return `${output}${indent ? `\n${baseIndent}` : ''}}`; +} +function serialize(obj, indent, baseIndent) { + if (typeof obj === 'object' && obj !== null) { + if (Array.isArray(obj)) + return serializeArray(obj, indent, baseIndent); + if (obj instanceof Date) + return `new Date(${obj.getTime()})`; + if (obj instanceof RegExp) + return obj.toString(); + return serializeObject(obj, indent, baseIndent); + } + if (typeof obj === 'number') { + if (obj === Infinity) + return 'Infinity'; + if (obj === -Infinity) + return '-Infinity'; + if (obj === 0) + return 1 / obj === Infinity ? '0' : '-0'; + if (obj !== obj) + return 'NaN'; // eslint-disable-line no-self-compare + } + if (typeof obj === 'symbol') { + const key = Symbol.keyFor(obj); + // eslint-disable-next-line no-undefined + if (key !== undefined) + return `Symbol.for(${stringify$8(key)})`; + } + if (typeof obj === 'bigint') + return `${obj}n`; + return stringify$8(obj); +} +// isWellFormed exists from Node.js 20 +const hasStringIsWellFormed = 'isWellFormed' in String.prototype; +function isWellFormedString(input) { + // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6 + if (hasStringIsWellFormed) + return input.isWellFormed(); + // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm + return !/\p{Surrogate}/u.test(input); +} +const dataToEsm = function dataToEsm(data, options = {}) { + var _a, _b; + const t = options.compact ? '' : 'indent' in options ? options.indent : '\t'; + const _ = options.compact ? '' : ' '; + const n = options.compact ? '' : '\n'; + const declarationType = options.preferConst ? 'const' : 'var'; + if (options.namedExports === false || + typeof data !== 'object' || + Array.isArray(data) || + data instanceof Date || + data instanceof RegExp || + data === null) { + const code = serialize(data, options.compact ? null : t, ''); + const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape + return `export default${magic}${code};`; + } + let maxUnderbarPrefixLength = 0; + for (const key of Object.keys(data)) { + const underbarPrefixLength = (_b = (_a = key.match(/^(_+)/)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0; + if (underbarPrefixLength > maxUnderbarPrefixLength) { + maxUnderbarPrefixLength = underbarPrefixLength; + } + } + const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`; + let namedExportCode = ''; + const defaultExportRows = []; + const arbitraryNameExportRows = []; + for (const [key, value] of Object.entries(data)) { + if (key === makeLegalIdentifier(key)) { + if (options.objectShorthand) + defaultExportRows.push(key); + else + defaultExportRows.push(`${key}:${_}${key}`); + namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; + } + else { + defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`); + if (options.includeArbitraryNames && isWellFormedString(key)) { + const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`; + namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; + arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`); + } + } + } + const arbitraryExportCode = arbitraryNameExportRows.length > 0 + ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` + : ''; + const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`; + return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`; +}; + +var path$l = require$$0$4; + +var commondir = function (basedir, relfiles) { + if (relfiles) { + var files = relfiles.map(function (r) { + return path$l.resolve(basedir, r); + }); + } + else { + var files = basedir; + } + + var res = files.slice(1).reduce(function (ps, file) { + if (!file.match(/^([A-Za-z]:)?\/|\\/)) { + throw new Error('relative path without a basedir'); + } + + var xs = file.split(/\/+|\\+/); + for ( + var i = 0; + ps[i] === xs[i] && i < Math.min(ps.length, xs.length); + i++ + ); + return ps.slice(0, i); + }, files[0].split(/\/+|\\+/)); + + // Windows correctly handles paths with forward-slashes + return res.length > 1 ? res.join('/') : '/' +}; + +var getCommonDir = /*@__PURE__*/getDefaultExportFromCjs(commondir); + +var old$1 = {}; + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var pathModule = require$$0$4; +var isWindows$5 = process.platform === 'win32'; +var fs$k = require$$0__default; + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG$1) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows$5) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows$5) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +old$1.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows$5 && !knownHard[base]) { + fs$k.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs$k.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows$5) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs$k.statSync(base); + linkTarget = fs$k.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows$5) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +old$1.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows$5 && !knownHard[base]) { + fs$k.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs$k.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows$5) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs$k.stat(base, function(err) { + if (err) return cb(err); + + fs$k.readlink(base, function(err, target) { + if (!isWindows$5) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + +var fs_realpath = realpath$2; +realpath$2.realpath = realpath$2; +realpath$2.sync = realpathSync; +realpath$2.realpathSync = realpathSync; +realpath$2.monkeypatch = monkeypatch; +realpath$2.unmonkeypatch = unmonkeypatch; + +var fs$j = require$$0__default; +var origRealpath = fs$j.realpath; +var origRealpathSync = fs$j.realpathSync; + +var version$4 = process.version; +var ok = /^v[0-5]\./.test(version$4); +var old = old$1; + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath$2 (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache; + cache = null; + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb); + } else { + cb(er, result); + } + }); +} + +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs$j.realpath = realpath$2; + fs$j.realpathSync = realpathSync; +} + +function unmonkeypatch () { + fs$j.realpath = origRealpath; + fs$j.realpathSync = origRealpathSync; +} + +const isWindows$4 = typeof process === 'object' && + process && + process.platform === 'win32'; +var path$k = isWindows$4 ? { sep: '\\' } : { sep: '/' }; + +var balancedMatch = balanced$1; +function balanced$1(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range$1(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$1.range = range$1; +function range$1(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; +} + +var balanced = balancedMatch; + +var braceExpansion = 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$4(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$4(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$4(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$4(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$4(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$4(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; +} + +const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => { + assertValidPattern(pattern); + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch$1(pattern, options).match(p) +}; + +var minimatch_1 = minimatch$1; + +const path$j = path$k; +minimatch$1.sep = path$j.sep; + +const GLOBSTAR$2 = Symbol('globstar **'); +minimatch$1.GLOBSTAR = GLOBSTAR$2; +const expand$3 = braceExpansion; + +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +}; + +// any single thing other than / +// don't need to escape / when using new RegExp() +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 = '(?:(?!(?:\\\/|^)\\.).)*?'; + +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true; + return set +}, {}); + +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!'); + +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.('); + +// normalizes slashes. +const slashSplit = /\/+/; + +minimatch$1.filter = (pattern, options = {}) => + (p, i, list) => minimatch$1(p, pattern, options); + +const ext = (a, b = {}) => { + const t = {}; + Object.keys(a).forEach(k => t[k] = a[k]); + Object.keys(b).forEach(k => t[k] = b[k]); + return t +}; + +minimatch$1.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch$1 + } + + const orig = minimatch$1; + + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)); + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)); + } + }; + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch; + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)); + m.defaults = options => orig.defaults(ext(def, options)); + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)); + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)); + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)); + + return m +}; + + + + + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options); + +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$3(pattern) +}; + +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') + } +}; + +// 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 SUBPARSE = Symbol('subparse'); + +minimatch$1.makeRe = (pattern, options) => + new Minimatch$1(pattern, options || {}).makeRe(); + +minimatch$1.match = (list, pattern, options = {}) => { + const mm = new Minimatch$1(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list +}; + +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1'); +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1'); +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&'); + +let Minimatch$1 = class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern); + + if (!options) options = {}; + + this.options = options; + this.set = []; + this.pattern = pattern; + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); + } + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + + // make the set of regexps etc. + this.make(); + } + + 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 + let set = this.globSet = this.braceExpand(); + + if (options.debug) this.debug = (...args) => console.error(...args); + + this.debug(this.pattern, set); + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)); + + this.debug(this.pattern, set); + + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)); + + this.debug(this.pattern, set); + + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1); + + this.debug(this.pattern, set); + + this.set = set; + } + + parseNegate () { + if (this.options.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) { + var options = this.options; + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }); + + this.debug('matchOne', file.length, pattern.length); + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + + this.debug(pattern, p, f); + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR$2) { + this.debug('GLOBSTAR', [pattern, p, f]); + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug('** at the end'); + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr]; + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr); + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit; + if (typeof p === 'string') { + hit = f === p; + this.debug('string match', p, f, hit); + } else { + hit = f.match(p); + this.debug('pattern match', p, f, hit); + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore 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] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } + + braceExpand () { + return braceExpand(this.pattern, this.options) + } + + parse (pattern, isSub) { + assertValidPattern(pattern); + + const options = this.options; + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR$2 + else + pattern = '*'; + } + if (pattern === '') return '' + + let re = ''; + let hasMagic = false; + let escaping = false; + // ? => one single character + const patternListStack = []; + const negativeLists = []; + let stateChar; + let inClass = false; + let reClassStart = -1; + let classStart = -1; + let cs; + let pl; + let sp; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.'; + let dotFileAllowed = options.dot || dotTravAllowed; + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + + + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break + case '?': + re += qmark; + hasMagic = true; + break + default: + re += '\\' + stateChar; + break + } + this.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + }; + + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } + + if (reSpecials[c]) { + re += '\\'; + } + re += c; + escaping = false; + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } + + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c; + continue + } + + clearStateChar(); + escaping = true; + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) c = '^'; + re += c; + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar(); + continue + + case '(': { + if (inClass) { + re += '('; + continue + } + + if (!stateChar) { + re += '\\('; + continue + } + + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + }; + this.debug(this.pattern, '\t', plEntry); + patternListStack.push(plEntry); + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open; + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue + } + + case ')': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\)'; + continue + } + patternListStack.pop(); + + // closing an extglob + clearStateChar(); + hasMagic = true; + pl = plEntry; + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close; + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })); + } + continue + } + + case '|': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\|'; + continue + } + + clearStateChar(); + re += '|'; + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + continue + } + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + + if (inClass) { + re += '\\' + c; + continue + } + + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + continue + } + + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']'); + // looks good, finish up the class. + re += c; + } catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)'; // match nothing ever + } + hasMagic = true; + inClass = false; + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + break + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substring(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail; + tail = re.slice(pl.reStart + pl.open.length); + this.debug('setting tail', re, pl); + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }); + + this.debug('tail=%j\n %s', tail, tail, pl, re); + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type; + + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } + + // handle trailing things that only matter at the very end. + clearStateChar(); + if (escaping) { + // trailing \\ + re += '\\\\'; + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)]; + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n]; + + const nlBefore = re.slice(0, nl.reStart); + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + let nlAfter = re.slice(nl.reEnd); + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length; + const openParensBefore = nlBefore.split('(').length - closeParensBefore; + let cleanAfter = nlAfter; + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : ''; + + re = nlBefore + nlFirst + nlAfter + dollar + nlLast; + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + + if (addPatternStart) { + re = patternStart() + re; + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase(); + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + const flags = options.nocase ? 'i' : ''; + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + } + + 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 = options.nocase ? 'i' : ''; + + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR$2 ? GLOBSTAR$2 + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR$2 && p === GLOBSTAR$2)) { + set.push(p); + } + return set + }, []); + pattern.forEach((p, i) => { + if (p !== GLOBSTAR$2 || pattern[i-1] === GLOBSTAR$2) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]; + } else { + pattern[i] = twoStar; + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?'; + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]; + pattern[i+1] = GLOBSTAR$2; + } + }); + return pattern.filter(p => p !== GLOBSTAR$2).join('/') + }).join('|'); + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$'; + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$'; + + try { + this.regexp = new RegExp(re, flags); + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false; + } + return this.regexp + } + + 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 (path$j.sep !== '/') { + f = f.split(path$j.sep).join('/'); + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit); + this.debug(this.pattern, 'split', f); + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + 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; + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break + } + + for (let i = 0; i < set.length; i++) { + const pattern = set[i]; + let file = f; + 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$1.defaults(def).Minimatch + } +}; + +minimatch$1.Minimatch = Minimatch$1; + +var inherits = {exports: {}}; + +var inherits_browser = {exports: {}}; + +var hasRequiredInherits_browser; + +function requireInherits_browser () { + if (hasRequiredInherits_browser) return inherits_browser.exports; + hasRequiredInherits_browser = 1; + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + // old school shim for old browsers + inherits_browser.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + return inherits_browser.exports; +} + +try { + var util$2 = require('util'); + /* istanbul ignore next */ + if (typeof util$2.inherits !== 'function') throw ''; + inherits.exports = util$2.inherits; +} catch (e) { + /* istanbul ignore next */ + inherits.exports = requireInherits_browser(); +} + +var inheritsExports = inherits.exports; + +var common$c = {}; + +common$c.setopts = setopts; +common$c.ownProp = ownProp; +common$c.makeAbs = makeAbs; +common$c.finish = finish; +common$c.mark = mark; +common$c.isIgnored = isIgnored; +common$c.childrenIgnored = childrenIgnored; + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var fs$i = require$$0__default; +var path$i = require$$0$4; +var minimatch = minimatch_1; +var isAbsolute = require$$0$4.isAbsolute; +var Minimatch = minimatch.Minimatch; + +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || []; + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore]; + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap); + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null; + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, ''); + gmatcher = new Minimatch(gpattern, { dot: true }); + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {}; + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern; + } + + self.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false; + if (self.windowsPathsNoEscape) { + pattern = pattern.replace(/\\/g, '/'); + } + + self.silent = !!options.silent; + self.pattern = pattern; + self.strict = options.strict !== false; + self.realpath = !!options.realpath; + self.realpathCache = options.realpathCache || Object.create(null); + self.follow = !!options.follow; + self.dot = !!options.dot; + self.mark = !!options.mark; + self.nodir = !!options.nodir; + if (self.nodir) + self.mark = true; + self.sync = !!options.sync; + self.nounique = !!options.nounique; + self.nonull = !!options.nonull; + self.nosort = !!options.nosort; + self.nocase = !!options.nocase; + self.stat = !!options.stat; + self.noprocess = !!options.noprocess; + self.absolute = !!options.absolute; + self.fs = options.fs || fs$i; + + self.maxLength = options.maxLength || Infinity; + self.cache = options.cache || Object.create(null); + self.statCache = options.statCache || Object.create(null); + self.symlinks = options.symlinks || Object.create(null); + + setupIgnores(self, options); + + self.changedCwd = false; + var cwd = process.cwd(); + if (!ownProp(options, "cwd")) + self.cwd = path$i.resolve(cwd); + else { + self.cwd = path$i.resolve(options.cwd); + self.changedCwd = self.cwd !== cwd; + } + + self.root = options.root || path$i.resolve(self.cwd, "/"); + self.root = path$i.resolve(self.root); + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); + self.nomount = !!options.nomount; + + if (process.platform === "win32") { + self.root = self.root.replace(/\\/g, "/"); + self.cwd = self.cwd.replace(/\\/g, "/"); + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); + } + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true; + options.nocomment = true; + + self.minimatch = new Minimatch(pattern, options); + self.options = self.minimatch.options; +} + +function finish (self) { + var nou = self.nounique; + var all = nou ? [] : Object.create(null); + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i]; + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i]; + if (nou) + all.push(literal); + else + all[literal] = true; + } + } else { + // had matches + var m = Object.keys(matches); + if (nou) + all.push.apply(all, m); + else + m.forEach(function (m) { + all[m] = true; + }); + } + } + + if (!nou) + all = Object.keys(all); + + if (!self.nosort) + all = all.sort(alphasort); + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]); + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)); + var c = self.cache[e] || self.cache[makeAbs(self, e)]; + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c); + return notDir + }); + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }); + + self.found = all; +} + +function mark (self, p) { + var abs = makeAbs(self, p); + var c = self.cache[abs]; + var m = p; + if (c) { + var isDir = c === 'DIR' || Array.isArray(c); + var slash = p.slice(-1) === '/'; + + if (isDir && !slash) + m += '/'; + else if (!isDir && slash) + m = m.slice(0, -1); + + if (m !== p) { + var mabs = makeAbs(self, m); + self.statCache[mabs] = self.statCache[abs]; + self.cache[mabs] = self.cache[abs]; + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f; + if (f.charAt(0) === '/') { + abs = path$i.join(self.root, f); + } else if (isAbsolute(f) || f === '') { + abs = f; + } else if (self.changedCwd) { + abs = path$i.resolve(self.cwd, f); + } else { + abs = path$i.resolve(f); + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/'); + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +var sync$9; +var hasRequiredSync; + +function requireSync () { + if (hasRequiredSync) return sync$9; + hasRequiredSync = 1; + sync$9 = globSync; + globSync.GlobSync = GlobSync; + + var rp = fs_realpath; + var minimatch = minimatch_1; + requireGlob().Glob; + var path = require$$0$4; + var assert = require$$5; + var isAbsolute = require$$0$4.isAbsolute; + var common = common$c; + var setopts = common.setopts; + var ownProp = common.ownProp; + var childrenIgnored = common.childrenIgnored; + var isIgnored = common.isIgnored; + + function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found + } + + function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options); + + if (this.noprocess) + return this + + var n = this.minimatch.set.length; + this.matches = new Array(n); + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false); + } + this._finish(); + } + + GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync); + if (this.realpath) { + var self = this; + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null); + for (var p in matchset) { + try { + p = self._makeAbs(p); + var real = rp.realpathSync(p, self.realpathCache); + set[real] = true; + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true; + else + throw er + } + } + }); + } + common.finish(this); + }; + + + GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync); + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar); + }; + + + GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar); + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + var newPattern; + if (prefix) + newPattern = [prefix, e]; + else + newPattern = [e]; + this._process(newPattern.concat(remain), index, inGlobStar); + } + }; + + + GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) { + e = abs; + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + if (this.stat) + this._stat(e); + }; + + + GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries; + var lstat; + try { + lstat = this.fs.lstatSync(abs); + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink(); + this.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE'; + else + entries = this._readdir(abs, false); + + return entries + }; + + GlobSync.prototype._readdir = function (abs, inGlobStar) { + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er); + return null + } + }; + + GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + + // mark and cache dir-ness + return entries + }; + + GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er); + break + } + }; + + GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar); + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false); + + var len = entries.length; + var isSym = this.symlinks[abs]; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true); + } + }; + + GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix); + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix); + } else { + prefix = path.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + }; + + // Returns either 'DIR', 'FILE', or false + GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (!stat) { + var lstat; + try { + lstat = this.fs.lstatSync(abs); + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs); + } catch (er) { + stat = lstat; + } + } else { + stat = lstat; + } + } + + this.statCache[abs] = stat; + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return false + + return c + }; + + GlobSync.prototype._mark = function (p) { + return common.mark(this, p) + }; + + GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) + }; + return sync$9; +} + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +var wrappy_1 = wrappy$2; +function wrappy$2 (fn, cb) { + if (fn && cb) return wrappy$2(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); + + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret + } +} + +var once$2 = {exports: {}}; + +var wrappy$1 = wrappy_1; +once$2.exports = wrappy$1(once$1); +once$2.exports.strict = wrappy$1(onceStrict); + +once$1.proto = once$1(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once$1(this) + }, + configurable: true + }); + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); +}); + +function once$1 (fn) { + var f = function () { + if (f.called) return f.value + f.called = true; + return f.value = fn.apply(this, arguments) + }; + f.called = false; + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true; + return f.value = fn.apply(this, arguments) + }; + var name = fn.name || 'Function wrapped with `once`'; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f +} + +var onceExports = once$2.exports; + +var wrappy = wrappy_1; +var reqs = Object.create(null); +var once = onceExports; + +var inflight_1 = wrappy(inflight); + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb); + return null + } else { + reqs[key] = [cb]; + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key]; + var len = cbs.length; + var args = slice$1(arguments); + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args); + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len); + process.nextTick(function () { + RES.apply(null, args); + }); + } else { + delete reqs[key]; + } + } + }) +} + +function slice$1 (args) { + var length = args.length; + var array = []; + + for (var i = 0; i < length; i++) array[i] = args[i]; + return array +} + +var glob_1; +var hasRequiredGlob; + +function requireGlob () { + if (hasRequiredGlob) return glob_1; + hasRequiredGlob = 1; + // Approach: + // + // 1. Get the minimatch set + // 2. For each pattern in the set, PROCESS(pattern, false) + // 3. Store matches per-set, then uniq them + // + // PROCESS(pattern, inGlobStar) + // Get the first [n] items from pattern that are all strings + // Join these together. This is PREFIX. + // If there is no more remaining, then stat(PREFIX) and + // add to matches if it succeeds. END. + // + // If inGlobStar and PREFIX is symlink and points to dir + // set ENTRIES = [] + // else readdir(PREFIX) as ENTRIES + // If fail, END + // + // with ENTRIES + // If pattern[n] is GLOBSTAR + // // handle the case where the globstar match is empty + // // by pruning it out, and testing the resulting pattern + // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) + // // handle other cases. + // for ENTRY in ENTRIES (not dotfiles) + // // attach globstar + tail onto the entry + // // Mark that this entry is a globstar match + // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) + // + // else // not globstar + // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) + // Test ENTRY against pattern[n] + // If fails, continue + // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) + // + // Caveat: + // Cache all stats and readdirs results to minimize syscall. Since all + // we ever care about is existence and directory-ness, we can just keep + // `true` for files, and [children,...] for directories, or `false` for + // things that don't exist. + + glob_1 = glob; + + var rp = fs_realpath; + var minimatch = minimatch_1; + var inherits = inheritsExports; + var EE = require$$0$5.EventEmitter; + var path = require$$0$4; + var assert = require$$5; + var isAbsolute = require$$0$4.isAbsolute; + var globSync = requireSync(); + var common = common$c; + var setopts = common.setopts; + var ownProp = common.ownProp; + var inflight = inflight_1; + var childrenIgnored = common.childrenIgnored; + var isIgnored = common.isIgnored; + + var once = onceExports; + + function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {}; + if (!options) options = {}; + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) + } + + glob.sync = globSync; + var GlobSync = glob.GlobSync = globSync.GlobSync; + + // old api surface + glob.glob = glob; + + function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin + } + + glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_); + options.noprocess = true; + + var g = new Glob(pattern, options); + var set = g.minimatch.set; + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false + }; + + glob.Glob = Glob; + inherits(Glob, EE); + function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options); + this._didRealPath = false; + + // process each pattern in the minimatch set + var n = this.minimatch.set.length; + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n); + + if (typeof cb === 'function') { + cb = once(cb); + this.on('error', cb); + this.on('end', function (matches) { + cb(null, matches); + }); + } + + var self = this; + this._processing = 0; + + this._emitQueue = []; + this._processQueue = []; + this.paused = false; + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true; + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done); + } + sync = false; + + function done () { + --self._processing; + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish(); + }); + } else { + self._finish(); + } + } + } + } + + Glob.prototype._finish = function () { + assert(this instanceof Glob); + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this); + this.emit('end', this.found); + }; + + Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true; + + var n = this.matches.length; + if (n === 0) + return this._finish() + + var self = this; + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next); + + function next () { + if (--n === 0) + self._finish(); + } + }; + + Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index]; + if (!matchset) + return cb() + + var found = Object.keys(matchset); + var self = this; + var n = found.length; + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null); + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p); + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true; + else if (er.syscall === 'stat') + set[p] = true; + else + self.emit('error', er); // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set; + cb(); + } + }); + }); + }; + + Glob.prototype._mark = function (p) { + return common.mark(this, p) + }; + + Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) + }; + + Glob.prototype.abort = function () { + this.aborted = true; + this.emit('abort'); + }; + + Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true; + this.emit('pause'); + } + }; + + Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume'); + this.paused = false; + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0); + this._emitQueue.length = 0; + for (var i = 0; i < eq.length; i ++) { + var e = eq[i]; + this._emitMatch(e[0], e[1]); + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0); + this._processQueue.length = 0; + for (var i = 0; i < pq.length; i ++) { + var p = pq[i]; + this._processing--; + this._process(p[0], p[1], p[2], p[3]); + } + } + } + }; + + Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob); + assert(typeof cb === 'function'); + + if (this.aborted) + return + + this._processing++; + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]); + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); + }; + + Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }); + }; + + Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + this._process([e].concat(remain), index, inGlobStar, cb); + } + cb(); + }; + + Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]); + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) + e = abs; + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + var st = this.statCache[abs]; + if (st) + this.emit('stat', e, st); + + this.emit('match', e); + }; + + Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs; + var self = this; + var lstatcb = inflight(lstatkey, lstatcb_); + + if (lstatcb) + self.fs.lstat(abs, lstatcb); + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink(); + self.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE'; + cb(); + } else + self._readdir(abs, false, cb); + } + }; + + Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb); + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this; + self.fs.readdir(abs, readdirCb(this, abs, cb)); + }; + + function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb); + else + self._readdirEntries(abs, entries, cb); + } + } + + Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + return cb(null, entries) + }; + + Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + this.emit('error', error); + this.abort(); + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) { + this.emit('error', er); + // If the error is handled, then we abort + // if not, we threw out of here + this.abort(); + } + if (!this.silent) + console.error('glob error', er); + break + } + + return cb() + }; + + Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); + }); + }; + + + Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb); + + var isSym = this.symlinks[abs]; + var len = entries.length; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true, cb); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true, cb); + } + + cb(); + }; + + Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this; + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb); + }); + }; + Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix); + } else { + prefix = path.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + cb(); + }; + + // Returns either 'DIR', 'FILE', or false + Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE'; + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this; + var statcb = inflight('stat\0' + abs, lstatcb_); + if (statcb) + self.fs.lstat(abs, statcb); + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb); + else + self._stat2(f, abs, er, stat, cb); + }) + } else { + self._stat2(f, abs, er, lstat, cb); + } + } + }; + + Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return cb() + } + + var needDir = f.slice(-1) === '/'; + this.statCache[abs] = stat; + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) + }; + return glob_1; +} + +var globExports = requireGlob(); +var glob$1 = /*@__PURE__*/getDefaultExportFromCjs(globExports); + +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars$1 = '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$1.length; i++) { + const c = chars$1.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const 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; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator$1); +} +function sortComparator$1(a, b) { + return a[0] - b[0]; +} +function encode$1(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + reset() { + this.intro = ''; + this.outro = ''; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa$1 = /*#__PURE__*/ getBtoa(); + +let SourceMap$1 = class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode$1(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); + } +}; + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString$2 = Object.prototype.toString; + +function isObject$2(thing) { + return toString$2.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n$1 = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap$1(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject$2(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + reset(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.reset(); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n$1); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n$1); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n$1); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n$1); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n$1); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +function isReference(node, parent) { + if (node.type === 'MemberExpression') { + return !node.computed && isReference(node.object, node); + } + if (node.type === 'Identifier') { + if (!parent) + return true; + switch (parent.type) { + // disregard `bar` in `foo.bar` + case 'MemberExpression': return parent.computed || node === parent.object; + // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` + case 'MethodDefinition': return parent.computed; + // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` + case 'FieldDefinition': return parent.computed || node === parent.value; + // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` + case 'Property': return parent.computed || node === parent.value; + // disregard the `bar` in `export { foo as bar }` or + // the foo in `import { foo as bar }` + case 'ExportSpecifier': + case 'ImportSpecifier': return node === parent.local; + // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` + case 'LabeledStatement': + case 'BreakStatement': + case 'ContinueStatement': return false; + default: return true; + } + } + return false; +} + +var version$3 = "25.0.7"; +var peerDependencies = { + rollup: "^2.68.0||^3.0.0||^4.0.0" +}; + +function tryParse(parse, code, id) { + try { + return parse(code, { allowReturnOutsideFunction: true }); + } catch (err) { + err.message += ` in ${id}`; + throw err; + } +} + +const firstpassGlobal = /\b(?:require|module|exports|global)\b/; + +const firstpassNoGlobal = /\b(?:require|module|exports)\b/; + +function hasCjsKeywords(code, ignoreGlobal) { + const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal; + return firstpass.test(code); +} + +/* eslint-disable no-underscore-dangle */ + + +function analyzeTopLevelStatements(parse, code, id) { + const ast = tryParse(parse, code, id); + + let isEsModule = false; + let hasDefaultExport = false; + let hasNamedExports = false; + + for (const node of ast.body) { + switch (node.type) { + case 'ExportDefaultDeclaration': + isEsModule = true; + hasDefaultExport = true; + break; + case 'ExportNamedDeclaration': + isEsModule = true; + if (node.declaration) { + hasNamedExports = true; + } else { + for (const specifier of node.specifiers) { + if (specifier.exported.name === 'default') { + hasDefaultExport = true; + } else { + hasNamedExports = true; + } + } + } + break; + case 'ExportAllDeclaration': + isEsModule = true; + if (node.exported && node.exported.name === 'default') { + hasDefaultExport = true; + } else { + hasNamedExports = true; + } + break; + case 'ImportDeclaration': + isEsModule = true; + break; + } + } + + return { isEsModule, hasDefaultExport, hasNamedExports, ast }; +} + +/* eslint-disable import/prefer-default-export */ + + +function deconflict(scopes, globals, identifier) { + let i = 1; + let deconflicted = makeLegalIdentifier(identifier); + const hasConflicts = () => + scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted); + + while (hasConflicts()) { + deconflicted = makeLegalIdentifier(`${identifier}_${i}`); + i += 1; + } + + for (const scope of scopes) { + scope.declarations[deconflicted] = true; + } + + return deconflicted; +} + +function getName(id) { + const name = makeLegalIdentifier(basename$1(id, extname(id))); + if (name !== 'index') { + return name; + } + return makeLegalIdentifier(basename$1(dirname$1(id))); +} + +function normalizePathSlashes(path) { + return path.replace(/\\/g, '/'); +} + +const getVirtualPathForDynamicRequirePath = (path, commonDir) => + `/${normalizePathSlashes(relative$1(commonDir, path))}`; + +function capitalize(name) { + return name[0].toUpperCase() + name.slice(1); +} + +function getStrictRequiresFilter({ strictRequires }) { + switch (strictRequires) { + case true: + return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; + // eslint-disable-next-line no-undefined + case undefined: + case 'auto': + case 'debug': + case null: + return { strictRequiresFilter: () => false, detectCyclesAndConditional: true }; + case false: + return { strictRequiresFilter: () => false, detectCyclesAndConditional: false }; + default: + if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) { + return { + strictRequiresFilter: createFilter$1(strictRequires), + detectCyclesAndConditional: false + }; + } + throw new Error('Unexpected value for "strictRequires" option.'); + } +} + +function getPackageEntryPoint(dirPath) { + let entryPoint = 'index.js'; + + try { + if (existsSync(join$1(dirPath, 'package.json'))) { + entryPoint = + JSON.parse(readFileSync(join$1(dirPath, 'package.json'), { encoding: 'utf8' })).main || + entryPoint; + } + } catch (ignored) { + // ignored + } + + return entryPoint; +} + +function isDirectory$1(path) { + try { + if (statSync$1(path).isDirectory()) return true; + } catch (ignored) { + // Nothing to do here + } + return false; +} + +function getDynamicRequireModules(patterns, dynamicRequireRoot) { + const dynamicRequireModules = new Map(); + const dirNames = new Set(); + for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { + const isNegated = pattern.startsWith('!'); + const modifyMap = (targetPath, resolvedPath) => + isNegated + ? dynamicRequireModules.delete(targetPath) + : dynamicRequireModules.set(targetPath, resolvedPath); + for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) { + const resolvedPath = resolve$3(path); + const requirePath = normalizePathSlashes(resolvedPath); + if (isDirectory$1(resolvedPath)) { + dirNames.add(resolvedPath); + const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path))); + modifyMap(requirePath, modulePath); + modifyMap(normalizePathSlashes(modulePath), modulePath); + } else { + dirNames.add(dirname$1(resolvedPath)); + modifyMap(requirePath, resolvedPath); + } + } + } + return { + commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null, + dynamicRequireModules + }; +} + +const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; + +const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire'; +const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire'; + +function getDynamicModuleRegistry( + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ignoreDynamicRequires +) { + if (!isDynamicRequireModulesEnabled) { + return `export function ${COMMONJS_REQUIRE_EXPORT}(path) { + ${FAILED_REQUIRE_ERROR} +}`; + } + const dynamicModuleImports = [...dynamicRequireModules.values()] + .map( + (id, index) => + `import ${ + id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }` + } from ${JSON.stringify(id)};` + ) + .join('\n'); + const dynamicModuleProps = [...dynamicRequireModules.keys()] + .map( + (id, index) => + `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${ + id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}` + }` + ) + .join(',\n'); + return `${dynamicModuleImports} + +var dynamicModules; + +function getDynamicModules() { + return dynamicModules || (dynamicModules = { +${dynamicModuleProps} + }); +} + +export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) { + function handleRequire(path) { + var resolvedPath = commonjsResolve(path, originalModuleDir); + if (resolvedPath !== null) { + return getDynamicModules()[resolvedPath](); + } + ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} + } + handleRequire.resolve = function (path) { + var resolvedPath = commonjsResolve(path, originalModuleDir); + if (resolvedPath !== null) { + return resolvedPath; + } + return require.resolve(path); + } + return handleRequire; +} + +function commonjsResolve (path, originalModuleDir) { + var shouldTryNodeModules = isPossibleNodeModulesPath(path); + path = normalize(path); + var relPath; + if (path[0] === '/') { + originalModuleDir = ''; + } + var modules = getDynamicModules(); + var checkedExtensions = ['', '.js', '.json']; + while (true) { + if (!shouldTryNodeModules) { + relPath = normalize(originalModuleDir + '/' + path); + } else { + relPath = normalize(originalModuleDir + '/node_modules/' + path); + } + + if (relPath.endsWith('/..')) { + break; // Travelled too far up, avoid infinite loop + } + + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { + var resolvedPath = relPath + checkedExtensions[extensionIndex]; + if (modules[resolvedPath]) { + return resolvedPath; + } + } + if (!shouldTryNodeModules) break; + var nextDir = normalize(originalModuleDir + '/..'); + if (nextDir === originalModuleDir) break; + originalModuleDir = nextDir; + } + return null; +} + +function isPossibleNodeModulesPath (modulePath) { + var c0 = modulePath[0]; + if (c0 === '/' || c0 === '\\\\') return false; + var c1 = modulePath[1], c2 = modulePath[2]; + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; + return true; +} + +function normalize (path) { + path = path.replace(/\\\\/g, '/'); + var parts = path.split('/'); + var slashed = parts[0] === ''; + for (var i = 1; i < parts.length; i++) { + if (parts[i] === '.' || parts[i] === '') { + parts.splice(i--, 1); + } + } + for (var i = 1; i < parts.length; i++) { + if (parts[i] !== '..') continue; + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { + parts.splice(--i, 2); + i--; + } + } + path = parts.join('/'); + if (slashed && path[0] !== '/') path = '/' + path; + else if (path.length === 0) path = '.'; + return path; +}`; +} + +const isWrappedId = (id, suffix) => id.endsWith(suffix); +const wrapId$1 = (id, suffix) => `\0${id}${suffix}`; +const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); + +const PROXY_SUFFIX = '?commonjs-proxy'; +const WRAPPED_SUFFIX = '?commonjs-wrapped'; +const EXTERNAL_SUFFIX = '?commonjs-external'; +const EXPORTS_SUFFIX = '?commonjs-exports'; +const MODULE_SUFFIX = '?commonjs-module'; +const ENTRY_SUFFIX = '?commonjs-entry'; +const ES_IMPORT_SUFFIX = '?commonjs-es-import'; + +const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules'; +const HELPERS_ID = '\0commonjsHelpers.js'; + +const IS_WRAPPED_COMMONJS = 'withRequireFunction'; + +// `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. +// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. +// This could be improved by inspecting Rollup's "generatedCode" option + +const HELPERS = ` +export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +export function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +export function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; +} + +export function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; +} + +export function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} +`; + +function getHelpersModule() { + return HELPERS; +} + +function getUnknownRequireProxy(id, requireReturnsDefault) { + if (requireReturnsDefault === true || id.endsWith('.json')) { + return `export { default } from ${JSON.stringify(id)};`; + } + const name = getName(id); + const exported = + requireReturnsDefault === 'auto' + ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` + : requireReturnsDefault === 'preferred' + ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` + : !requireReturnsDefault + ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` + : `export default ${name};`; + return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; +} + +async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) { + const name = getName(id); + const { + meta: { commonjs: commonjsMeta } + } = await loadModule({ id }); + if (!commonjsMeta) { + return getUnknownRequireProxy(id, requireReturnsDefault); + } + if (commonjsMeta.isCommonJS) { + return `export { __moduleExports as default } from ${JSON.stringify(id)};`; + } + if (!requireReturnsDefault) { + return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( + id + )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; + } + if ( + requireReturnsDefault !== true && + (requireReturnsDefault === 'namespace' || + !commonjsMeta.hasDefaultExport || + (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports)) + ) { + return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; + } + return `export { default } from ${JSON.stringify(id)};`; +} + +function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) { + const { + meta: { commonjs: commonjsMeta }, + hasDefaultExport + } = getModuleInfo(id); + if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { + const stringifiedId = JSON.stringify(id); + let code = `export * from ${stringifiedId};`; + if (hasDefaultExport) { + code += `export { default } from ${stringifiedId};`; + } + return shebang + code; + } + const result = getEsImportProxy(id, defaultIsModuleExports); + return { + ...result, + code: shebang + result.code + }; +} + +function getEsImportProxy(id, defaultIsModuleExports) { + const name = getName(id); + const exportsName = `${name}Exports`; + const requireModule = `require${capitalize(name)}`; + let code = + `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` + + `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` + + `var ${exportsName} = ${requireModule}();\n` + + `export { ${exportsName} as __moduleExports };`; + if (defaultIsModuleExports === true) { + code += `\nexport { ${exportsName} as default };`; + } else { + code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; + } + return { + code, + syntheticNamedExports: '__moduleExports' + }; +} + +/* eslint-disable no-param-reassign, no-undefined */ + + +function getCandidatesForExtension(resolved, extension) { + return [resolved + extension, `${resolved}${sep}index${extension}`]; +} + +function getCandidates(resolved, extensions) { + return extensions.reduce( + (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), + [resolved] + ); +} + +function resolveExtensions(importee, importer, extensions) { + // not our problem + if (importee[0] !== '.' || !importer) return undefined; + + const resolved = resolve$3(dirname$1(importer), importee); + const candidates = getCandidates(resolved, extensions); + + for (let i = 0; i < candidates.length; i += 1) { + try { + const stats = statSync$1(candidates[i]); + if (stats.isFile()) return { id: candidates[i] }; + } catch (err) { + /* noop */ + } + } + + return undefined; +} + +function getResolveId(extensions, isPossibleCjsId) { + const currentlyResolving = new Map(); + + return { + /** + * This is a Maps of importers to Sets of require sources being resolved at + * the moment by resolveRequireSourcesAndUpdateMeta + */ + currentlyResolving, + async resolveId(importee, importer, resolveOptions) { + const customOptions = resolveOptions.custom; + // All logic below is specific to ES imports. + // Also, if we do not skip this logic for requires that are resolved while + // transforming a commonjs file, it can easily lead to deadlocks. + if ( + customOptions && + customOptions['node-resolve'] && + customOptions['node-resolve'].isRequire + ) { + return null; + } + const currentlyResolvingForParent = currentlyResolving.get(importer); + if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) { + this.warn({ + code: 'THIS_RESOLVE_WITHOUT_OPTIONS', + message: + 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.', + url: 'https://rollupjs.org/guide/en/#resolveid' + }); + return null; + } + + if (isWrappedId(importee, WRAPPED_SUFFIX)) { + return unwrapId$1(importee, WRAPPED_SUFFIX); + } + + if ( + importee.endsWith(ENTRY_SUFFIX) || + isWrappedId(importee, MODULE_SUFFIX) || + isWrappedId(importee, EXPORTS_SUFFIX) || + isWrappedId(importee, PROXY_SUFFIX) || + isWrappedId(importee, ES_IMPORT_SUFFIX) || + isWrappedId(importee, EXTERNAL_SUFFIX) || + importee.startsWith(HELPERS_ID) || + importee === DYNAMIC_MODULES_ID + ) { + return importee; + } + + if (importer) { + if ( + importer === DYNAMIC_MODULES_ID || + // Proxies are only importing resolved ids, no need to resolve again + isWrappedId(importer, PROXY_SUFFIX) || + isWrappedId(importer, ES_IMPORT_SUFFIX) || + importer.endsWith(ENTRY_SUFFIX) + ) { + return importee; + } + if (isWrappedId(importer, EXTERNAL_SUFFIX)) { + // We need to return null for unresolved imports so that the proper warning is shown + if ( + !(await this.resolve( + importee, + importer, + Object.assign({ skipSelf: true }, resolveOptions) + )) + ) { + return null; + } + // For other external imports, we need to make sure they are handled as external + return { id: importee, external: true }; + } + } + + if (importee.startsWith('\0')) { + return null; + } + + // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and + // if that is the case, we need to add a proxy. + const resolved = + (await this.resolve( + importee, + importer, + Object.assign({ skipSelf: true }, resolveOptions) + )) || resolveExtensions(importee, importer, extensions); + // Make sure that even if other plugins resolve again, we ignore our own proxies + if ( + !resolved || + resolved.external || + resolved.id.endsWith(ENTRY_SUFFIX) || + isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || + !isPossibleCjsId(resolved.id) + ) { + return resolved; + } + const moduleInfo = await this.load(resolved); + const { + meta: { commonjs: commonjsMeta } + } = moduleInfo; + if (commonjsMeta) { + const { isCommonJS } = commonjsMeta; + if (isCommonJS) { + if (resolveOptions.isEntry) { + moduleInfo.moduleSideEffects = true; + // We must not precede entry proxies with a `\0` as that will mess up relative external resolution + return resolved.id + ENTRY_SUFFIX; + } + if (isCommonJS === IS_WRAPPED_COMMONJS) { + return { id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } }; + } + } + } + return resolved; + } + }; +} + +function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) { + const knownCjsModuleTypes = Object.create(null); + const requiredIds = Object.create(null); + const unconditionallyRequiredIds = Object.create(null); + const dependencies = Object.create(null); + const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set()); + + const isCyclic = (id) => { + const dependenciesToCheck = new Set(getDependencies(id)); + for (const dependency of dependenciesToCheck) { + if (dependency === id) { + return true; + } + for (const childDependency of getDependencies(dependency)) { + dependenciesToCheck.add(childDependency); + } + } + return false; + }; + + // Once a module is listed here, its type (wrapped or not) is fixed and may + // not change for the rest of the current build, to not break already + // transformed modules. + const fullyAnalyzedModules = Object.create(null); + + const getTypeForFullyAnalyzedModule = (id) => { + const knownType = knownCjsModuleTypes[id]; + if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) { + return knownType; + } + if (isCyclic(id)) { + return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS); + } + return knownType; + }; + + const setInitialParentType = (id, initialCommonJSType) => { + // Fully analyzed modules may never change type + if (fullyAnalyzedModules[id]) { + return; + } + knownCjsModuleTypes[id] = initialCommonJSType; + if ( + detectCyclesAndConditional && + knownCjsModuleTypes[id] === true && + requiredIds[id] && + !unconditionallyRequiredIds[id] + ) { + knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; + } + }; + + const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => { + const childId = resolved.id; + requiredIds[childId] = true; + if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) { + unconditionallyRequiredIds[childId] = true; + } + + getDependencies(parentId).add(childId); + if (!isCyclic(childId)) { + // This makes sure the current transform handler waits for all direct + // dependencies to be loaded and transformed and therefore for all + // transitive CommonJS dependencies to be loaded as well so that all + // cycles have been found and knownCjsModuleTypes is reliable. + await loadModule(resolved); + } + }; + + const getTypeForImportedModule = async (resolved, loadModule) => { + if (resolved.id in knownCjsModuleTypes) { + // This handles cyclic ES dependencies + return knownCjsModuleTypes[resolved.id]; + } + const { + meta: { commonjs } + } = await loadModule(resolved); + return (commonjs && commonjs.isCommonJS) || false; + }; + + return { + getWrappedIds: () => + Object.keys(knownCjsModuleTypes).filter( + (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS + ), + isRequiredId: (id) => requiredIds[id], + async shouldTransformCachedModule({ + id: parentId, + resolvedSources, + meta: { commonjs: parentMeta } + }) { + // We explicitly track ES modules to handle circular imports + if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false; + if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false; + const parentRequires = parentMeta && parentMeta.requires; + if (parentRequires) { + setInitialParentType(parentId, parentMeta.initialCommonJSType); + await Promise.all( + parentRequires.map(({ resolved, isConditional }) => + analyzeRequiredModule(parentId, resolved, isConditional, this.load) + ) + ); + if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) { + return true; + } + for (const { + resolved: { id } + } of parentRequires) { + if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) { + return true; + } + } + // Now that we decided to go with the cached copy, neither the parent + // module nor any of its children may change types anymore + fullyAnalyzedModules[parentId] = true; + for (const { + resolved: { id } + } of parentRequires) { + fullyAnalyzedModules[id] = true; + } + } + const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id)); + return ( + await Promise.all( + Object.keys(resolvedSources) + .map((source) => resolvedSources[source]) + .filter(({ id, external }) => !(external || parentRequireSet.has(id))) + .map(async (resolved) => { + if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) { + return ( + (await getTypeForImportedModule( + ( + await this.load({ id: resolved.id }) + ).meta.commonjs.resolved, + this.load + )) !== IS_WRAPPED_COMMONJS + ); + } + return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS; + }) + ) + ).some((shouldTransform) => shouldTransform); + }, + /* eslint-disable no-param-reassign */ + resolveRequireSourcesAndUpdateMeta: + (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => { + parentMeta.initialCommonJSType = isParentCommonJS; + parentMeta.requires = []; + parentMeta.isRequiredCommonJS = Object.create(null); + setInitialParentType(parentId, isParentCommonJS); + const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set(); + currentlyResolving.set(parentId, currentlyResolvingForParent); + const requireTargets = await Promise.all( + sources.map(async ({ source, isConditional }) => { + // Never analyze or proxy internal modules + if (source.startsWith('\0')) { + return { id: source, allowProxy: false }; + } + currentlyResolvingForParent.add(source); + const resolved = + (await rollupContext.resolve(source, parentId, { + skipSelf: false, + custom: { 'node-resolve': { isRequire: true } } + })) || resolveExtensions(source, parentId, extensions); + currentlyResolvingForParent.delete(source); + if (!resolved) { + return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false }; + } + const childId = resolved.id; + if (resolved.external) { + return { id: wrapId$1(childId, EXTERNAL_SUFFIX), allowProxy: false }; + } + parentMeta.requires.push({ resolved, isConditional }); + await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load); + return { id: childId, allowProxy: true }; + }) + ); + parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId); + fullyAnalyzedModules[parentId] = true; + return requireTargets.map(({ id: dependencyId, allowProxy }, index) => { + // eslint-disable-next-line no-multi-assign + const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] = + getTypeForFullyAnalyzedModule(dependencyId)); + fullyAnalyzedModules[dependencyId] = true; + return { + source: sources[index].source, + id: allowProxy + ? isCommonJS === IS_WRAPPED_COMMONJS + ? wrapId$1(dependencyId, WRAPPED_SUFFIX) + : wrapId$1(dependencyId, PROXY_SUFFIX) + : dependencyId, + isCommonJS + }; + }); + }, + isCurrentlyResolving(source, parentId) { + const currentlyResolvingForParent = currentlyResolving.get(parentId); + return currentlyResolvingForParent && currentlyResolvingForParent.has(source); + } + }; +} + +function validateVersion(actualVersion, peerDependencyVersion, name) { + const versionRegexp = /\^(\d+\.\d+\.\d+)/g; + let minMajor = Infinity; + let minMinor = Infinity; + let minPatch = Infinity; + let foundVersion; + // eslint-disable-next-line no-cond-assign + while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { + const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number); + if (foundMajor < minMajor) { + minMajor = foundMajor; + minMinor = foundMinor; + minPatch = foundPatch; + } + } + if (!actualVersion) { + throw new Error( + `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.` + ); + } + const [major, minor, patch] = actualVersion.split('.').map(Number); + if ( + major < minMajor || + (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch))) + ) { + throw new Error( + `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.` + ); + } +} + +const operators = { + '==': (x) => equals(x.left, x.right, false), + + '!=': (x) => not(operators['=='](x)), + + '===': (x) => equals(x.left, x.right, true), + + '!==': (x) => not(operators['==='](x)), + + '!': (x) => isFalsy(x.argument), + + '&&': (x) => isTruthy(x.left) && isTruthy(x.right), + + '||': (x) => isTruthy(x.left) || isTruthy(x.right) +}; + +function not(value) { + return value === null ? value : !value; +} + +function equals(a, b, strict) { + if (a.type !== b.type) return null; + // eslint-disable-next-line eqeqeq + if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value; + return null; +} + +function isTruthy(node) { + if (!node) return false; + if (node.type === 'Literal') return !!node.value; + if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression); + if (node.operator in operators) return operators[node.operator](node); + return null; +} + +function isFalsy(node) { + return not(isTruthy(node)); +} + +function getKeypath(node) { + const parts = []; + + while (node.type === 'MemberExpression') { + if (node.computed) return null; + + parts.unshift(node.property.name); + // eslint-disable-next-line no-param-reassign + node = node.object; + } + + if (node.type !== 'Identifier') return null; + + const { name } = node; + parts.unshift(name); + + return { name, keypath: parts.join('.') }; +} + +const KEY_COMPILED_ESM = '__esModule'; + +function getDefineCompiledEsmType(node) { + const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports'); + const definedProperty = + definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports'); + if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { + return isTruthy(definedProperty.value) + ? definedPropertyWithExports + ? 'exports' + : 'module' + : false; + } + return false; +} + +function getDefinePropertyCallName(node, targetName) { + const { + callee: { object, property } + } = node; + if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; + if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; + if (node.arguments.length !== 3) return; + + const targetNames = targetName.split('.'); + const [target, key, value] = node.arguments; + if (targetNames.length === 1) { + if (target.type !== 'Identifier' || target.name !== targetNames[0]) { + return; + } + } + + if (targetNames.length === 2) { + if ( + target.type !== 'MemberExpression' || + target.object.name !== targetNames[0] || + target.property.name !== targetNames[1] + ) { + return; + } + } + + if (value.type !== 'ObjectExpression' || !value.properties) return; + + const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); + if (!valueProperty || !valueProperty.value) return; + + // eslint-disable-next-line consistent-return + return { key: key.value, value: valueProperty.value }; +} + +function isShorthandProperty(parent) { + return parent && parent.type === 'Property' && parent.shorthand; +} + +function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) { + const args = []; + const passedArgs = []; + if (uses.module) { + args.push('module'); + passedArgs.push(moduleName); + } + if (uses.exports) { + args.push('exports'); + passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName); + } + magicString + .trim() + .indent('\t', { exclude: indentExclusionRanges }) + .prepend(`(function (${args.join(', ')}) {\n`) + // For some reason, this line is only indented correctly when using a + // require-wrapper if we have this leading space + .append(` \n} (${passedArgs.join(', ')}));`); +} + +function rewriteExportsAndGetExportsBlock( + magicString, + moduleName, + exportsName, + exportedExportsName, + wrapped, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsAssignmentsByName, + topLevelAssignments, + defineCompiledEsmExpressions, + deconflictedExportNames, + code, + HELPERS_NAME, + exportMode, + defaultIsModuleExports, + usesRequireWrapper, + requireName +) { + const exports = []; + const exportDeclarations = []; + + if (usesRequireWrapper) { + getExportsWhenUsingRequireWrapper( + magicString, + wrapped, + exportMode, + exports, + moduleExportsAssignments, + exportsAssignmentsByName, + moduleName, + exportsName, + requireName, + defineCompiledEsmExpressions + ); + } else if (exportMode === 'replace') { + getExportsForReplacedModuleExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsName, + defaultIsModuleExports, + HELPERS_NAME + ); + } else { + if (exportMode === 'module') { + exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`); + exports.push(`${exportedExportsName} as __moduleExports`); + } else { + exports.push(`${exportsName} as __moduleExports`); + } + if (wrapped) { + exportDeclarations.push( + getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) + ); + } else { + getExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + exportsAssignmentsByName, + deconflictedExportNames, + topLevelAssignments, + moduleName, + exportsName, + exportedExportsName, + defineCompiledEsmExpressions, + HELPERS_NAME, + defaultIsModuleExports, + exportMode + ); + } + } + if (exports.length) { + exportDeclarations.push(`export { ${exports.join(', ')} }`); + } + + return `\n\n${exportDeclarations.join(';\n')};`; +} + +function getExportsWhenUsingRequireWrapper( + magicString, + wrapped, + exportMode, + exports, + moduleExportsAssignments, + exportsAssignmentsByName, + moduleName, + exportsName, + requireName, + defineCompiledEsmExpressions +) { + exports.push(`${requireName} as __require`); + if (wrapped) return; + if (exportMode === 'replace') { + rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName); + } else { + rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`); + // Collect and rewrite named exports + for (const [exportName, { nodes }] of exportsAssignmentsByName) { + for (const { node, type } of nodes) { + magicString.overwrite( + node.start, + node.left.end, + `${ + exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName + }.${exportName}` + ); + } + } + replaceDefineCompiledEsmExpressionsAndGetIfRestorable( + defineCompiledEsmExpressions, + magicString, + exportMode, + moduleName, + exportsName + ); + } +} + +function getExportsForReplacedModuleExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsName, + defaultIsModuleExports, + HELPERS_NAME +) { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } + magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var '); + exports.push(`${exportsName} as __moduleExports`); + exportDeclarations.push( + getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME) + ); +} + +function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) { + return `export default ${ + defaultIsModuleExports === true + ? exportedExportsName + : defaultIsModuleExports === false + ? `${exportedExportsName}.default` + : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})` + }`; +} + +function getExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + exportsAssignmentsByName, + deconflictedExportNames, + topLevelAssignments, + moduleName, + exportsName, + exportedExportsName, + defineCompiledEsmExpressions, + HELPERS_NAME, + defaultIsModuleExports, + exportMode +) { + let deconflictedDefaultExportName; + // Collect and rewrite module.exports assignments + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, `${moduleName}.exports`); + } + + // Collect and rewrite named exports + for (const [exportName, { nodes }] of exportsAssignmentsByName) { + const deconflicted = deconflictedExportNames[exportName]; + let needsDeclaration = true; + for (const { node, type } of nodes) { + let replacement = `${deconflicted} = ${ + exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName + }.${exportName}`; + if (needsDeclaration && topLevelAssignments.has(node)) { + replacement = `var ${replacement}`; + needsDeclaration = false; + } + magicString.overwrite(node.start, node.left.end, replacement); + } + if (needsDeclaration) { + magicString.prepend(`var ${deconflicted};\n`); + } + + if (exportName === 'default') { + deconflictedDefaultExportName = deconflicted; + } else { + exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`); + } + } + + const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable( + defineCompiledEsmExpressions, + magicString, + exportMode, + moduleName, + exportsName + ); + + if ( + defaultIsModuleExports === false || + (defaultIsModuleExports === 'auto' && + isRestorableCompiledEsm && + moduleExportsAssignments.length === 0) + ) { + // If there is no deconflictedDefaultExportName, then we use the namespace as + // fallback because there can be no "default" property on the namespace + exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`); + } else if ( + defaultIsModuleExports === true || + (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0) + ) { + exports.push(`${exportedExportsName} as default`); + } else { + exportDeclarations.push( + getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) + ); + } +} + +function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } +} + +function replaceDefineCompiledEsmExpressionsAndGetIfRestorable( + defineCompiledEsmExpressions, + magicString, + exportMode, + moduleName, + exportsName +) { + let isRestorableCompiledEsm = false; + for (const { node, type } of defineCompiledEsmExpressions) { + isRestorableCompiledEsm = true; + const moduleExportsExpression = + node.type === 'CallExpression' ? node.arguments[0] : node.left.object; + magicString.overwrite( + moduleExportsExpression.start, + moduleExportsExpression.end, + exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName + ); + } + return isRestorableCompiledEsm; +} + +function isRequireExpression(node, scope) { + if (!node) return false; + if (node.type !== 'CallExpression') return false; + + // Weird case of `require()` or `module.require()` without arguments + if (node.arguments.length === 0) return false; + + return isRequire(node.callee, scope); +} + +function isRequire(node, scope) { + return ( + (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || + (node.type === 'MemberExpression' && isModuleRequire(node, scope)) + ); +} + +function isModuleRequire({ object, property }, scope) { + return ( + object.type === 'Identifier' && + object.name === 'module' && + property.type === 'Identifier' && + property.name === 'require' && + !scope.contains('module') + ); +} + +function hasDynamicArguments(node) { + return ( + node.arguments.length > 1 || + (node.arguments[0].type !== 'Literal' && + (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0)) + ); +} + +const reservedMethod = { resolve: true, cache: true, main: true }; + +function isNodeRequirePropertyAccess(parent) { + return parent && parent.property && reservedMethod[parent.property.name]; +} + +function getRequireStringArg(node) { + return node.arguments[0].type === 'Literal' + ? node.arguments[0].value + : node.arguments[0].quasis[0].value.cooked; +} + +function getRequireHandlers() { + const requireExpressions = []; + + function addRequireExpression( + sourceId, + node, + scope, + usesReturnValue, + isInsideTryBlock, + isInsideConditional, + toBeRemoved + ) { + requireExpressions.push({ + sourceId, + node, + scope, + usesReturnValue, + isInsideTryBlock, + isInsideConditional, + toBeRemoved + }); + } + + async function rewriteRequireExpressionsAndGetImportBlock( + magicString, + topLevelDeclarations, + reassignedNames, + helpersName, + dynamicRequireName, + moduleName, + exportsName, + id, + exportMode, + resolveRequireSourcesAndUpdateMeta, + needsRequireWrapper, + isEsModule, + isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + commonjsMeta + ) { + const imports = []; + imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`); + if (dynamicRequireName) { + imports.push( + `import { ${ + isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT + } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"` + ); + } + if (exportMode === 'module') { + imports.push( + `import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`, + `var ${exportsName} = ${moduleName}.exports` + ); + } else if (exportMode === 'exports') { + imports.push( + `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}` + ); + } + const requiresBySource = collectSources(requireExpressions); + const requireTargets = await resolveRequireSourcesAndUpdateMeta( + id, + needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, + commonjsMeta, + Object.keys(requiresBySource).map((source) => { + return { + source, + isConditional: requiresBySource[source].every((require) => require.isInsideConditional) + }; + }) + ); + processRequireExpressions( + imports, + requireTargets, + requiresBySource, + getIgnoreTryCatchRequireStatementMode, + magicString + ); + return imports.length ? `${imports.join(';\n')};\n\n` : ''; + } + + return { + addRequireExpression, + rewriteRequireExpressionsAndGetImportBlock + }; +} + +function collectSources(requireExpressions) { + const requiresBySource = Object.create(null); + for (const requireExpression of requireExpressions) { + const { sourceId } = requireExpression; + if (!requiresBySource[sourceId]) { + requiresBySource[sourceId] = []; + } + const requires = requiresBySource[sourceId]; + requires.push(requireExpression); + } + return requiresBySource; +} + +function processRequireExpressions( + imports, + requireTargets, + requiresBySource, + getIgnoreTryCatchRequireStatementMode, + magicString +) { + const generateRequireName = getGenerateRequireName(); + for (const { source, id: resolvedId, isCommonJS } of requireTargets) { + const requires = requiresBySource[source]; + const name = generateRequireName(requires); + let usesRequired = false; + let needsImport = false; + for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) { + const { canConvertRequire, shouldRemoveRequire } = + isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) + ? getIgnoreTryCatchRequireStatementMode(source) + : { canConvertRequire: true, shouldRemoveRequire: false }; + if (shouldRemoveRequire) { + if (usesReturnValue) { + magicString.overwrite(node.start, node.end, 'undefined'); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } else if (canConvertRequire) { + needsImport = true; + if (isCommonJS === IS_WRAPPED_COMMONJS) { + magicString.overwrite(node.start, node.end, `${name}()`); + } else if (usesReturnValue) { + usesRequired = true; + magicString.overwrite(node.start, node.end, name); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } + } + if (needsImport) { + if (isCommonJS === IS_WRAPPED_COMMONJS) { + imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`); + } else { + imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`); + } + } + } +} + +function getGenerateRequireName() { + let uid = 0; + return (requires) => { + let name; + const hasNameConflict = ({ scope }) => scope.contains(name); + do { + name = `require$$${uid}`; + uid += 1; + } while (requires.some(hasNameConflict)); + return name; + }; +} + +/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */ + + +const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; + +const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; + +// There are three different types of CommonJS modules, described by their +// "exportMode": +// - exports: Only assignments to (module.)exports properties +// - replace: A single assignment to module.exports itself +// - module: Anything else +// Special cases: +// - usesRequireWrapper +// - isWrapped +async function transformCommonjs( + parse, + code, + id, + isEsModule, + ignoreGlobal, + ignoreRequire, + ignoreDynamicRequires, + getIgnoreTryCatchRequireStatementMode, + sourceMap, + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + astCache, + defaultIsModuleExports, + needsRequireWrapper, + resolveRequireSourcesAndUpdateMeta, + isRequired, + checkDynamicRequire, + commonjsMeta +) { + const ast = astCache || tryParse(parse, code, id); + const magicString = new MagicString(code); + const uses = { + module: false, + exports: false, + global: false, + require: false + }; + const virtualDynamicRequirePath = + isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir); + let scope = attachScopes(ast, 'scope'); + let lexicalDepth = 0; + let programDepth = 0; + let classBodyDepth = 0; + let currentTryBlockEnd = null; + let shouldWrap = false; + + const globals = new Set(); + // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require + // or contains nested requires, those should be handled as function calls unless there is an + // unconditional require elsewhere. + let currentConditionalNodeEnd = null; + const conditionalNodes = new Set(); + const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); + + // See which names are assigned to. This is necessary to prevent + // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, + // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) + const reassignedNames = new Set(); + const topLevelDeclarations = []; + const skippedNodes = new Set(); + const moduleAccessScopes = new Set([scope]); + const exportsAccessScopes = new Set([scope]); + const moduleExportsAssignments = []; + let firstTopLevelModuleExportsAssignment = null; + const exportsAssignmentsByName = new Map(); + const topLevelAssignments = new Set(); + const topLevelDefineCompiledEsmExpressions = []; + const replacedGlobal = []; + const replacedDynamicRequires = []; + const importedVariables = new Set(); + const indentExclusionRanges = []; + + walk$3(ast, { + enter(node, parent) { + if (skippedNodes.has(node)) { + this.skip(); + return; + } + + if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { + currentTryBlockEnd = null; + } + if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) { + currentConditionalNodeEnd = null; + } + if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) { + currentConditionalNodeEnd = node.end; + } + + programDepth += 1; + if (node.scope) ({ scope } = node); + if (functionType.test(node.type)) lexicalDepth += 1; + if (sourceMap) { + magicString.addSourcemapLocation(node.start); + magicString.addSourcemapLocation(node.end); + } + + // eslint-disable-next-line default-case + switch (node.type) { + case 'AssignmentExpression': + if (node.left.type === 'MemberExpression') { + const flattened = getKeypath(node.left); + if (!flattened || scope.contains(flattened.name)) return; + + const exportsPatternMatch = exportsPattern.exec(flattened.keypath); + if (!exportsPatternMatch || flattened.keypath === 'exports') return; + + const [, exportName] = exportsPatternMatch; + uses[flattened.name] = true; + + // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` – + if (flattened.keypath === 'module.exports') { + moduleExportsAssignments.push(node); + if (programDepth > 3) { + moduleAccessScopes.add(scope); + } else if (!firstTopLevelModuleExportsAssignment) { + firstTopLevelModuleExportsAssignment = node; + } + } else if (exportName === KEY_COMPILED_ESM) { + if (programDepth > 3) { + shouldWrap = true; + } else { + // The "type" is either "module" or "exports" to discern + // assignments to module.exports vs exports if needed + topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name }); + } + } else { + const exportsAssignments = exportsAssignmentsByName.get(exportName) || { + nodes: [], + scopes: new Set() + }; + exportsAssignments.nodes.push({ node, type: flattened.name }); + exportsAssignments.scopes.add(scope); + exportsAccessScopes.add(scope); + exportsAssignmentsByName.set(exportName, exportsAssignments); + if (programDepth <= 3) { + topLevelAssignments.add(node); + } + } + + skippedNodes.add(node.left); + } else { + for (const name of extractAssignedNames(node.left)) { + reassignedNames.add(name); + } + } + return; + case 'CallExpression': { + const defineCompiledEsmType = getDefineCompiledEsmType(node); + if (defineCompiledEsmType) { + if (programDepth === 3 && parent.type === 'ExpressionStatement') { + // skip special handling for [module.]exports until we know we render this + skippedNodes.add(node.arguments[0]); + topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType }); + } else { + shouldWrap = true; + } + return; + } + + // Transform require.resolve + if ( + isDynamicRequireModulesEnabled && + node.callee.object && + isRequire(node.callee.object, scope) && + node.callee.property.name === 'resolve' + ) { + checkDynamicRequire(node.start); + uses.require = true; + const requireNode = node.callee.object; + replacedDynamicRequires.push(requireNode); + skippedNodes.add(node.callee); + return; + } + + if (!isRequireExpression(node, scope)) { + const keypath = getKeypath(node.callee); + if (keypath && importedVariables.has(keypath.name)) { + // Heuristic to deoptimize requires after a required function has been called + currentConditionalNodeEnd = Infinity; + } + return; + } + + skippedNodes.add(node.callee); + uses.require = true; + + if (hasDynamicArguments(node)) { + if (isDynamicRequireModulesEnabled) { + checkDynamicRequire(node.start); + } + if (!ignoreDynamicRequires) { + replacedDynamicRequires.push(node.callee); + } + return; + } + + const requireStringArg = getRequireStringArg(node); + if (!ignoreRequire(requireStringArg)) { + const usesReturnValue = parent.type !== 'ExpressionStatement'; + const toBeRemoved = + parent.type === 'ExpressionStatement' && + (!currentConditionalNodeEnd || + // We should completely remove requires directly in a try-catch + // so that Rollup can remove up the try-catch + (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd)) + ? parent + : node; + addRequireExpression( + requireStringArg, + node, + scope, + usesReturnValue, + currentTryBlockEnd !== null, + currentConditionalNodeEnd !== null, + toBeRemoved + ); + if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') { + for (const name of extractAssignedNames(parent.id)) { + importedVariables.add(name); + } + } + } + return; + } + case 'ClassBody': + classBodyDepth += 1; + return; + case 'ConditionalExpression': + case 'IfStatement': + // skip dead branches + if (isFalsy(node.test)) { + skippedNodes.add(node.consequent); + } else if (isTruthy(node.test)) { + if (node.alternate) { + skippedNodes.add(node.alternate); + } + } else { + conditionalNodes.add(node.consequent); + if (node.alternate) { + conditionalNodes.add(node.alternate); + } + } + return; + case 'ArrowFunctionExpression': + case 'FunctionDeclaration': + case 'FunctionExpression': + // requires in functions should be conditional unless it is an IIFE + if ( + currentConditionalNodeEnd === null && + !(parent.type === 'CallExpression' && parent.callee === node) + ) { + currentConditionalNodeEnd = node.end; + } + return; + case 'Identifier': { + const { name } = node; + if (!isReference(node, parent) || scope.contains(name)) return; + switch (name) { + case 'require': + uses.require = true; + if (isNodeRequirePropertyAccess(parent)) { + return; + } + if (!ignoreDynamicRequires) { + if (isShorthandProperty(parent)) { + // as key and value are the same object, isReference regards + // both as references, so we need to skip now + skippedNodes.add(parent.value); + magicString.prependRight(node.start, 'require: '); + } + replacedDynamicRequires.push(node); + } + return; + case 'module': + case 'exports': + shouldWrap = true; + uses[name] = true; + return; + case 'global': + uses.global = true; + if (!ignoreGlobal) { + replacedGlobal.push(node); + } + return; + case 'define': + magicString.overwrite(node.start, node.end, 'undefined', { + storeName: true + }); + return; + default: + globals.add(name); + return; + } + } + case 'LogicalExpression': + // skip dead branches + if (node.operator === '&&') { + if (isFalsy(node.left)) { + skippedNodes.add(node.right); + } else if (!isTruthy(node.left)) { + conditionalNodes.add(node.right); + } + } else if (node.operator === '||') { + if (isTruthy(node.left)) { + skippedNodes.add(node.right); + } else if (!isFalsy(node.left)) { + conditionalNodes.add(node.right); + } + } + return; + case 'MemberExpression': + if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { + uses.require = true; + replacedDynamicRequires.push(node); + skippedNodes.add(node.object); + skippedNodes.add(node.property); + } + return; + case 'ReturnStatement': + // if top-level return, we need to wrap it + if (lexicalDepth === 0) { + shouldWrap = true; + } + return; + case 'ThisExpression': + // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal` + if (lexicalDepth === 0 && !classBodyDepth) { + uses.global = true; + if (!ignoreGlobal) { + replacedGlobal.push(node); + } + } + return; + case 'TryStatement': + if (currentTryBlockEnd === null) { + currentTryBlockEnd = node.block.end; + } + if (currentConditionalNodeEnd === null) { + currentConditionalNodeEnd = node.end; + } + return; + case 'UnaryExpression': + // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) + if (node.operator === 'typeof') { + const flattened = getKeypath(node.argument); + if (!flattened) return; + + if (scope.contains(flattened.name)) return; + + if ( + !isEsModule && + (flattened.keypath === 'module.exports' || + flattened.keypath === 'module' || + flattened.keypath === 'exports') + ) { + magicString.overwrite(node.start, node.end, `'object'`, { + storeName: false + }); + } + } + return; + case 'VariableDeclaration': + if (!scope.parent) { + topLevelDeclarations.push(node); + } + return; + case 'TemplateElement': + if (node.value.raw.includes('\n')) { + indentExclusionRanges.push([node.start, node.end]); + } + } + }, + + leave(node) { + programDepth -= 1; + if (node.scope) scope = scope.parent; + if (functionType.test(node.type)) lexicalDepth -= 1; + if (node.type === 'ClassBody') classBodyDepth -= 1; + } + }); + + const nameBase = getName(id); + const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); + const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); + const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); + const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); + const helpersName = deconflict([scope], globals, 'commonjsHelpers'); + const dynamicRequireName = + replacedDynamicRequires.length > 0 && + deconflict( + [scope], + globals, + isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT + ); + const deconflictedExportNames = Object.create(null); + for (const [exportName, { scopes }] of exportsAssignmentsByName) { + deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); + } + + for (const node of replacedGlobal) { + magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { + storeName: true + }); + } + for (const node of replacedDynamicRequires) { + magicString.overwrite( + node.start, + node.end, + isDynamicRequireModulesEnabled + ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` + : dynamicRequireName, + { + contentOnly: true, + storeName: true + } + ); + } + + // We cannot wrap ES/mixed modules + shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); + + if ( + !( + shouldWrap || + isRequired || + needsRequireWrapper || + uses.module || + uses.exports || + uses.require || + topLevelDefineCompiledEsmExpressions.length > 0 + ) && + (ignoreGlobal || !uses.global) + ) { + return { meta: { commonjs: { isCommonJS: false } } }; + } + + let leadingComment = ''; + if (code.startsWith('/*')) { + const commentEnd = code.indexOf('*/', 2) + 2; + leadingComment = `${code.slice(0, commentEnd)}\n`; + magicString.remove(0, commentEnd).trim(); + } + + let shebang = ''; + if (code.startsWith('#!')) { + const shebangEndPosition = code.indexOf('\n') + 1; + shebang = code.slice(0, shebangEndPosition); + magicString.remove(0, shebangEndPosition).trim(); + } + + const exportMode = isEsModule + ? 'none' + : shouldWrap + ? uses.module + ? 'module' + : 'exports' + : firstTopLevelModuleExportsAssignment + ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 + ? 'replace' + : 'module' + : moduleExportsAssignments.length === 0 + ? 'exports' + : 'module'; + + const exportedExportsName = + exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName; + + const importBlock = await rewriteRequireExpressionsAndGetImportBlock( + magicString, + topLevelDeclarations, + reassignedNames, + helpersName, + dynamicRequireName, + moduleName, + exportsName, + id, + exportMode, + resolveRequireSourcesAndUpdateMeta, + needsRequireWrapper, + isEsModule, + isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + commonjsMeta + ); + const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS; + const exportBlock = isEsModule + ? '' + : rewriteExportsAndGetExportsBlock( + magicString, + moduleName, + exportsName, + exportedExportsName, + shouldWrap, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsAssignmentsByName, + topLevelAssignments, + topLevelDefineCompiledEsmExpressions, + deconflictedExportNames, + code, + helpersName, + exportMode, + defaultIsModuleExports, + usesRequireWrapper, + requireName + ); + + if (shouldWrap) { + wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges); + } + + if (usesRequireWrapper) { + magicString.trim().indent('\t', { + exclude: indentExclusionRanges + }); + const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName; + magicString.prepend( + `var ${isRequiredName}; + +function ${requireName} () { +\tif (${isRequiredName}) return ${exported}; +\t${isRequiredName} = 1; +` + ).append(` +\treturn ${exported}; +}`); + if (exportMode === 'replace') { + magicString.prepend(`var ${exportsName};\n`); + } + } + + magicString + .trim() + .prepend(shebang + leadingComment + importBlock) + .append(exportBlock); + + return { + code: magicString.toString(), + map: sourceMap ? magicString.generateMap() : null, + syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', + meta: { commonjs: { ...commonjsMeta, shebang } } + }; +} + +const PLUGIN_NAME = 'commonjs'; + +function commonjs(options = {}) { + const { + ignoreGlobal, + ignoreDynamicRequires, + requireReturnsDefault: requireReturnsDefaultOption, + defaultIsModuleExports: defaultIsModuleExportsOption, + esmExternals + } = options; + const extensions = options.extensions || ['.js']; + const filter = createFilter$1(options.include, options.exclude); + const isPossibleCjsId = (id) => { + const extName = extname(id); + return extName === '.cjs' || (extensions.includes(extName) && filter(id)); + }; + + const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options); + + const getRequireReturnsDefault = + typeof requireReturnsDefaultOption === 'function' + ? requireReturnsDefaultOption + : () => requireReturnsDefaultOption; + + let esmExternalIds; + const isEsmExternal = + typeof esmExternals === 'function' + ? esmExternals + : Array.isArray(esmExternals) + ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) + : () => esmExternals; + + const getDefaultIsModuleExports = + typeof defaultIsModuleExportsOption === 'function' + ? defaultIsModuleExportsOption + : () => + typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto'; + + const dynamicRequireRoot = + typeof options.dynamicRequireRoot === 'string' + ? resolve$3(options.dynamicRequireRoot) + : process.cwd(); + const { commonDir, dynamicRequireModules } = getDynamicRequireModules( + options.dynamicRequireTargets, + dynamicRequireRoot + ); + const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0; + + const ignoreRequire = + typeof options.ignore === 'function' + ? options.ignore + : Array.isArray(options.ignore) + ? (id) => options.ignore.includes(id) + : () => false; + + const getIgnoreTryCatchRequireStatementMode = (id) => { + const mode = + typeof options.ignoreTryCatch === 'function' + ? options.ignoreTryCatch(id) + : Array.isArray(options.ignoreTryCatch) + ? options.ignoreTryCatch.includes(id) + : typeof options.ignoreTryCatch !== 'undefined' + ? options.ignoreTryCatch + : true; + + return { + canConvertRequire: mode !== 'remove' && mode !== true, + shouldRemoveRequire: mode === 'remove' + }; + }; + + const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId); + + const sourceMap = options.sourceMap !== false; + + // Initialized in buildStart + let requireResolver; + + function transformAndCheckExports(code, id) { + const normalizedId = normalizePathSlashes(id); + const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( + this.parse, + code, + id + ); + + const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {}; + if (hasDefaultExport) { + commonjsMeta.hasDefaultExport = true; + } + if (hasNamedExports) { + commonjsMeta.hasNamedExports = true; + } + + if ( + !dynamicRequireModules.has(normalizedId) && + (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || + (isEsModule && !options.transformMixedEsModules)) + ) { + commonjsMeta.isCommonJS = false; + return { meta: { commonjs: commonjsMeta } }; + } + + const needsRequireWrapper = + !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id)); + + const checkDynamicRequire = (position) => { + const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot); + + if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) { + this.error( + { + code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', + normalizedId, + normalizedDynamicRequireRoot, + message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1( + normalizedId + )}" or one of its parent directories.` + }, + position + ); + } + }; + + return transformCommonjs( + this.parse, + code, + id, + isEsModule, + ignoreGlobal || isEsModule, + ignoreRequire, + ignoreDynamicRequires && !isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + sourceMap, + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ast, + getDefaultIsModuleExports(id), + needsRequireWrapper, + requireResolver.resolveRequireSourcesAndUpdateMeta(this), + requireResolver.isRequiredId(id), + checkDynamicRequire, + commonjsMeta + ); + } + + return { + name: PLUGIN_NAME, + + version: version$3, + + options(rawOptions) { + // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver + // do not prevent our plugin from resolving entry points ot proxies. + const plugins = Array.isArray(rawOptions.plugins) + ? [...rawOptions.plugins] + : rawOptions.plugins + ? [rawOptions.plugins] + : []; + plugins.unshift({ + name: 'commonjs--resolver', + resolveId + }); + return { ...rawOptions, plugins }; + }, + + buildStart({ plugins }) { + validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup'); + const nodeResolve = plugins.find(({ name }) => name === 'node-resolve'); + if (nodeResolve) { + validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve'); + } + if (options.namedExports != null) { + this.warn( + 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' + ); + } + requireResolver = getRequireResolver( + extensions, + detectCyclesAndConditional, + currentlyResolving + ); + }, + + buildEnd() { + if (options.strictRequires === 'debug') { + const wrappedIds = requireResolver.getWrappedIds(); + if (wrappedIds.length) { + this.warn({ + code: 'WRAPPED_IDS', + ids: wrappedIds, + message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds + .map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`) + .join(',\n')}\n]` + }); + } else { + this.warn({ + code: 'WRAPPED_IDS', + ids: wrappedIds, + message: 'The commonjs plugin did not wrap any files.' + }); + } + } + }, + + load(id) { + if (id === HELPERS_ID) { + return getHelpersModule(); + } + + if (isWrappedId(id, MODULE_SUFFIX)) { + const name = getName(unwrapId$1(id, MODULE_SUFFIX)); + return { + code: `var ${name} = {exports: {}}; export {${name} as __module}`, + meta: { commonjs: { isCommonJS: false } } + }; + } + + if (isWrappedId(id, EXPORTS_SUFFIX)) { + const name = getName(unwrapId$1(id, EXPORTS_SUFFIX)); + return { + code: `var ${name} = {}; export {${name} as __exports}`, + meta: { commonjs: { isCommonJS: false } } + }; + } + + if (isWrappedId(id, EXTERNAL_SUFFIX)) { + const actualId = unwrapId$1(id, EXTERNAL_SUFFIX); + return getUnknownRequireProxy( + actualId, + isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true + ); + } + + // entry suffix is just appended to not mess up relative external resolution + if (id.endsWith(ENTRY_SUFFIX)) { + const acutalId = id.slice(0, -ENTRY_SUFFIX.length); + const { + meta: { commonjs: commonjsMeta } + } = this.getModuleInfo(acutalId); + const shebang = commonjsMeta?.shebang ?? ''; + return getEntryProxy( + acutalId, + getDefaultIsModuleExports(acutalId), + this.getModuleInfo, + shebang + ); + } + + if (isWrappedId(id, ES_IMPORT_SUFFIX)) { + const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX); + return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId)); + } + + if (id === DYNAMIC_MODULES_ID) { + return getDynamicModuleRegistry( + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ignoreDynamicRequires + ); + } + + if (isWrappedId(id, PROXY_SUFFIX)) { + const actualId = unwrapId$1(id, PROXY_SUFFIX); + return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load); + } + + return null; + }, + + shouldTransformCachedModule(...args) { + return requireResolver.shouldTransformCachedModule.call(this, ...args); + }, + + transform(code, id) { + if (!isPossibleCjsId(id)) return null; + + try { + return transformAndCheckExports.call(this, code, id); + } catch (err) { + return this.error(err, err.pos); + } + } + }; +} + +// 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; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +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: UrlType.Absolute, + }; +} +function parseUrl$2(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.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('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.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$4(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$4(url, type) { + const rel = type <= UrlType.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$2(input, base) { + if (!input && !base) + return ''; + const url = parseUrl$2(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl$2(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.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 UrlType.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$4(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 UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.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 UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +function resolve$1(input, base) { + // The base 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 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$2(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN$1 = 0; +const SOURCES_INDEX$1 = 1; +const SOURCE_LINE$1 = 2; +const SOURCE_COLUMN$1 = 3; +const NAMES_INDEX$1 = 4; + +function maybeSort(mappings, owned) { + 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, 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$1] < line[j - 1][COLUMN$1]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN$1] - b[COLUMN$1]; +} + +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]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN$1] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN$1] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN$1] !== needle) + break; + } + return index; +} +function memoizedState() { + 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. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // 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)); +} + +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)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * 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`. + */ +let traceSegment; +/** + * 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. + */ +let originalPositionFor$1; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : 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; + const from = resolve$1(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve$1(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + 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, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + originalPositionFor$1 = (map, { line, column, bias }) => { + 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, 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$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null); + }; +})(); +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + 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; +} + +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +let get; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +let put; +/** + * 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. + */ +class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +} +(() => { + get = (strarr, key) => strarr._indexes[key]; + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; +})(); + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +const NO_NAME = -1; +/** + * 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. + */ +let maybeAddSegment; +/** + * Adds/removes the content of the source file to the source map. + */ +let setSourceContent; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toDecodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toEncodedMap; +// This split declaration is only so that terser can elminiate the static initialization block. +let addSegmentInternal; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } +} +(() => { + maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + toEncodedMap = (map) => { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) }); + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? 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 getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[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 skipSourceless(line, index) { + // 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, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // 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)); +} + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; +} +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build$2(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build$2(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build$2(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +var src$2 = {exports: {}}; + +var node$1 = {exports: {}}; + +/** + * Helpers. + */ + +var ms$1; +var hasRequiredMs$1; + +function requireMs$1 () { + if (hasRequiredMs$1) return ms$1; + hasRequiredMs$1 = 1; + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + ms$1 = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + return ms$1; +} + +var common$b; +var hasRequiredCommon; + +function requireCommon () { + if (hasRequiredCommon) return common$b; + hasRequiredCommon = 1; + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs$1(); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + common$b = setup; + return common$b; +} + +/** + * Module dependencies. + */ + +var hasRequiredNode$1; + +function requireNode$1 () { + if (hasRequiredNode$1) return node$1.exports; + hasRequiredNode$1 = 1; + (function (module, exports) { + const tty = require$$0$3; + const util = require$$0$6; + + /** + * This is the Node.js implementation of `debug()`. + */ + + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' + ); + + /** + * Colors. + */ + + exports.colors = [6, 2, 3, 4, 5, 1]; + + try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. + } + + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; + }, {}); + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + + function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); + } + + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } + } + + function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; + } + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); + } + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + function load() { + return process.env.DEBUG; + } + + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %o to `util.inspect()`, all on a single line. + */ + + formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); + }; + + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + } (node$1, node$1.exports)); + return node$1.exports; +} + +var browser$3 = {exports: {}}; + +/* eslint-env browser */ + +var hasRequiredBrowser$1; + +function requireBrowser$1 () { + if (hasRequiredBrowser$1) return browser$3.exports; + hasRequiredBrowser$1 = 1; + (function (module, exports) { + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + } (browser$3, browser$3.exports)); + return browser$3.exports; +} + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + src$2.exports = requireBrowser$1(); +} else { + src$2.exports = requireNode$1(); +} + +var srcExports$1 = src$2.exports; +var debug$i = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1); + +let pnp; +if (process.versions.pnp) { + try { + pnp = createRequire$1(import.meta.url)('pnpapi'); + } + catch { } +} +function invalidatePackageData(packageCache, pkgPath) { + const pkgDir = path$o.dirname(pkgPath); + packageCache.forEach((pkg, cacheKey) => { + if (pkg.dir === pkgDir) { + packageCache.delete(cacheKey); + } + }); +} +function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) { + if (pnp) { + const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); + if (packageCache?.has(cacheKey)) + return packageCache.get(cacheKey); + try { + const pkg = pnp.resolveToUnqualified(pkgName, basedir, { + considerBuiltins: false, + }); + if (!pkg) + return null; + const pkgData = loadPackageData(path$o.join(pkg, 'package.json')); + packageCache?.set(cacheKey, pkgData); + return pkgData; + } + catch { + return null; + } + } + const originalBasedir = basedir; + while (basedir) { + if (packageCache) { + const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks); + if (cached) + return cached; + } + const pkg = path$o.join(basedir, 'node_modules', pkgName, 'package.json'); + try { + if (fs$l.existsSync(pkg)) { + const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg); + const pkgData = loadPackageData(pkgPath); + if (packageCache) { + setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks); + } + return pkgData; + } + } + catch { } + const nextBasedir = path$o.dirname(basedir); + if (nextBasedir === basedir) + break; + basedir = nextBasedir; + } + return null; +} +function findNearestPackageData(basedir, packageCache) { + const originalBasedir = basedir; + while (basedir) { + if (packageCache) { + const cached = getFnpdCache(packageCache, basedir, originalBasedir); + if (cached) + return cached; + } + const pkgPath = path$o.join(basedir, 'package.json'); + if (tryStatSync(pkgPath)?.isFile()) { + try { + const pkgData = loadPackageData(pkgPath); + if (packageCache) { + setFnpdCache(packageCache, pkgData, basedir, originalBasedir); + } + return pkgData; + } + catch { } + } + const nextBasedir = path$o.dirname(basedir); + if (nextBasedir === basedir) + break; + basedir = nextBasedir; + } + return null; +} +// Finds the nearest package.json with a `name` field +function findNearestMainPackageData(basedir, packageCache) { + const nearestPackage = findNearestPackageData(basedir, packageCache); + return (nearestPackage && + (nearestPackage.data.name + ? nearestPackage + : findNearestMainPackageData(path$o.dirname(nearestPackage.dir), packageCache))); +} +function loadPackageData(pkgPath) { + const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8')); + const pkgDir = path$o.dirname(pkgPath); + const { sideEffects } = data; + let hasSideEffects; + if (typeof sideEffects === 'boolean') { + hasSideEffects = () => sideEffects; + } + else if (Array.isArray(sideEffects)) { + const finalPackageSideEffects = sideEffects.map((sideEffect) => { + /* + * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css. + * https://webpack.js.org/guides/tree-shaking/ + * https://github.com/vitejs/vite/pull/11807 + */ + if (sideEffect.includes('/')) { + return sideEffect; + } + return `**/${sideEffect}`; + }); + hasSideEffects = createFilter(finalPackageSideEffects, null, { + resolve: pkgDir, + }); + } + else { + hasSideEffects = () => null; + } + const pkg = { + dir: pkgDir, + data, + hasSideEffects, + webResolvedImports: {}, + nodeResolvedImports: {}, + setResolvedCache(key, entry, targetWeb) { + if (targetWeb) { + pkg.webResolvedImports[key] = entry; + } + else { + pkg.nodeResolvedImports[key] = entry; + } + }, + getResolvedCache(key, targetWeb) { + if (targetWeb) { + return pkg.webResolvedImports[key]; + } + else { + return pkg.nodeResolvedImports[key]; + } + }, + }; + return pkg; +} +function watchPackageDataPlugin(packageCache) { + // a list of files to watch before the plugin is ready + const watchQueue = new Set(); + const watchedDirs = new Set(); + const watchFileStub = (id) => { + watchQueue.add(id); + }; + let watchFile = watchFileStub; + const setPackageData = packageCache.set.bind(packageCache); + packageCache.set = (id, pkg) => { + if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) { + watchedDirs.add(pkg.dir); + watchFile(path$o.join(pkg.dir, 'package.json')); + } + return setPackageData(id, pkg); + }; + return { + name: 'vite:watch-package-data', + buildStart() { + watchFile = this.addWatchFile.bind(this); + watchQueue.forEach(watchFile); + watchQueue.clear(); + }, + buildEnd() { + watchFile = watchFileStub; + }, + watchChange(id) { + if (id.endsWith('/package.json')) { + invalidatePackageData(packageCache, path$o.normalize(id)); + } + }, + handleHotUpdate({ file }) { + if (file.endsWith('/package.json')) { + invalidatePackageData(packageCache, path$o.normalize(file)); + } + }, + }; +} +/** + * Get cached `resolvePackageData` value based on `basedir`. When one is found, + * and we've already traversed some directories between `basedir` and `originalBasedir`, + * we cache the value for those in-between directories as well. + * + * This makes it so the fs is only read once for a shared `basedir`. + */ +function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) { + const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); + const pkgData = packageCache.get(cacheKey); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); + }); + return pkgData; + } +} +function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) { + packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); + }); +} +// package cache key for `resolvePackageData` +function getRpdCacheKey(pkgName, basedir, preserveSymlinks) { + return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`; +} +/** + * Get cached `findNearestPackageData` value based on `basedir`. When one is found, + * and we've already traversed some directories between `basedir` and `originalBasedir`, + * we cache the value for those in-between directories as well. + * + * This makes it so the fs is only read once for a shared `basedir`. + */ +function getFnpdCache(packageCache, basedir, originalBasedir) { + const cacheKey = getFnpdCacheKey(basedir); + const pkgData = packageCache.get(cacheKey); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getFnpdCacheKey(dir), pkgData); + }); + return pkgData; + } +} +function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) { + packageCache.set(getFnpdCacheKey(basedir), pkgData); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getFnpdCacheKey(dir), pkgData); + }); +} +// package cache key for `findNearestPackageData` +function getFnpdCacheKey(basedir) { + return `fnpd_${basedir}`; +} +/** + * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. + * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` + * @param shorterDir Shorter dir path, e.g. `/User/foo` + */ +function traverseBetweenDirs(longerDir, shorterDir, cb) { + while (longerDir !== shorterDir) { + cb(longerDir); + longerDir = path$o.dirname(longerDir); + } +} + +const createFilter = createFilter$1; +const windowsSlashRE = /\\/g; +function slash$1(p) { + return p.replace(windowsSlashRE, '/'); +} +/** + * Prepend `/@id/` and replace null byte so the id is URL-safe. + * This is prepended to resolved ids that are not valid browser + * import specifiers by the importAnalysis plugin. + */ +function wrapId(id) { + return id.startsWith(VALID_ID_PREFIX) + ? id + : VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER); +} +/** + * Undo {@link wrapId}'s `/@id/` and null byte replacements. + */ +function unwrapId(id) { + return id.startsWith(VALID_ID_PREFIX) + ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0') + : id; +} +const replaceSlashOrColonRE = /[/:]/g; +const replaceDotRE = /\./g; +const replaceNestedIdRE = /(\s*>\s*)/g; +const replaceHashRE = /#/g; +const flattenId = (id) => { + const flatId = limitFlattenIdLength(id + .replace(replaceSlashOrColonRE, '_') + .replace(replaceDotRE, '__') + .replace(replaceNestedIdRE, '___') + .replace(replaceHashRE, '____')); + return flatId; +}; +const FLATTEN_ID_HASH_LENGTH = 8; +const FLATTEN_ID_MAX_FILE_LENGTH = 170; +const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => { + if (id.length <= limit) { + return id; + } + return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + '_' + getHash(id); +}; +const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > '); +// Supported by Node, Deno, Bun +const NODE_BUILTIN_NAMESPACE = 'node:'; +// Supported by Deno +const NPM_BUILTIN_NAMESPACE = 'npm:'; +// Supported by Bun +const BUN_BUILTIN_NAMESPACE = 'bun:'; +// Some runtimes like Bun injects namespaced modules here, which is not a node builtin +const nodeBuiltins = builtinModules.filter((id) => !id.includes(':')); +// TODO: Use `isBuiltin` from `node:module`, but Deno doesn't support it +function isBuiltin(id) { + if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) + return true; + if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) + return true; + return isNodeBuiltin(id); +} +function isNodeBuiltin(id) { + if (id.startsWith(NODE_BUILTIN_NAMESPACE)) + return true; + return nodeBuiltins.includes(id); +} +function isInNodeModules$1(id) { + return id.includes('node_modules'); +} +function moduleListContains(moduleList, id) { + return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m))); +} +function isOptimizable(id, optimizeDeps) { + const { extensions } = optimizeDeps; + return (OPTIMIZABLE_ENTRY_RE.test(id) || + (extensions?.some((ext) => id.endsWith(ext)) ?? false)); +} +const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/; +const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; +// TODO: use import() +const _require$1 = createRequire$1(import.meta.url); +function resolveDependencyVersion(dep, pkgRelativePath = '../../package.json') { + const pkgPath = path$o.resolve(_require$1.resolve(dep), pkgRelativePath); + return JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8')).version; +} +const rollupVersion = resolveDependencyVersion('rollup'); +// set in bin/vite.js +const filter = process.env.VITE_DEBUG_FILTER; +const DEBUG = process.env.DEBUG; +function createDebugger(namespace, options = {}) { + const log = debug$i(namespace); + const { onlyWhenFocused } = options; + let enabled = log.enabled; + if (enabled && onlyWhenFocused) { + const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; + enabled = !!DEBUG?.includes(ns); + } + if (enabled) { + return (...args) => { + if (!filter || args.some((a) => a?.includes?.(filter))) { + log(...args); + } + }; + } +} +function testCaseInsensitiveFS() { + if (!CLIENT_ENTRY.endsWith('client.mjs')) { + throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); + } + if (!fs$l.existsSync(CLIENT_ENTRY)) { + throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + + CLIENT_ENTRY); + } + return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')); +} +const urlCanParse = URL$3.canParse ?? + // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+ + ((path, base) => { + try { + new URL$3(path, base); + return true; + } + catch { + return false; + } + }); +const isCaseInsensitiveFS = testCaseInsensitiveFS(); +const isWindows$3 = os$4.platform() === 'win32'; +const VOLUME_RE = /^[A-Z]:/i; +function normalizePath$3(id) { + return path$o.posix.normalize(isWindows$3 ? slash$1(id) : id); +} +function fsPathFromId(id) { + const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); + return fsPath[0] === '/' || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`; +} +function fsPathFromUrl(url) { + return fsPathFromId(cleanUrl(url)); +} +function withTrailingSlash(path) { + if (path[path.length - 1] !== '/') { + return `${path}/`; + } + return path; +} +/** + * Check if dir is a parent of file + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param dir - normalized absolute path + * @param file - normalized absolute path + * @returns true if dir is a parent of file + */ +function isParentDirectory(dir, file) { + dir = withTrailingSlash(dir); + return (file.startsWith(dir) || + (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))); +} +/** + * Check if 2 file name are identical + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param file1 - normalized absolute path + * @param file2 - normalized absolute path + * @returns true if both files url are identical + */ +function isSameFileUri(file1, file2) { + return (file1 === file2 || + (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase())); +} +const postfixRE = /[?#].*$/; +function cleanUrl(url) { + return url.replace(postfixRE, ''); +} +const externalRE = /^(https?:)?\/\//; +const isExternalUrl = (url) => externalRE.test(url); +const dataUrlRE = /^\s*data:/i; +const isDataUrl = (url) => dataUrlRE.test(url); +const virtualModuleRE = /^virtual-module:.*/; +const virtualModulePrefix = 'virtual-module:'; +const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/; +const isJSRequest = (url) => { + url = cleanUrl(url); + if (knownJsSrcRE.test(url)) { + return true; + } + if (!path$o.extname(url) && url[url.length - 1] !== '/') { + return true; + } + return false; +}; +const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/; +const isTsRequest = (url) => knownTsRE.test(url); +const importQueryRE = /(\?|&)import=?(?:&|$)/; +const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/; +const internalPrefixes = [ + FS_PREFIX, + VALID_ID_PREFIX, + CLIENT_PUBLIC_PATH, + ENV_PUBLIC_PATH, +]; +const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`); +const trailingSeparatorRE = /[?&]$/; +const isImportRequest = (url) => importQueryRE.test(url); +const isInternalRequest = (url) => InternalPrefixRE.test(url); +function removeImportQuery(url) { + return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, ''); +} +function removeDirectQuery(url) { + return url.replace(directRequestRE$1, '$1').replace(trailingSeparatorRE, ''); +} +const urlRE = /(\?|&)url(?:&|$)/; +const rawRE = /(\?|&)raw(?:&|$)/; +function removeUrlQuery(url) { + return url.replace(urlRE, '$1').replace(trailingSeparatorRE, ''); +} +const replacePercentageRE = /%/g; +function injectQuery(url, queryToInject) { + // encode percents for consistent behavior with pathToFileURL + // see #2614 for details + const resolvedUrl = new URL$3(url.replace(replacePercentageRE, '%25'), 'relative:///'); + const { search, hash } = resolvedUrl; + let pathname = cleanUrl(url); + pathname = isWindows$3 ? slash$1(pathname) : pathname; + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash ?? ''}`; +} +const timestampRE = /\bt=\d{13}&?\b/; +function removeTimestampQuery(url) { + return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); +} +async function asyncReplace(input, re, replacer) { + let match; + let remaining = input; + let rewritten = ''; + while ((match = re.exec(remaining))) { + rewritten += remaining.slice(0, match.index); + rewritten += await replacer(match); + remaining = remaining.slice(match.index + match[0].length); + } + rewritten += remaining; + return rewritten; +} +function timeFrom(start, subtract = 0) { + const time = performance.now() - start - subtract; + const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' '); + if (time < 10) { + return colors$1.green(timeString); + } + else if (time < 50) { + return colors$1.yellow(timeString); + } + else { + return colors$1.red(timeString); + } +} +/** + * pretty url for logging. + */ +function prettifyUrl(url, root) { + url = removeTimestampQuery(url); + const isAbsoluteFile = url.startsWith(root); + if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { + const file = path$o.posix.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); + return colors$1.dim(file); + } + else { + return colors$1.dim(url); + } +} +function isObject$1(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +function isDefined(value) { + return value != null; +} +function tryStatSync(file) { + try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist + return fs$l.statSync(file, { throwIfNoEntry: false }); + } + catch { + // Ignore errors + } +} +function lookupFile(dir, fileNames) { + while (dir) { + for (const fileName of fileNames) { + const fullPath = path$o.join(dir, fileName); + if (tryStatSync(fullPath)?.isFile()) + return fullPath; + } + const parentDir = path$o.dirname(dir); + if (parentDir === dir) + return; + dir = parentDir; + } +} +function isFilePathESM(filePath, packageCache) { + if (/\.m[jt]s$/.test(filePath)) { + return true; + } + else if (/\.c[jt]s$/.test(filePath)) { + return false; + } + else { + // check package.json for type: "module" + try { + const pkg = findNearestPackageData(path$o.dirname(filePath), packageCache); + return pkg?.data.type === 'module'; + } + catch { + return false; + } + } +} +const splitRE = /\r?\n/; +const range = 2; +function pad$1(source, n = 2) { + const lines = source.split(splitRE); + return lines.map((l) => ` `.repeat(n) + l).join(`\n`); +} +function posToNumber(source, pos) { + if (typeof pos === 'number') + return pos; + const lines = source.split(splitRE); + const { line, column } = pos; + let start = 0; + for (let i = 0; i < line - 1 && i < lines.length; i++) { + start += lines[i].length + 1; + } + return start + column; +} +function numberToPos(source, offset) { + if (typeof offset !== 'number') + return offset; + if (offset > source.length) { + throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); + } + const lines = source.split(splitRE); + let counted = 0; + let line = 0; + let column = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + 1; + if (counted + lineLength >= offset) { + column = offset - counted + 1; + break; + } + counted += lineLength; + } + return { line: line + 1, column }; +} +function generateCodeFrame(source, start = 0, end) { + start = Math.max(posToNumber(source, start), 0); + end = Math.min(end !== undefined ? posToNumber(source, end) : start, source.length); + const lines = source.split(splitRE); + let count = 0; + const res = []; + for (let i = 0; i < lines.length; i++) { + count += lines[i].length; + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) + continue; + const line = j + 1; + res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); + const lineLength = lines[j].length; + if (j === i) { + // push underline + const pad = Math.max(start - (count - lineLength), 0); + const length = Math.max(1, end > count ? lineLength - pad : end - start); + res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); + } + else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1); + res.push(` | ` + '^'.repeat(length)); + } + count += lineLength + 1; + } + } + break; + } + count++; + } + return res.join('\n'); +} +function isFileReadable(filename) { + if (!tryStatSync(filename)) { + return false; + } + try { + // Check if current process has read permission to the file + fs$l.accessSync(filename, fs$l.constants.R_OK); + return true; + } + catch { + return false; + } +} +const splitFirstDirRE = /(.+?)[\\/](.+)/; +/** + * Delete every file and subdirectory. **The given directory must exist.** + * Pass an optional `skip` array to preserve files under the root directory. + */ +function emptyDir(dir, skip) { + const skipInDir = []; + let nested = null; + if (skip?.length) { + for (const file of skip) { + if (path$o.dirname(file) !== '.') { + const matched = file.match(splitFirstDirRE); + if (matched) { + nested ??= new Map(); + const [, nestedDir, skipPath] = matched; + let nestedSkip = nested.get(nestedDir); + if (!nestedSkip) { + nestedSkip = []; + nested.set(nestedDir, nestedSkip); + } + if (!nestedSkip.includes(skipPath)) { + nestedSkip.push(skipPath); + } + } + } + else { + skipInDir.push(file); + } + } + } + for (const file of fs$l.readdirSync(dir)) { + if (skipInDir.includes(file)) { + continue; + } + if (nested?.has(file)) { + emptyDir(path$o.resolve(dir, file), nested.get(file)); + } + else { + fs$l.rmSync(path$o.resolve(dir, file), { recursive: true, force: true }); + } + } +} +function copyDir(srcDir, destDir) { + fs$l.mkdirSync(destDir, { recursive: true }); + for (const file of fs$l.readdirSync(srcDir)) { + const srcFile = path$o.resolve(srcDir, file); + if (srcFile === destDir) { + continue; + } + const destFile = path$o.resolve(destDir, file); + const stat = fs$l.statSync(srcFile); + if (stat.isDirectory()) { + copyDir(srcFile, destFile); + } + else { + fs$l.copyFileSync(srcFile, destFile); + } + } +} +const ERR_SYMLINK_IN_RECURSIVE_READDIR = 'ERR_SYMLINK_IN_RECURSIVE_READDIR'; +async function recursiveReaddir(dir) { + if (!fs$l.existsSync(dir)) { + return []; + } + let dirents; + try { + dirents = await fsp.readdir(dir, { withFileTypes: true }); + } + catch (e) { + if (e.code === 'EACCES') { + // Ignore permission errors + return []; + } + throw e; + } + if (dirents.some((dirent) => dirent.isSymbolicLink())) { + const err = new Error('Symbolic links are not supported in recursiveReaddir'); + err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR; + throw err; + } + const files = await Promise.all(dirents.map((dirent) => { + const res = path$o.resolve(dir, dirent.name); + return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res); + })); + return files.flat(1); +} +// `fs.realpathSync.native` resolves differently in Windows network drive, +// causing file read errors. skip for now. +// https://github.com/nodejs/node/issues/37737 +let safeRealpathSync = isWindows$3 + ? windowsSafeRealPathSync + : fs$l.realpathSync.native; +// Based on https://github.com/larrybahr/windows-network-drive +// MIT License, Copyright (c) 2017 Larry Bahr +const windowsNetworkMap = new Map(); +function windowsMappedRealpathSync(path) { + const realPath = fs$l.realpathSync.native(path); + if (realPath.startsWith('\\\\')) { + for (const [network, volume] of windowsNetworkMap) { + if (realPath.startsWith(network)) + return realPath.replace(network, volume); + } + } + return realPath; +} +const parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/; +let firstSafeRealPathSyncRun = false; +function windowsSafeRealPathSync(path) { + if (!firstSafeRealPathSyncRun) { + optimizeSafeRealPathSync(); + firstSafeRealPathSyncRun = true; + } + return fs$l.realpathSync(path); +} +function optimizeSafeRealPathSync() { + // Skip if using Node <18.10 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931 + const nodeVersion = process.versions.node.split('.').map(Number); + if (nodeVersion[0] < 18 || (nodeVersion[0] === 18 && nodeVersion[1] < 10)) { + safeRealpathSync = fs$l.realpathSync; + return; + } + // Check the availability `fs.realpathSync.native` + // in Windows virtual and RAM disks that bypass the Volume Mount Manager, in programs such as imDisk + // get the error EISDIR: illegal operation on a directory + try { + fs$l.realpathSync.native(path$o.resolve('./')); + } + catch (error) { + if (error.message.includes('EISDIR: illegal operation on a directory')) { + safeRealpathSync = fs$l.realpathSync; + return; + } + } + exec('net use', (error, stdout) => { + if (error) + return; + const lines = stdout.split('\n'); + // OK Y: \\NETWORKA\Foo Microsoft Windows Network + // OK Z: \\NETWORKA\Bar Microsoft Windows Network + for (const line of lines) { + const m = line.match(parseNetUseRE); + if (m) + windowsNetworkMap.set(m[3], m[2]); + } + if (windowsNetworkMap.size === 0) { + safeRealpathSync = fs$l.realpathSync.native; + } + else { + safeRealpathSync = windowsMappedRealpathSync; + } + }); +} +function ensureWatchedFile(watcher, file, root) { + if (file && + // only need to watch if out of root + !file.startsWith(withTrailingSlash(root)) && + // some rollup plugins use null bytes for private resolved Ids + !file.includes('\0') && + fs$l.existsSync(file)) { + // resolve file to normalized system path + watcher.add(path$o.resolve(file)); + } +} +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; +const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/; +function joinSrcset(ret) { + return ret + .map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : '')) + .join(', '); +} +function splitSrcSetDescriptor(srcs) { + return splitSrcSet(srcs) + .map((s) => { + const src = s.replace(escapedSpaceCharacters, ' ').trim(); + const url = imageSetUrlRE.exec(src)?.[0] ?? ''; + return { + url, + descriptor: src.slice(url.length).trim(), + }; + }) + .filter(({ url }) => !!url); +} +function processSrcSet(srcs, replacer) { + return Promise.all(splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({ + url: await replacer({ url, descriptor }), + descriptor, + }))).then(joinSrcset); +} +function processSrcSetSync(srcs, replacer) { + return joinSrcset(splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({ + url: replacer({ url, descriptor }), + descriptor, + }))); +} +const cleanSrcSetRE = /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'|data:\w+\/[\w.+\-]+;base64,[\w+/=]+/g; +function splitSrcSet(srcs) { + const parts = []; + // There could be a ',' inside of url(data:...), linear-gradient(...), "data:..." or data:... + const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer); + let startIndex = 0; + let splitIndex; + do { + splitIndex = cleanedSrcs.indexOf(',', startIndex); + parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined)); + startIndex = splitIndex + 1; + } while (splitIndex !== -1); + return parts; +} +const windowsDriveRE = /^[A-Z]:/; +const replaceWindowsDriveRE = /^([A-Z]):\//; +const linuxAbsolutePathRE = /^\/[^/]/; +function escapeToLinuxLikePath(path) { + if (windowsDriveRE.test(path)) { + return path.replace(replaceWindowsDriveRE, '/windows/$1/'); + } + if (linuxAbsolutePathRE.test(path)) { + return `/linux${path}`; + } + return path; +} +const revertWindowsDriveRE = /^\/windows\/([A-Z])\//; +function unescapeToLinuxLikePath(path) { + if (path.startsWith('/linux/')) { + return path.slice('/linux'.length); + } + if (path.startsWith('/windows/')) { + return path.replace(revertWindowsDriveRE, '$1:/'); + } + return path; +} +// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 +const nullSourceMap = { + names: [], + sources: [], + mappings: '', + version: 3, +}; +function combineSourcemaps(filename, sourcemapList) { + if (sourcemapList.length === 0 || + sourcemapList.every((m) => m.sources.length === 0)) { + return { ...nullSourceMap }; + } + // hack for parse broken with normalized absolute paths on windows (C:/path/to/something). + // escape them to linux like paths + // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442) + sourcemapList = sourcemapList.map((sourcemap) => { + const newSourcemaps = { ...sourcemap }; + newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null); + if (sourcemap.sourceRoot) { + newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot); + } + return newSourcemaps; + }); + const escapedFilename = escapeToLinuxLikePath(filename); + // We don't declare type here so we can convert/fake/map as RawSourceMap + let map; //: SourceMap + let mapIndex = 1; + const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; + if (useArrayInterface) { + map = remapping(sourcemapList, () => null); + } + else { + map = remapping(sourcemapList[0], function loader(sourcefile) { + if (sourcefile === escapedFilename && sourcemapList[mapIndex]) { + return sourcemapList[mapIndex++]; + } + else { + return null; + } + }); + } + if (!map.file) { + delete map.file; + } + // unescape the previous hack + map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source); + map.file = filename; + return map; +} +function unique(arr) { + return Array.from(new Set(arr)); +} +/** + * Returns resolved localhost address when `dns.lookup` result differs from DNS + * + * `dns.lookup` result is same when defaultResultOrder is `verbatim`. + * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same. + * For example, when IPv6 is not supported on that machine/network. + */ +async function getLocalhostAddressIfDiffersFromDNS() { + const [nodeResult, dnsResult] = await Promise.all([ + promises.lookup('localhost'), + promises.lookup('localhost', { verbatim: true }), + ]); + const isSame = nodeResult.family === dnsResult.family && + nodeResult.address === dnsResult.address; + return isSame ? undefined : nodeResult.address; +} +function diffDnsOrderChange(oldUrls, newUrls) { + return !(oldUrls === newUrls || + (oldUrls && + newUrls && + arrayEqual(oldUrls.local, newUrls.local) && + arrayEqual(oldUrls.network, newUrls.network))); +} +async function resolveHostname(optionsHost) { + let host; + if (optionsHost === undefined || optionsHost === false) { + // Use a secure default + host = 'localhost'; + } + else if (optionsHost === true) { + // If passed --host in the CLI without arguments + host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) + } + else { + host = optionsHost; + } + // Set host name to localhost when possible + let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host; + if (host === 'localhost') { + // See #8647 for more details. + const localhostAddr = await getLocalhostAddressIfDiffersFromDNS(); + if (localhostAddr) { + name = localhostAddr; + } + } + return { host, name }; +} +async function resolveServerUrls(server, options, config) { + const address = server.address(); + const isAddressInfo = (x) => x?.address; + if (!isAddressInfo(address)) { + return { local: [], network: [] }; + } + const local = []; + const network = []; + const hostname = await resolveHostname(options.host); + const protocol = options.https ? 'https' : 'http'; + const port = address.port; + const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase; + if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) { + let hostnameName = hostname.name; + // ipv6 host + if (hostnameName.includes(':')) { + hostnameName = `[${hostnameName}]`; + } + const address = `${protocol}://${hostnameName}:${port}${base}`; + if (loopbackHosts.has(hostname.host)) { + local.push(address); + } + else { + network.push(address); + } + } + else { + Object.values(os$4.networkInterfaces()) + .flatMap((nInterface) => nInterface ?? []) + .filter((detail) => detail && + detail.address && + (detail.family === 'IPv4' || + // @ts-expect-error Node 18.0 - 18.3 returns number + detail.family === 4)) + .forEach((detail) => { + let host = detail.address.replace('127.0.0.1', hostname.name); + // ipv6 host + if (host.includes(':')) { + host = `[${host}]`; + } + const url = `${protocol}://${host}:${port}${base}`; + if (detail.address.includes('127.0.0.1')) { + local.push(url); + } + else { + network.push(url); + } + }); + } + return { local, network }; +} +function arraify(target) { + return Array.isArray(target) ? target : [target]; +} +// Taken from https://stackoverflow.com/a/36328890 +const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g; +const singlelineCommentsRE = /\/\/.*/g; +const requestQuerySplitRE = /\?(?!.*[/|}])/; +const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/; +const blankReplacer = (match) => ' '.repeat(match.length); +function getHash(text, length = 8) { + const h = createHash$2('sha256').update(text).digest('hex').substring(0, length); + if (length <= 64) + return h; + return h.padEnd(length, '_'); +} +const _dirname = path$o.dirname(fileURLToPath(import.meta.url)); +const requireResolveFromRootWithFallback = (root, id) => { + // check existence first, so if the package is not found, + // it won't be cached by nodejs, since there isn't a way to invalidate them: + // https://github.com/nodejs/node/issues/44663 + const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname); + if (!found) { + const error = new Error(`${JSON.stringify(id)} not found.`); + error.code = 'MODULE_NOT_FOUND'; + throw error; + } + // actually resolve + // Search in the root directory first, and fallback to the default require paths. + return _require$1.resolve(id, { paths: [root, _dirname] }); +}; +function emptyCssComments(raw) { + return raw.replace(multilineCommentsRE, blankReplacer); +} +function backwardCompatibleWorkerPlugins(plugins) { + if (Array.isArray(plugins)) { + return plugins; + } + if (typeof plugins === 'function') { + return plugins(); + } + return []; +} +function mergeConfigRecursively(defaults, overrides, rootPath) { + const merged = { ...defaults }; + for (const key in overrides) { + const value = overrides[key]; + if (value == null) { + continue; + } + const existing = merged[key]; + if (existing == null) { + merged[key] = value; + continue; + } + // fields that require special handling + if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) { + merged[key] = mergeAlias(existing, value); + continue; + } + else if (key === 'assetsInclude' && rootPath === '') { + merged[key] = [].concat(existing, value); + continue; + } + else if (key === 'noExternal' && + rootPath === 'ssr' && + (existing === true || value === true)) { + merged[key] = true; + continue; + } + else if (key === 'plugins' && rootPath === 'worker') { + merged[key] = () => [ + ...backwardCompatibleWorkerPlugins(existing), + ...backwardCompatibleWorkerPlugins(value), + ]; + continue; + } + if (Array.isArray(existing) || Array.isArray(value)) { + merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])]; + continue; + } + if (isObject$1(existing) && isObject$1(value)) { + merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key); + continue; + } + merged[key] = value; + } + return merged; +} +function mergeConfig(defaults, overrides, isRoot = true) { + if (typeof defaults === 'function' || typeof overrides === 'function') { + throw new Error(`Cannot merge config in form of callback`); + } + return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); +} +function mergeAlias(a, b) { + if (!a) + return b; + if (!b) + return a; + if (isObject$1(a) && isObject$1(b)) { + return { ...a, ...b }; + } + // the order is flipped because the alias is resolved from top-down, + // where the later should have higher priority + return [...normalizeAlias(b), ...normalizeAlias(a)]; +} +function normalizeAlias(o = []) { + return Array.isArray(o) + ? o.map(normalizeSingleAlias) + : Object.keys(o).map((find) => normalizeSingleAlias({ + find, + replacement: o[find], + })); +} +// https://github.com/vitejs/vite/issues/1363 +// work around https://github.com/rollup/plugins/issues/759 +function normalizeSingleAlias({ find, replacement, customResolver, }) { + if (typeof find === 'string' && + find[find.length - 1] === '/' && + replacement[replacement.length - 1] === '/') { + find = find.slice(0, find.length - 1); + replacement = replacement.slice(0, replacement.length - 1); + } + const alias = { + find, + replacement, + }; + if (customResolver) { + alias.customResolver = customResolver; + } + return alias; +} +/** + * Transforms transpiled code result where line numbers aren't altered, + * so we can skip sourcemap generation during dev + */ +function transformStableResult(s, id, config) { + return { + code: s.toString(), + map: config.command === 'build' && config.build.sourcemap + ? s.generateMap({ hires: 'boundary', source: id }) + : null, + }; +} +async function asyncFlatten(arr) { + do { + arr = (await Promise.all(arr)).flat(Infinity); + } while (arr.some((v) => v?.then)); + return arr; +} +// strip UTF-8 BOM +function stripBomTag(content) { + if (content.charCodeAt(0) === 0xfeff) { + return content.slice(1); + } + return content; +} +const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/; +/** + * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something) + * this function returns false for them but true for absolute paths (e.g. C:/something) + */ +const isNonDriveRelativeAbsolutePath = (p) => { + if (!isWindows$3) + return p[0] === '/'; + return windowsDrivePathPrefixRE.test(p); +}; +/** + * Determine if a file is being requested with the correct case, to ensure + * consistent behavior between dev and prod and across operating systems. + */ +function shouldServeFile(filePath, root) { + // can skip case check on Linux + if (!isCaseInsensitiveFS) + return true; + return hasCorrectCase(filePath, root); +} +/** + * Note that we can't use realpath here, because we don't want to follow + * symlinks. + */ +function hasCorrectCase(file, assets) { + if (file === assets) + return true; + const parent = path$o.dirname(file); + if (fs$l.readdirSync(parent).includes(path$o.basename(file))) { + return hasCorrectCase(parent, assets); + } + return false; +} +function joinUrlSegments(a, b) { + if (!a || !b) { + return a || b || ''; + } + if (a[a.length - 1] === '/') { + a = a.substring(0, a.length - 1); + } + if (b[0] !== '/') { + b = '/' + b; + } + return a + b; +} +function removeLeadingSlash(str) { + return str[0] === '/' ? str.slice(1) : str; +} +function stripBase(path, base) { + if (path === base) { + return '/'; + } + const devBase = withTrailingSlash(base); + return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path; +} +function arrayEqual(a, b) { + if (a === b) + return true; + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) + return false; + } + return true; +} +function evalValue(rawValue) { + const fn = new Function(` + var console, exports, global, module, process, require + return (\n${rawValue}\n) + `); + return fn(); +} +function getNpmPackageName(importPath) { + const parts = importPath.split('/'); + if (parts[0][0] === '@') { + if (!parts[1]) + return null; + return `${parts[0]}/${parts[1]}`; + } + else { + return parts[0]; + } +} +const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; +function escapeRegex(str) { + return str.replace(escapeRegexRE, '\\$&'); +} +function getPackageManagerCommand(type = 'install') { + const packageManager = process.env.npm_config_user_agent?.split(' ')[0].split('/')[0] || 'npm'; + switch (type) { + case 'install': + return packageManager === 'npm' ? 'npm install' : `${packageManager} add`; + case 'uninstall': + return packageManager === 'npm' + ? 'npm uninstall' + : `${packageManager} remove`; + case 'update': + return packageManager === 'yarn' + ? 'yarn upgrade' + : `${packageManager} update`; + default: + throw new TypeError(`Unknown command type: ${type}`); + } +} +function isDevServer(server) { + return 'pluginContainer' in server; +} +function promiseWithResolvers() { + let resolve; + let reject; + const promise = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + return { promise, resolve, reject }; +} +function createSerialPromiseQueue() { + let previousTask; + return { + async run(f) { + const thisTask = f(); + // wait for both the previous task and this task + // so that this function resolves in the order this function is called + const depTasks = Promise.all([previousTask, thisTask]); + previousTask = depTasks; + const [, result] = await depTasks; + // this task was the last one, clear `previousTask` to free up memory + if (previousTask === depTasks) { + previousTask = undefined; + } + return result; + }, + }; +} +function sortObjectKeys(obj) { + const sorted = {}; + for (const key of Object.keys(obj).sort()) { + sorted[key] = obj[key]; + } + return sorted; +} +function displayTime(time) { + // display: {X}ms + if (time < 1000) { + return `${time}ms`; + } + time = time / 1000; + // display: {X}s + if (time < 60) { + return `${time.toFixed(2)}s`; + } + const mins = parseInt((time / 60).toString()); + const seconds = time % 60; + // display: {X}m {Y}s + return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`; +} + +/* eslint no-console: 0 */ +const LogLevels = { + silent: 0, + error: 1, + warn: 2, + info: 3, +}; +let lastType; +let lastMsg; +let sameCount = 0; +function clearScreen() { + const repeatCount = process.stdout.rows - 2; + const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; + console.log(blank); + readline.cursorTo(process.stdout, 0, 0); + readline.clearScreenDown(process.stdout); +} +// Only initialize the timeFormatter when the timestamp option is used, and +// reuse it across all loggers +let timeFormatter; +function getTimeFormatter() { + timeFormatter ??= new Intl.DateTimeFormat(undefined, { + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + }); + return timeFormatter; +} +function createLogger(level = 'info', options = {}) { + if (options.customLogger) { + return options.customLogger; + } + const loggedErrors = new WeakSet(); + const { prefix = '[vite]', allowClearScreen = true } = options; + const thresh = LogLevels[level]; + const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; + const clear = canClearScreen ? clearScreen : () => { }; + function format(type, msg, options = {}) { + if (options.timestamp) { + const tag = type === 'info' + ? colors$1.cyan(colors$1.bold(prefix)) + : type === 'warn' + ? colors$1.yellow(colors$1.bold(prefix)) + : colors$1.red(colors$1.bold(prefix)); + return `${colors$1.dim(getTimeFormatter().format(new Date()))} ${tag} ${msg}`; + } + else { + return msg; + } + } + function output(type, msg, options = {}) { + if (thresh >= LogLevels[type]) { + const method = type === 'info' ? 'log' : type; + if (options.error) { + loggedErrors.add(options.error); + } + if (canClearScreen) { + if (type === lastType && msg === lastMsg) { + sameCount++; + clear(); + console[method](format(type, msg, options), colors$1.yellow(`(x${sameCount + 1})`)); + } + else { + sameCount = 0; + lastMsg = msg; + lastType = type; + if (options.clear) { + clear(); + } + console[method](format(type, msg, options)); + } + } + else { + console[method](format(type, msg, options)); + } + } + } + const warnedMessages = new Set(); + const logger = { + hasWarned: false, + info(msg, opts) { + output('info', msg, opts); + }, + warn(msg, opts) { + logger.hasWarned = true; + output('warn', msg, opts); + }, + warnOnce(msg, opts) { + if (warnedMessages.has(msg)) + return; + logger.hasWarned = true; + output('warn', msg, opts); + warnedMessages.add(msg); + }, + error(msg, opts) { + logger.hasWarned = true; + output('error', msg, opts); + }, + clearScreen(type) { + if (thresh >= LogLevels[type]) { + clear(); + } + }, + hasErrorLogged(error) { + return loggedErrors.has(error); + }, + }; + return logger; +} +function printServerUrls(urls, optionsHost, info) { + const colorUrl = (url) => colors$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`)); + for (const url of urls.local) { + info(` ${colors$1.green('➜')} ${colors$1.bold('Local')}: ${colorUrl(url)}`); + } + for (const url of urls.network) { + info(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: ${colorUrl(url)}`); + } + if (urls.network.length === 0 && optionsHost === undefined) { + info(colors$1.dim(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: use `) + + colors$1.bold('--host') + + colors$1.dim(' to expose')); + } +} + +const groups = [ + { name: 'Assets', color: colors$1.green }, + { name: 'CSS', color: colors$1.magenta }, + { name: 'JS', color: colors$1.cyan }, +]; +const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/; +function buildReporterPlugin(config) { + const compress = promisify$4(gzip); + const chunkLimit = config.build.chunkSizeWarningLimit; + const numberFormatter = new Intl.NumberFormat('en', { + maximumFractionDigits: 2, + minimumFractionDigits: 2, + }); + const displaySize = (bytes) => { + return `${numberFormatter.format(bytes / 1000)} kB`; + }; + const tty = process.stdout.isTTY && !process.env.CI; + const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; + let hasTransformed = false; + let hasRenderedChunk = false; + let hasCompressChunk = false; + let transformedCount = 0; + let chunkCount = 0; + let compressedCount = 0; + async function getCompressedSize(code) { + if (config.build.ssr || !config.build.reportCompressedSize) { + return null; + } + if (shouldLogInfo && !hasCompressChunk) { + if (!tty) { + config.logger.info('computing gzip size...'); + } + else { + writeLine('computing gzip size (0)...'); + } + hasCompressChunk = true; + } + const compressed = await compress(typeof code === 'string' ? code : Buffer.from(code)); + compressedCount++; + if (shouldLogInfo && tty) { + writeLine(`computing gzip size (${compressedCount})...`); + } + return compressed.length; + } + const logTransform = throttle((id) => { + writeLine(`transforming (${transformedCount}) ${colors$1.dim(path$o.relative(config.root, id))}`); + }); + return { + name: 'vite:reporter', + transform(_, id) { + transformedCount++; + if (shouldLogInfo) { + if (!tty) { + if (!hasTransformed) { + config.logger.info(`transforming...`); + } + } + else { + if (id.includes(`?`)) + return; + logTransform(id); + } + hasTransformed = true; + } + return null; + }, + buildStart() { + transformedCount = 0; + }, + buildEnd() { + if (shouldLogInfo) { + if (tty) { + clearLine$1(); + } + config.logger.info(`${colors$1.green(`✓`)} ${transformedCount} modules transformed.`); + } + }, + renderStart() { + chunkCount = 0; + compressedCount = 0; + }, + renderChunk(code, chunk, options) { + if (!options.inlineDynamicImports) { + for (const id of chunk.moduleIds) { + const module = this.getModuleInfo(id); + if (!module) + continue; + // When a dynamic importer shares a chunk with the imported module, + // warn that the dynamic imported module will not be moved to another chunk (#12850). + if (module.importers.length && module.dynamicImporters.length) { + // Filter out the intersection of dynamic importers and sibling modules in + // the same chunk. The intersecting dynamic importers' dynamic import is not + // expected to work. Note we're only detecting the direct ineffective + // dynamic import here. + const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules$1(id) && chunk.moduleIds.includes(id)); + if (detectedIneffectiveDynamicImport) { + this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`); + } + } + } + } + chunkCount++; + if (shouldLogInfo) { + if (!tty) { + if (!hasRenderedChunk) { + config.logger.info('rendering chunks...'); + } + } + else { + writeLine(`rendering chunks (${chunkCount})...`); + } + hasRenderedChunk = true; + } + return null; + }, + generateBundle() { + if (shouldLogInfo && tty) + clearLine$1(); + }, + async writeBundle({ dir: outDir }, output) { + let hasLargeChunks = false; + if (shouldLogInfo) { + const entries = (await Promise.all(Object.values(output).map(async (chunk) => { + if (chunk.type === 'chunk') { + return { + name: chunk.fileName, + group: 'JS', + size: chunk.code.length, + compressedSize: await getCompressedSize(chunk.code), + mapSize: chunk.map ? chunk.map.toString().length : null, + }; + } + else { + if (chunk.fileName.endsWith('.map')) + return null; + const isCSS = chunk.fileName.endsWith('.css'); + const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName); + return { + name: chunk.fileName, + group: isCSS ? 'CSS' : 'Assets', + size: chunk.source.length, + mapSize: null, + compressedSize: isCompressible + ? await getCompressedSize(chunk.source) + : null, + }; + } + }))).filter(isDefined); + if (tty) + clearLine$1(); + let longest = 0; + let biggestSize = 0; + let biggestMap = 0; + let biggestCompressSize = 0; + for (const entry of entries) { + if (entry.name.length > longest) + longest = entry.name.length; + if (entry.size > biggestSize) + biggestSize = entry.size; + if (entry.mapSize && entry.mapSize > biggestMap) { + biggestMap = entry.mapSize; + } + if (entry.compressedSize && + entry.compressedSize > biggestCompressSize) { + biggestCompressSize = entry.compressedSize; + } + } + const sizePad = displaySize(biggestSize).length; + const mapPad = displaySize(biggestMap).length; + const compressPad = displaySize(biggestCompressSize).length; + const relativeOutDir = normalizePath$3(path$o.relative(config.root, path$o.resolve(config.root, outDir ?? config.build.outDir))); + const assetsDir = path$o.join(config.build.assetsDir, '/'); + for (const group of groups) { + const filtered = entries.filter((e) => e.group === group.name); + if (!filtered.length) + continue; + for (const entry of filtered.sort((a, z) => a.size - z.size)) { + const isLarge = group.name === 'JS' && entry.size / 1000 > chunkLimit; + if (isLarge) + hasLargeChunks = true; + const sizeColor = isLarge ? colors$1.yellow : colors$1.dim; + let log = colors$1.dim(withTrailingSlash(relativeOutDir)); + log += + !config.build.lib && + entry.name.startsWith(withTrailingSlash(assetsDir)) + ? colors$1.dim(assetsDir) + + group.color(entry.name + .slice(assetsDir.length) + .padEnd(longest + 2 - assetsDir.length)) + : group.color(entry.name.padEnd(longest + 2)); + log += colors$1.bold(sizeColor(displaySize(entry.size).padStart(sizePad))); + if (entry.compressedSize) { + log += colors$1.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`); + } + if (entry.mapSize) { + log += colors$1.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`); + } + config.logger.info(log); + } + } + } + else { + hasLargeChunks = Object.values(output).some((chunk) => { + return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit; + }); + } + if (hasLargeChunks && + config.build.minify && + !config.build.lib && + !config.build.ssr) { + config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n` + + `- Using dynamic import() to code-split the application\n` + + `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` + + `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); + } + }, + }; +} +function writeLine(output) { + clearLine$1(); + if (output.length < process.stdout.columns) { + process.stdout.write(output); + } + else { + process.stdout.write(output.substring(0, process.stdout.columns - 1)); + } +} +function clearLine$1() { + process.stdout.clearLine(0); + process.stdout.cursorTo(0); +} +function throttle(fn) { + let timerHandle = null; + return (...args) => { + if (timerHandle) + return; + fn(...args); + timerHandle = setTimeout(() => { + timerHandle = null; + }, 100); + }; +} + +const POSIX_SEP_RE = new RegExp('\\' + path$o.posix.sep, 'g'); +const NATIVE_SEP_RE = new RegExp('\\' + path$o.sep, 'g'); +/** @type {Map}*/ +const PATTERN_REGEX_CACHE = new Map(); +const GLOB_ALL_PATTERN = `**/*`; +const TS_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts']; +const JS_EXTENSIONS = ['.js', '.jsx', '.mjs', '.cjs']; +const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS); +const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join('|')})`; +const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join( + '|' +)})`; +const IS_POSIX = path$o.posix.sep === path$o.sep; + +/** + * @template T + * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise}} + */ +function makePromise() { + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +/** + * @param {string} filename + * @param {import('./cache.js').TSConfckCache} [cache] + * @returns {Promise} + */ +async function resolveTSConfigJson(filename, cache) { + if (path$o.extname(filename) !== '.json') { + return; // ignore files that are not json + } + const tsconfig = path$o.resolve(filename); + if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) { + return tsconfig; + } + return promises$1.stat(tsconfig).then((stat) => { + if (stat.isFile() || stat.isFIFO()) { + return tsconfig; + } else { + throw new Error(`${filename} exists but is not a regular file.`); + } + }); +} + +/** + * + * @param {string} dir an absolute directory path + * @returns {boolean} if dir path includes a node_modules segment + */ +const isInNodeModules = IS_POSIX + ? (dir) => dir.includes('/node_modules/') + : (dir) => dir.match(/[/\\]node_modules[/\\]/); + +/** + * convert posix separator to native separator + * + * eg. + * windows: C:/foo/bar -> c:\foo\bar + * linux: /foo/bar -> /foo/bar + * + * @param {string} filename with posix separators + * @returns {string} filename with native separators + */ +const posix2native = IS_POSIX + ? (filename) => filename + : (filename) => filename.replace(POSIX_SEP_RE, path$o.sep); + +/** + * convert native separator to posix separator + * + * eg. + * windows: C:\foo\bar -> c:/foo/bar + * linux: /foo/bar -> /foo/bar + * + * @param {string} filename - filename with native separators + * @returns {string} filename with posix separators + */ +const native2posix = IS_POSIX + ? (filename) => filename + : (filename) => filename.replace(NATIVE_SEP_RE, path$o.posix.sep); + +/** + * converts params to native separator, resolves path and converts native back to posix + * + * needed on windows to handle posix paths in tsconfig + * + * @param dir {string|null} directory to resolve from + * @param filename {string} filename or pattern to resolve + * @returns string + */ +const resolve2posix = IS_POSIX + ? (dir, filename) => (dir ? path$o.resolve(dir, filename) : path$o.resolve(filename)) + : (dir, filename) => + native2posix( + dir + ? path$o.resolve(posix2native(dir), posix2native(filename)) + : path$o.resolve(posix2native(filename)) + ); + +/** + * + * @param {import('./public.d.ts').TSConfckParseResult} result + * @param {import('./public.d.ts').TSConfckParseOptions} [options] + * @returns {string[]} + */ +function resolveReferencedTSConfigFiles(result, options) { + const dir = path$o.dirname(result.tsconfigFile); + return result.tsconfig.references.map((ref) => { + const refPath = ref.path.endsWith('.json') + ? ref.path + : path$o.join(ref.path, options?.configName ?? 'tsconfig.json'); + return resolve2posix(dir, refPath); + }); +} + +/** + * @param {string} filename + * @param {import('./public.d.ts').TSConfckParseResult} result + * @returns {import('./public.d.ts').TSConfckParseResult} + */ +function resolveSolutionTSConfig(filename, result) { + const allowJs = result.tsconfig.compilerOptions?.allowJs; + const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; + if ( + result.referenced && + extensions.some((ext) => filename.endsWith(ext)) && + !isIncluded(filename, result) + ) { + const solutionTSConfig = result.referenced.find((referenced) => + isIncluded(filename, referenced) + ); + if (solutionTSConfig) { + return solutionTSConfig; + } + } + return result; +} + +/** + * + * @param {string} filename + * @param {import('./public.d.ts').TSConfckParseResult} result + * @returns {boolean} + */ +function isIncluded(filename, result) { + const dir = native2posix(path$o.dirname(result.tsconfigFile)); + const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file)); + const absoluteFilename = resolve2posix(null, filename); + if (files.includes(filename)) { + return true; + } + const allowJs = result.tsconfig.compilerOptions?.allowJs; + const isIncluded = isGlobMatch( + absoluteFilename, + dir, + result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]), + allowJs + ); + if (isIncluded) { + const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs); + return !isExcluded; + } + return false; +} + +/** + * test filenames agains glob patterns in tsconfig + * + * @param filename {string} posix style abolute path to filename to test + * @param dir {string} posix style absolute path to directory of tsconfig containing patterns + * @param patterns {string[]} glob patterns to match against + * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks + * @returns {boolean} true when at least one pattern matches filename + */ +function isGlobMatch(filename, dir, patterns, allowJs) { + const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; + return patterns.some((pattern) => { + // filename must end with part of pattern that comes after last wildcard + let lastWildcardIndex = pattern.length; + let hasWildcard = false; + for (let i = pattern.length - 1; i > -1; i--) { + if (pattern[i] === '*' || pattern[i] === '?') { + lastWildcardIndex = i; + hasWildcard = true; + break; + } + } + + // if pattern does not end with wildcard, filename must end with pattern after last wildcard + if ( + lastWildcardIndex < pattern.length - 1 && + !filename.endsWith(pattern.slice(lastWildcardIndex + 1)) + ) { + return false; + } + + // if pattern ends with *, filename must end with a default extension + if (pattern.endsWith('*') && !extensions.some((ext) => filename.endsWith(ext))) { + return false; + } + + // for **/* , filename must start with the dir + if (pattern === GLOB_ALL_PATTERN) { + return filename.startsWith(`${dir}/`); + } + + const resolvedPattern = resolve2posix(dir, pattern); + + // filename must start with part of pattern that comes before first wildcard + let firstWildcardIndex = -1; + for (let i = 0; i < resolvedPattern.length; i++) { + if (resolvedPattern[i] === '*' || resolvedPattern[i] === '?') { + firstWildcardIndex = i; + hasWildcard = true; + break; + } + } + if ( + firstWildcardIndex > 1 && + !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1)) + ) { + return false; + } + + // if no wildcard in pattern, filename must be equal to resolved pattern + if (!hasWildcard) { + return filename === resolvedPattern; + } + + // complex pattern, use regex to check it + if (PATTERN_REGEX_CACHE.has(resolvedPattern)) { + return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename); + } + const regex = pattern2regex(resolvedPattern, allowJs); + PATTERN_REGEX_CACHE.set(resolvedPattern, regex); + return regex.test(filename); + }); +} + +/** + * @param {string} resolvedPattern + * @param {boolean} allowJs + * @returns {RegExp} + */ +function pattern2regex(resolvedPattern, allowJs) { + let regexStr = '^'; + for (let i = 0; i < resolvedPattern.length; i++) { + const char = resolvedPattern[i]; + if (char === '?') { + regexStr += '[^\\/]'; + continue; + } + if (char === '*') { + if (resolvedPattern[i + 1] === '*' && resolvedPattern[i + 2] === '/') { + i += 2; + regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments + continue; + } + regexStr += '[^\\/]*'; + continue; + } + if ('/.+^${}()|[]\\'.includes(char)) { + regexStr += `\\`; + } + regexStr += char; + } + + // add known file endings if pattern ends on * + if (resolvedPattern.endsWith('*')) { + regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP; + } + regexStr += '$'; + + return new RegExp(regexStr); +} + +/** + * find the closest tsconfig.json file + * + * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd) + * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options + * @returns {Promise} absolute path to closest tsconfig.json or null if not found + */ +async function find(filename, options) { + let dir = path$o.dirname(path$o.resolve(filename)); + if (options?.ignoreNodeModules && isInNodeModules(dir)) { + return null; + } + const cache = options?.cache; + const configName = options?.configName ?? 'tsconfig.json'; + if (cache?.hasConfigPath(dir, configName)) { + return cache.getConfigPath(dir, configName); + } + const { /** @type {Promise} */ promise, resolve, reject } = makePromise(); + if (options?.root && !path$o.isAbsolute(options.root)) { + options.root = path$o.resolve(options.root); + } + findUp(dir, { promise, resolve, reject }, options); + return promise; +} + +/** + * + * @param {string} dir + * @param {{promise:Promise,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise + * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options + */ +function findUp(dir, { resolve, reject, promise }, options) { + const { cache, root, configName } = options ?? {}; + if (cache) { + if (cache.hasConfigPath(dir, configName)) { + let cached; + try { + cached = cache.getConfigPath(dir, configName); + } catch (e) { + reject(e); + return; + } + if (cached?.then) { + cached.then(resolve).catch(reject); + } else { + resolve(cached); + } + } else { + cache.setConfigPath(dir, promise, configName); + } + } + const tsconfig = path$o.join(dir, options?.configName ?? 'tsconfig.json'); + fs$l.stat(tsconfig, (err, stats) => { + if (stats && (stats.isFile() || stats.isFIFO())) { + resolve(tsconfig); + } else if (err?.code !== 'ENOENT') { + reject(err); + } else { + let parent; + if (root === dir || (parent = path$o.dirname(dir)) === dir) { + resolve(null); + } else { + findUp(parent, { promise, resolve, reject }, options); + } + } + }); +} + +/* + this file contains code from strip-bom and strip-json-comments by Sindre Sorhus + https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js + https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js + licensed under MIT, see ../LICENSE +*/ + +/** + * convert content of tsconfig.json to regular json + * + * @param {string} tsconfigJson - content of tsconfig.json + * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace + */ +function toJson(tsconfigJson) { + const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson))); + if (stripped.trim() === '') { + // only whitespace left after stripping, return empty object so that JSON.parse still works + return '{}'; + } else { + return stripped; + } +} + +/** + * replace dangling commas from pseudo-json string with single space + * implementation heavily inspired by strip-json-comments + * + * @param {string} pseudoJson + * @returns {string} + */ +function stripDanglingComma(pseudoJson) { + let insideString = false; + let offset = 0; + let result = ''; + let danglingCommaPos = null; + for (let i = 0; i < pseudoJson.length; i++) { + const currentCharacter = pseudoJson[i]; + if (currentCharacter === '"') { + const escaped = isEscaped(pseudoJson, i); + if (!escaped) { + insideString = !insideString; + } + } + if (insideString) { + danglingCommaPos = null; + continue; + } + if (currentCharacter === ',') { + danglingCommaPos = i; + continue; + } + if (danglingCommaPos) { + if (currentCharacter === '}' || currentCharacter === ']') { + result += pseudoJson.slice(offset, danglingCommaPos) + ' '; + offset = danglingCommaPos + 1; + danglingCommaPos = null; + } else if (!currentCharacter.match(/\s/)) { + danglingCommaPos = null; + } + } + } + return result + pseudoJson.substring(offset); +} + +// start strip-json-comments +/** + * + * @param {string} jsonString + * @param {number} quotePosition + * @returns {boolean} + */ +function isEscaped(jsonString, quotePosition) { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === '\\') { + index -= 1; + backslashCount += 1; + } + + return Boolean(backslashCount % 2); +} + +/** + * + * @param {string} string + * @param {number?} start + * @param {number?} end + */ +function strip(string, start, end) { + return string.slice(start, end).replace(/\S/g, ' '); +} + +const singleComment = Symbol('singleComment'); +const multiComment = Symbol('multiComment'); + +/** + * @param {string} jsonString + * @returns {string} + */ +function stripJsonComments(jsonString) { + let isInsideString = false; + /** @type {false | symbol} */ + let isInsideComment = false; + let offset = 0; + let result = ''; + + for (let index = 0; index < jsonString.length; index++) { + const currentCharacter = jsonString[index]; + const nextCharacter = jsonString[index + 1]; + + if (!isInsideComment && currentCharacter === '"') { + const escaped = isEscaped(jsonString, index); + if (!escaped) { + isInsideString = !isInsideString; + } + } + + if (isInsideString) { + continue; + } + + if (!isInsideComment && currentCharacter + nextCharacter === '//') { + result += jsonString.slice(offset, index); + offset = index; + isInsideComment = singleComment; + index++; + } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') { + index++; + isInsideComment = false; + result += strip(jsonString, offset, index); + offset = index; + } else if (isInsideComment === singleComment && currentCharacter === '\n') { + isInsideComment = false; + result += strip(jsonString, offset, index); + offset = index; + } else if (!isInsideComment && currentCharacter + nextCharacter === '/*') { + result += jsonString.slice(offset, index); + offset = index; + isInsideComment = multiComment; + index++; + } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') { + index++; + isInsideComment = false; + result += strip(jsonString, offset, index + 1); + offset = index + 1; + } + } + + return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); +} +// end strip-json-comments + +// start strip-bom +/** + * @param {string} string + * @returns {string} + */ +function stripBom(string) { + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM). + if (string.charCodeAt(0) === 0xfeff) { + return string.slice(1); + } + return string; +} +// end strip-bom + +const not_found_result = { + tsconfigFile: null, + tsconfig: {} +}; + +/** + * parse the closest tsconfig.json file + * + * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd) + * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options + * @returns {Promise} + * @throws {TSConfckParseError} + */ +async function parse$f(filename, options) { + /** @type {import('./cache.js').TSConfckCache} */ + const cache = options?.cache; + if (cache?.hasParseResult(filename)) { + return getParsedDeep(filename, cache, options); + } + const { + resolve, + reject, + /** @type {Promise}*/ + promise + } = makePromise(); + cache?.setParseResult(filename, promise); + try { + let tsconfigFile = + (await resolveTSConfigJson(filename, cache)) || (await find(filename, options)); + if (!tsconfigFile) { + resolve(not_found_result); + return promise; + } + let result; + if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) { + result = await getParsedDeep(tsconfigFile, cache, options); + } else { + result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile); + await Promise.all([parseExtends(result, cache), parseReferences(result, options)]); + } + resolve(resolveSolutionTSConfig(filename, result)); + } catch (e) { + reject(e); + } + return promise; +} + +/** + * ensure extends and references are parsed + * + * @param {string} filename - cached file + * @param {import('./cache.js').TSConfckCache} cache - cache + * @param {import('./public.d.ts').TSConfckParseOptions} options - options + */ +async function getParsedDeep(filename, cache, options) { + const result = await cache.getParseResult(filename); + if ( + (result.tsconfig.extends && !result.extended) || + (result.tsconfig.references && !result.referenced) + ) { + const promise = Promise.all([ + parseExtends(result, cache), + parseReferences(result, options) + ]).then(() => result); + cache.setParseResult(filename, promise); + return promise; + } + return result; +} + +/** + * + * @param {string} tsconfigFile - path to tsconfig file + * @param {import('./cache.js').TSConfckCache} [cache] - cache + * @param {boolean} [skipCache] - skip cache + * @returns {Promise} + */ +async function parseFile$1(tsconfigFile, cache, skipCache) { + if (!skipCache && cache?.hasParseResult(tsconfigFile)) { + return cache.getParseResult(tsconfigFile); + } + const promise = promises$1 + .readFile(tsconfigFile, 'utf-8') + .then(toJson) + .then((json) => { + const parsed = JSON.parse(json); + applyDefaults(parsed, tsconfigFile); + return { + tsconfigFile, + tsconfig: normalizeTSConfig(parsed, path$o.dirname(tsconfigFile)) + }; + }) + .catch((e) => { + throw new TSConfckParseError( + `parsing ${tsconfigFile} failed: ${e}`, + 'PARSE_FILE', + tsconfigFile, + e + ); + }); + if (!skipCache) { + cache?.setParseResult(tsconfigFile, promise); + } + return promise; +} + +/** + * normalize to match the output of ts.parseJsonConfigFileContent + * + * @param {any} tsconfig - typescript tsconfig output + * @param {string} dir - directory + */ +function normalizeTSConfig(tsconfig, dir) { + // set baseUrl to absolute path + if (tsconfig.compilerOptions?.baseUrl && !path$o.isAbsolute(tsconfig.compilerOptions.baseUrl)) { + tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl); + } + return tsconfig; +} + +/** + * + * @param {import('./public.d.ts').TSConfckParseResult} result + * @param {import('./public.d.ts').TSConfckParseOptions} [options] + * @returns {Promise} + */ +async function parseReferences(result, options) { + if (!result.tsconfig.references) { + return; + } + const referencedFiles = resolveReferencedTSConfigFiles(result, options); + const referenced = await Promise.all( + referencedFiles.map((file) => parseFile$1(file, options?.cache)) + ); + await Promise.all(referenced.map((ref) => parseExtends(ref, options?.cache))); + referenced.forEach((ref) => { + ref.solution = result; + }); + result.referenced = referenced; +} + +/** + * @param {import('./public.d.ts').TSConfckParseResult} result + * @param {import('./cache.js').TSConfckCache}[cache] + * @returns {Promise} + */ +async function parseExtends(result, cache) { + if (!result.tsconfig.extends) { + return; + } + // use result as first element in extended + // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0] + /** @type {import('./public.d.ts').TSConfckParseResult[]} */ + const extended = [ + { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) } + ]; + + // flatten extends graph into extended + let pos = 0; + /** @type {string[]} */ + const extendsPath = []; + let currentBranchDepth = 0; + while (pos < extended.length) { + const extending = extended[pos]; + extendsPath.push(extending.tsconfigFile); + if (extending.tsconfig.extends) { + // keep following this branch + currentBranchDepth += 1; + /** @type {string[]} */ + let resolvedExtends; + if (!Array.isArray(extending.tsconfig.extends)) { + resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)]; + } else { + // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a + resolvedExtends = extending.tsconfig.extends + .reverse() + .map((ex) => resolveExtends(ex, extending.tsconfigFile)); + } + + const circularExtends = resolvedExtends.find((tsconfigFile) => + extendsPath.includes(tsconfigFile) + ); + if (circularExtends) { + const circle = extendsPath.concat([circularExtends]).join(' -> '); + throw new TSConfckParseError( + `Circular dependency in "extends": ${circle}`, + 'EXTENDS_CIRCULAR', + result.tsconfigFile + ); + } + // add new extends to the list directly after current + extended.splice( + pos + 1, + 0, + ...(await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))) + ); + } else { + // reached a leaf, backtrack to the last branching point and continue + extendsPath.splice(-currentBranchDepth); + currentBranchDepth = 0; + } + pos = pos + 1; + } + result.extended = extended; + // skip first as it is the original config + for (const ext of result.extended.slice(1)) { + extendTSConfig(result, ext); + } +} + +/** + * + * @param {string} extended + * @param {string} from + * @returns {string} + */ +function resolveExtends(extended, from) { + if (extended === '..') { + // see #149 + extended = '../tsconfig.json'; + } + const req = createRequire$2(from); + let error; + try { + return req.resolve(extended); + } catch (e) { + error = e; + } + if (extended[0] !== '.' && !path$o.isAbsolute(extended)) { + try { + return req.resolve(`${extended}/tsconfig.json`); + } catch (e) { + error = e; + } + } + + throw new TSConfckParseError( + `failed to resolve "extends":"${extended}" in ${from}`, + 'EXTENDS_RESOLVE', + from, + error + ); +} + +// references, extends and custom keys are not carried over +const EXTENDABLE_KEYS = [ + 'compilerOptions', + 'files', + 'include', + 'exclude', + 'watchOptions', + 'compileOnSave', + 'typeAcquisition', + 'buildOptions' +]; + +/** + * + * @param {import('./public.d.ts').TSConfckParseResult} extending + * @param {import('./public.d.ts').TSConfckParseResult} extended + * @returns void + */ +function extendTSConfig(extending, extended) { + const extendingConfig = extending.tsconfig; + const extendedConfig = extended.tsconfig; + const relativePath = native2posix( + path$o.relative(path$o.dirname(extending.tsconfigFile), path$o.dirname(extended.tsconfigFile)) + ); + for (const key of Object.keys(extendedConfig).filter((key) => EXTENDABLE_KEYS.includes(key))) { + if (key === 'compilerOptions') { + if (!extendingConfig.compilerOptions) { + extendingConfig.compilerOptions = {}; + } + for (const option of Object.keys(extendedConfig.compilerOptions)) { + if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) { + continue; // already set + } + extendingConfig.compilerOptions[option] = rebaseRelative( + option, + extendedConfig.compilerOptions[option], + relativePath + ); + } + } else if (extendingConfig[key] === undefined) { + if (key === 'watchOptions') { + extendingConfig.watchOptions = {}; + for (const option of Object.keys(extendedConfig.watchOptions)) { + extendingConfig.watchOptions[option] = rebaseRelative( + option, + extendedConfig.watchOptions[option], + relativePath + ); + } + } else { + extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath); + } + } + } +} + +const REBASE_KEYS = [ + // root + 'files', + 'include', + 'exclude', + // compilerOptions + 'baseUrl', + 'rootDir', + 'rootDirs', + 'typeRoots', + 'outDir', + 'outFile', + 'declarationDir', + // watchOptions + 'excludeDirectories', + 'excludeFiles' +]; + +/** @typedef {string | string[]} PathValue */ + +/** + * + * @param {string} key + * @param {PathValue} value + * @param {string} prependPath + * @returns {PathValue} + */ +function rebaseRelative(key, value, prependPath) { + if (!REBASE_KEYS.includes(key)) { + return value; + } + if (Array.isArray(value)) { + return value.map((x) => rebasePath(x, prependPath)); + } else { + return rebasePath(value, prependPath); + } +} + +/** + * + * @param {string} value + * @param {string} prependPath + * @returns {string} + */ +function rebasePath(value, prependPath) { + if (path$o.isAbsolute(value)) { + return value; + } else { + // relative paths use posix syntax in tsconfig + return path$o.posix.normalize(path$o.posix.join(prependPath, value)); + } +} + +class TSConfckParseError extends Error { + /** + * error code + * @type {string} + */ + code; + /** + * error cause + * @type { Error | undefined} + */ + cause; + + /** + * absolute path of tsconfig file where the error happened + * @type {string} + */ + tsconfigFile; + /** + * + * @param {string} message - error message + * @param {string} code - error code + * @param {string} tsconfigFile - path to tsconfig file + * @param {Error?} cause - cause of this error + */ + constructor(message, code, tsconfigFile, cause) { + super(message); + // Set the prototype explicitly. + Object.setPrototypeOf(this, TSConfckParseError.prototype); + this.name = TSConfckParseError.name; + this.code = code; + this.cause = cause; + this.tsconfigFile = tsconfigFile; + } +} + +/** + * + * @param {any} tsconfig + * @param {string} tsconfigFile + */ +function applyDefaults(tsconfig, tsconfigFile) { + if (isJSConfig(tsconfigFile)) { + tsconfig.compilerOptions = { + ...DEFAULT_JSCONFIG_COMPILER_OPTIONS, + ...tsconfig.compilerOptions + }; + } +} + +const DEFAULT_JSCONFIG_COMPILER_OPTIONS = { + allowJs: true, + maxNodeModuleJsDepth: 2, + allowSyntheticDefaultImports: true, + skipLibCheck: true, + noEmit: true +}; + +/** + * @param {string} configFileName + */ +function isJSConfig(configFileName) { + return path$o.basename(configFileName) === 'jsconfig.json'; +} + +/** @template T */ +class TSConfckCache { + /** + * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted + */ + clear() { + this.#configPaths.clear(); + this.#parsed.clear(); + } + + /** + * has cached closest config for files in dir + * @param {string} dir + * @param {string} [configName=tsconfig.json] + * @returns {boolean} + */ + hasConfigPath(dir, configName = 'tsconfig.json') { + return this.#configPaths.has(`${dir}/${configName}`); + } + + /** + * get cached closest tsconfig for files in dir + * @param {string} dir + * @param {string} [configName=tsconfig.json] + * @returns {Promise|string|null} + * @throws {unknown} if cached value is an error + */ + getConfigPath(dir, configName = 'tsconfig.json') { + const key = `${dir}/${configName}`; + const value = this.#configPaths.get(key); + if (value == null || value.length || value.then) { + return value; + } else { + throw value; + } + } + + /** + * has parsed tsconfig for file + * @param {string} file + * @returns {boolean} + */ + hasParseResult(file) { + return this.#parsed.has(file); + } + + /** + * get parsed tsconfig for file + * @param {string} file + * @returns {Promise|T} + * @throws {unknown} if cached value is an error + */ + getParseResult(file) { + const value = this.#parsed.get(file); + if (value.then || value.tsconfig) { + return value; + } else { + throw value; // cached error, rethrow + } + } + + /** + * @internal + * @private + * @param file + * @param {Promise} result + */ + setParseResult(file, result) { + this.#parsed.set(file, result); + result + .then((parsed) => { + if (this.#parsed.get(file) === result) { + this.#parsed.set(file, parsed); + } + }) + .catch((e) => { + if (this.#parsed.get(file) === result) { + this.#parsed.set(file, e); + } + }); + } + + /** + * @internal + * @private + * @param {string} dir + * @param {Promise} configPath + * @param {string} [configName=tsconfig.json] + */ + setConfigPath(dir, configPath, configName = 'tsconfig.json') { + const key = `${dir}/${configName}`; + this.#configPaths.set(key, configPath); + configPath + .then((path) => { + if (this.#configPaths.get(key) === configPath) { + this.#configPaths.set(key, path); + } + }) + .catch((e) => { + if (this.#configPaths.get(key) === configPath) { + this.#configPaths.set(key, e); + } + }); + } + + /** + * map directories to their closest tsconfig.json + * @internal + * @private + * @type{Map|string|null)>} + */ + #configPaths = new Map(); + + /** + * map files to their parsed tsconfig result + * @internal + * @private + * @type {Map|T)> } + */ + #parsed = new Map(); +} + +const debug$h = createDebugger('vite:esbuild'); +// IIFE content looks like `var MyLib = function() {`. +// Spaces are removed and parameters are mangled when minified +const IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/; +const validExtensionRE = /\.\w+$/; +const jsxExtensionsRE = /\.(?:j|t)sx\b/; +let server; +async function transformWithEsbuild(code, filename, options, inMap) { + let loader = options?.loader; + if (!loader) { + // if the id ends with a valid ext, use it (e.g. vue blocks) + // otherwise, cleanup the query before checking the ext + const ext = path$o + .extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)) + .slice(1); + if (ext === 'cjs' || ext === 'mjs') { + loader = 'js'; + } + else if (ext === 'cts' || ext === 'mts') { + loader = 'ts'; + } + else { + loader = ext; + } + } + let tsconfigRaw = options?.tsconfigRaw; + // if options provide tsconfigRaw in string, it takes highest precedence + if (typeof tsconfigRaw !== 'string') { + // these fields would affect the compilation result + // https://esbuild.github.io/content-types/#tsconfig-json + const meaningfulFields = [ + 'alwaysStrict', + 'experimentalDecorators', + 'importsNotUsedAsValues', + 'jsx', + 'jsxFactory', + 'jsxFragmentFactory', + 'jsxImportSource', + 'preserveValueImports', + 'target', + 'useDefineForClassFields', + 'verbatimModuleSyntax', + ]; + const compilerOptionsForFile = {}; + if (loader === 'ts' || loader === 'tsx') { + const loadedTsconfig = await loadTsconfigJsonForFile(filename); + const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}; + for (const field of meaningfulFields) { + if (field in loadedCompilerOptions) { + // @ts-expect-error TypeScript can't tell they are of the same type + compilerOptionsForFile[field] = loadedCompilerOptions[field]; + } + } + } + const compilerOptions = { + ...compilerOptionsForFile, + ...tsconfigRaw?.compilerOptions, + }; + // esbuild uses `useDefineForClassFields: true` when `tsconfig.compilerOptions.target` isn't declared + // but we want `useDefineForClassFields: false` when `tsconfig.compilerOptions.target` isn't declared + // to align with the TypeScript's behavior + if (compilerOptions.useDefineForClassFields === undefined && + compilerOptions.target === undefined) { + compilerOptions.useDefineForClassFields = false; + } + // esbuild uses tsconfig fields when both the normal options and tsconfig was set + // but we want to prioritize the normal options + if (options) { + options.jsx && (compilerOptions.jsx = undefined); + options.jsxFactory && (compilerOptions.jsxFactory = undefined); + options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined); + options.jsxImportSource && (compilerOptions.jsxImportSource = undefined); + } + tsconfigRaw = { + ...tsconfigRaw, + compilerOptions, + }; + } + const resolvedOptions = { + sourcemap: true, + // ensure source file name contains full query + sourcefile: filename, + ...options, + loader, + tsconfigRaw, + }; + // Some projects in the ecosystem are calling this function with an ESBuildOptions + // object and esbuild throws an error for extra fields + // @ts-expect-error include exists in ESBuildOptions + delete resolvedOptions.include; + // @ts-expect-error exclude exists in ESBuildOptions + delete resolvedOptions.exclude; + // @ts-expect-error jsxInject exists in ESBuildOptions + delete resolvedOptions.jsxInject; + try { + const result = await transform$1(code, resolvedOptions); + let map; + if (inMap && resolvedOptions.sourcemap) { + const nextMap = JSON.parse(result.map); + nextMap.sourcesContent = []; + map = combineSourcemaps(filename, [ + nextMap, + inMap, + ]); + } + else { + map = + resolvedOptions.sourcemap && resolvedOptions.sourcemap !== 'inline' + ? JSON.parse(result.map) + : { mappings: '' }; + } + return { + ...result, + map, + }; + } + catch (e) { + debug$h?.(`esbuild error with options used: `, resolvedOptions); + // patch error information + if (e.errors) { + e.frame = ''; + e.errors.forEach((m) => { + if (m.text === 'Experimental decorators are not currently enabled' || + m.text === + 'Parameter decorators only work when experimental decorators are enabled') { + m.text += + '. Vite 5 now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.'; + } + e.frame += `\n` + prettifyMessage(m, code); + }); + e.loc = e.errors[0].location; + } + throw e; + } +} +function esbuildPlugin(config) { + const options = config.esbuild; + const { jsxInject, include, exclude, ...esbuildTransformOptions } = options; + const filter = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/); + // Remove optimization options for dev as we only need to transpile them, + // and for build as the final optimization is in `buildEsbuildPlugin` + const transformOptions = { + target: 'esnext', + charset: 'utf8', + ...esbuildTransformOptions, + minify: false, + minifyIdentifiers: false, + minifySyntax: false, + minifyWhitespace: false, + treeShaking: false, + // keepNames is not needed when minify is disabled. + // Also transforming multiple times with keepNames enabled breaks + // tree-shaking. (#9164) + keepNames: false, + }; + return { + name: 'vite:esbuild', + configureServer(_server) { + server = _server; + server.watcher + .on('add', reloadOnTsconfigChange) + .on('change', reloadOnTsconfigChange) + .on('unlink', reloadOnTsconfigChange); + }, + buildEnd() { + // recycle serve to avoid preventing Node self-exit (#6815) + server = null; + }, + async transform(code, id) { + if (filter(id) || filter(cleanUrl(id))) { + const result = await transformWithEsbuild(code, id, transformOptions); + if (result.warnings.length) { + result.warnings.forEach((m) => { + this.warn(prettifyMessage(m, code)); + }); + } + if (jsxInject && jsxExtensionsRE.test(id)) { + result.code = jsxInject + ';' + result.code; + } + return { + code: result.code, + map: result.map, + }; + } + }, + }; +} +const rollupToEsbuildFormatMap = { + es: 'esm', + cjs: 'cjs', + // passing `var Lib = (() => {})()` to esbuild with format = "iife" + // will turn it to `(() => { var Lib = (() => {})() })()`, + // so we remove the format config to tell esbuild not doing this + // + // although esbuild doesn't change format, there is still possibility + // that `{ treeShaking: true }` removes a top-level no-side-effect variable + // like: `var Lib = 1`, which becomes `` after esbuild transforming, + // but thankfully rollup does not do this optimization now + iife: undefined, +}; +const buildEsbuildPlugin = (config) => { + return { + name: 'vite:esbuild-transpile', + async renderChunk(code, chunk, opts) { + // @ts-expect-error injected by @vitejs/plugin-legacy + if (opts.__vite_skip_esbuild__) { + return null; + } + const options = resolveEsbuildTranspileOptions(config, opts.format); + if (!options) { + return null; + } + const res = await transformWithEsbuild(code, chunk.fileName, options); + if (config.build.lib) { + // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the + // names are minified potentially causing collision with other globals. + // We inject the helpers inside the wrappers. + // e.g. turn: + // (function(){ /*actual content/* })() + // into: + // (function(){ /*actual content/* })() + // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065 + // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant + // We don't need to create a MagicString here because both the helpers and + // the headers don't modify the sourcemap + const esbuildCode = res.code; + const contentIndex = opts.format === 'iife' + ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) + : opts.format === 'umd' + ? esbuildCode.indexOf(`(function(`) // same for minified or not + : 0; + if (contentIndex > 0) { + const esbuildHelpers = esbuildCode.slice(0, contentIndex); + res.code = esbuildCode + .slice(contentIndex) + .replace(`"use strict";`, `"use strict";` + esbuildHelpers); + } + } + return res; + }, + }; +}; +function resolveEsbuildTranspileOptions(config, format) { + const target = config.build.target; + const minify = config.build.minify === 'esbuild'; + if ((!target || target === 'esnext') && !minify) { + return null; + } + // Do not minify whitespace for ES lib output since that would remove + // pure annotations and break tree-shaking + // https://github.com/vuejs/core/issues/2860#issuecomment-926882793 + const isEsLibBuild = config.build.lib && format === 'es'; + const esbuildOptions = config.esbuild || {}; + const options = { + charset: 'utf8', + ...esbuildOptions, + loader: 'js', + target: target || undefined, + format: rollupToEsbuildFormatMap[format], + // the final build should always support dynamic import and import.meta. + // if they need to be polyfilled, plugin-legacy should be used. + // plugin-legacy detects these two features when checking for modern code. + supported: { + 'dynamic-import': true, + 'import-meta': true, + ...esbuildOptions.supported, + }, + }; + // If no minify, disable all minify options + if (!minify) { + return { + ...options, + minify: false, + minifyIdentifiers: false, + minifySyntax: false, + minifyWhitespace: false, + treeShaking: false, + }; + } + // If user enable fine-grain minify options, minify with their options instead + if (options.minifyIdentifiers != null || + options.minifySyntax != null || + options.minifyWhitespace != null) { + if (isEsLibBuild) { + // Disable minify whitespace as it breaks tree-shaking + return { + ...options, + minify: false, + minifyIdentifiers: options.minifyIdentifiers ?? true, + minifySyntax: options.minifySyntax ?? true, + minifyWhitespace: false, + treeShaking: true, + }; + } + else { + return { + ...options, + minify: false, + minifyIdentifiers: options.minifyIdentifiers ?? true, + minifySyntax: options.minifySyntax ?? true, + minifyWhitespace: options.minifyWhitespace ?? true, + treeShaking: true, + }; + } + } + // Else apply default minify options + if (isEsLibBuild) { + // Minify all except whitespace as it breaks tree-shaking + return { + ...options, + minify: false, + minifyIdentifiers: true, + minifySyntax: true, + minifyWhitespace: false, + treeShaking: true, + }; + } + else { + return { + ...options, + minify: true, + treeShaking: true, + }; + } +} +function prettifyMessage(m, code) { + let res = colors$1.yellow(m.text); + if (m.location) { + res += `\n` + generateCodeFrame(code, m.location); + } + return res + `\n`; +} +let tsconfckCache; +async function loadTsconfigJsonForFile(filename) { + try { + if (!tsconfckCache) { + tsconfckCache = new TSConfckCache(); + } + const result = await parse$f(filename, { + cache: tsconfckCache, + ignoreNodeModules: true, + }); + // tsconfig could be out of root, make sure it is watched on dev + if (server && result.tsconfigFile) { + ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root); + } + return result.tsconfig; + } + catch (e) { + if (e instanceof TSConfckParseError) { + // tsconfig could be out of root, make sure it is watched on dev + if (server && e.tsconfigFile) { + ensureWatchedFile(server.watcher, e.tsconfigFile, server.config.root); + } + } + throw e; + } +} +async function reloadOnTsconfigChange(changedFile) { + // server could be closed externally after a file change is detected + if (!server) + return; + // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one + // any json file in the tsconfig cache could have been used to compile ts + if (path$o.basename(changedFile) === 'tsconfig.json' || + (changedFile.endsWith('.json') && + tsconfckCache?.hasParseResult(changedFile))) { + server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true }); + // clear module graph to remove code compiled with outdated config + server.moduleGraph.invalidateAll(); + // reset tsconfck so that recompile works with up2date configs + tsconfckCache?.clear(); + // server may not be available if vite config is updated at the same time + if (server) { + // force full reload + server.hot.send({ + type: 'full-reload', + path: '*', + }); + } + } +} + +// src/realWorker.ts +var Worker = class { + /** @internal */ + _code; + /** @internal */ + _parentFunctions; + /** @internal */ + _max; + /** @internal */ + _pool; + /** @internal */ + _idlePool; + /** @internal */ + _queue; + constructor(fn, options = {}) { + this._code = genWorkerCode(fn, options.parentFunctions ?? {}); + this._parentFunctions = options.parentFunctions ?? {}; + const defaultMax = Math.max( + 1, + // os.availableParallelism is available from Node.js 18.14.0 + (os$4.availableParallelism?.() ?? os$4.cpus().length) - 1 + ); + this._max = options.max || defaultMax; + this._pool = []; + this._idlePool = []; + this._queue = []; + } + async run(...args) { + const worker = await this._getAvailableWorker(); + return new Promise((resolve, reject) => { + worker.currentResolve = resolve; + worker.currentReject = reject; + worker.postMessage({ type: "run", args }); + }); + } + stop() { + this._pool.forEach((w) => w.unref()); + this._queue.forEach( + ([, reject]) => reject( + new Error("Main worker pool stopped before a worker was available.") + ) + ); + this._pool = []; + this._idlePool = []; + this._queue = []; + } + /** @internal */ + async _getAvailableWorker() { + if (this._idlePool.length) { + return this._idlePool.shift(); + } + if (this._pool.length < this._max) { + const worker = new Worker$1(this._code, { eval: true }); + worker.on("message", async (args) => { + if (args.type === "run") { + if ("result" in args) { + worker.currentResolve && worker.currentResolve(args.result); + worker.currentResolve = null; + } else { + if (args.error instanceof ReferenceError) { + args.error.message += ". Maybe you forgot to pass the function to parentFunction?"; + } + worker.currentReject && worker.currentReject(args.error); + worker.currentReject = null; + } + this._assignDoneWorker(worker); + } else if (args.type === "parentFunction") { + try { + const result = await this._parentFunctions[args.name](...args.args); + worker.postMessage({ type: "parentFunction", id: args.id, result }); + } catch (e) { + worker.postMessage({ + type: "parentFunction", + id: args.id, + error: e + }); + } + } + }); + worker.on("error", (err) => { + worker.currentReject && worker.currentReject(err); + worker.currentReject = null; + }); + worker.on("exit", (code) => { + const i = this._pool.indexOf(worker); + if (i > -1) + this._pool.splice(i, 1); + if (code !== 0 && worker.currentReject) { + worker.currentReject( + new Error(`Worker stopped with non-0 exit code ${code}`) + ); + worker.currentReject = null; + } + }); + this._pool.push(worker); + return worker; + } + let resolve; + let reject; + const onWorkerAvailablePromise = new Promise((r, rj) => { + resolve = r; + reject = rj; + }); + this._queue.push([resolve, reject]); + return onWorkerAvailablePromise; + } + /** @internal */ + _assignDoneWorker(worker) { + if (this._queue.length) { + const [resolve] = this._queue.shift(); + resolve(worker); + return; + } + this._idlePool.push(worker); + } +}; +function genWorkerCode(fn, parentFunctions) { + const createParentFunctionCaller = (parentPort) => { + let id = 0; + const resolvers = /* @__PURE__ */ new Map(); + const call = (key) => async (...args) => { + id++; + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + resolvers.set(id, { resolve, reject }); + parentPort.postMessage({ type: "parentFunction", id, name: key, args }); + return await promise; + }; + const receive = (id2, args) => { + if (resolvers.has(id2)) { + const { resolve, reject } = resolvers.get(id2); + resolvers.delete(id2); + if ("result" in args) { + resolve(args.result); + } else { + reject(args.error); + } + } + }; + return { call, receive }; + }; + return ` +const { parentPort } = require('worker_threads') +const parentFunctionCaller = (${createParentFunctionCaller.toString()})(parentPort) + +const doWork = (() => { + ${Object.keys(parentFunctions).map( + (key) => `const ${key} = parentFunctionCaller.call(${JSON.stringify(key)});` + ).join("\n")} + return (${fn.toString()})() +})() + +parentPort.on('message', async (args) => { + if (args.type === 'run') { + try { + const res = await doWork(...args.args) + parentPort.postMessage({ type: 'run', result: res }) + } catch (e) { + parentPort.postMessage({ type: 'run', error: e }) + } + } else if (args.type === 'parentFunction') { + parentFunctionCaller.receive(args.id, args) + } +}) + `; +} +var FakeWorker = class { + /** @internal */ + _fn; + constructor(fn, options = {}) { + const argsAndCode = genFakeWorkerArgsAndCode( + fn, + options.parentFunctions ?? {} + ); + const require2 = createRequire$1(import.meta.url); + this._fn = new Function(...argsAndCode)(require2, options.parentFunctions); + } + async run(...args) { + try { + return await this._fn(...args); + } catch (err) { + if (err instanceof ReferenceError) { + err.message += ". Maybe you forgot to pass the function to parentFunction?"; + } + throw err; + } + } + stop() { + } +}; +function genFakeWorkerArgsAndCode(fn, parentFunctions) { + return [ + "require", + "parentFunctions", + ` +${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")} +return (${fn.toString()})() + ` + ]; +} + +// src/workerWithFallback.ts +var WorkerWithFallback = class { + /** @internal */ + _disableReal; + /** @internal */ + _realWorker; + /** @internal */ + _fakeWorker; + /** @internal */ + _shouldUseFake; + constructor(fn, options) { + this._disableReal = options.max !== void 0 && options.max <= 0; + this._realWorker = new Worker(fn, options); + this._fakeWorker = new FakeWorker(fn, options); + this._shouldUseFake = options.shouldUseFake; + } + async run(...args) { + const useFake = this._disableReal || this._shouldUseFake(...args); + return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args); + } + stop() { + this._realWorker.stop(); + this._fakeWorker.stop(); + } +}; + +let terserPath; +const loadTerserPath = (root) => { + if (terserPath) + return terserPath; + try { + terserPath = requireResolveFromRootWithFallback(root, 'terser'); + } + catch (e) { + if (e.code === 'MODULE_NOT_FOUND') { + throw new Error('terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.'); + } + else { + const message = new Error(`terser failed to load:\n${e.message}`); + message.stack = e.stack + '\n' + message.stack; + throw message; + } + } + return terserPath; +}; +function terserPlugin(config) { + const { maxWorkers, ...terserOptions } = config.build.terserOptions; + const makeWorker = () => new Worker(() => async (terserPath, code, options) => { + // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 + // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs + const terser = require(terserPath); + return terser.minify(code, options); + }, { + max: maxWorkers, + }); + let worker; + return { + name: 'vite:terser', + async renderChunk(code, _chunk, outputOptions) { + // This plugin is included for any non-false value of config.build.minify, + // so that normal chunks can use the preferred minifier, and legacy chunks + // can use terser. + if (config.build.minify !== 'terser' && + // @ts-expect-error injected by @vitejs/plugin-legacy + !outputOptions.__vite_force_terser__) { + return null; + } + // Do not minify ES lib output since that would remove pure annotations + // and break tree-shaking. + if (config.build.lib && outputOptions.format === 'es') { + return null; + } + // Lazy load worker. + worker ||= makeWorker(); + const terserPath = loadTerserPath(config.root); + const res = await worker.run(terserPath, code, { + safari10: true, + ...terserOptions, + sourceMap: !!outputOptions.sourcemap, + module: outputOptions.format.startsWith('es'), + toplevel: outputOptions.format === 'cjs', + }); + return { + code: res.code, + map: res.map, + }; + }, + closeBundle() { + worker?.stop(); + }, + }; +} + +const mimes$1 = { + "3g2": "video/3gpp2", + "3gp": "video/3gpp", + "3gpp": "video/3gpp", + "3mf": "model/3mf", + "aac": "audio/aac", + "ac": "application/pkix-attr-cert", + "adp": "audio/adpcm", + "adts": "audio/aac", + "ai": "application/postscript", + "aml": "application/automationml-aml+xml", + "amlx": "application/automationml-amlx+zip", + "amr": "audio/amr", + "apng": "image/apng", + "appcache": "text/cache-manifest", + "appinstaller": "application/appinstaller", + "appx": "application/appx", + "appxbundle": "application/appxbundle", + "asc": "application/pgp-keys", + "atom": "application/atom+xml", + "atomcat": "application/atomcat+xml", + "atomdeleted": "application/atomdeleted+xml", + "atomsvc": "application/atomsvc+xml", + "au": "audio/basic", + "avci": "image/avci", + "avcs": "image/avcs", + "avif": "image/avif", + "aw": "application/applixware", + "bdoc": "application/bdoc", + "bin": "application/octet-stream", + "bmp": "image/bmp", + "bpk": "application/octet-stream", + "btf": "image/prs.btif", + "btif": "image/prs.btif", + "buffer": "application/octet-stream", + "ccxml": "application/ccxml+xml", + "cdfx": "application/cdfx+xml", + "cdmia": "application/cdmi-capability", + "cdmic": "application/cdmi-container", + "cdmid": "application/cdmi-domain", + "cdmio": "application/cdmi-object", + "cdmiq": "application/cdmi-queue", + "cer": "application/pkix-cert", + "cgm": "image/cgm", + "cjs": "application/node", + "class": "application/java-vm", + "coffee": "text/coffeescript", + "conf": "text/plain", + "cpl": "application/cpl+xml", + "cpt": "application/mac-compactpro", + "crl": "application/pkix-crl", + "css": "text/css", + "csv": "text/csv", + "cu": "application/cu-seeme", + "cwl": "application/cwl", + "cww": "application/prs.cww", + "davmount": "application/davmount+xml", + "dbk": "application/docbook+xml", + "deb": "application/octet-stream", + "def": "text/plain", + "deploy": "application/octet-stream", + "dib": "image/bmp", + "disposition-notification": "message/disposition-notification", + "dist": "application/octet-stream", + "distz": "application/octet-stream", + "dll": "application/octet-stream", + "dmg": "application/octet-stream", + "dms": "application/octet-stream", + "doc": "application/msword", + "dot": "application/msword", + "dpx": "image/dpx", + "drle": "image/dicom-rle", + "dsc": "text/prs.lines.tag", + "dssc": "application/dssc+der", + "dtd": "application/xml-dtd", + "dump": "application/octet-stream", + "dwd": "application/atsc-dwd+xml", + "ear": "application/java-archive", + "ecma": "application/ecmascript", + "elc": "application/octet-stream", + "emf": "image/emf", + "eml": "message/rfc822", + "emma": "application/emma+xml", + "emotionml": "application/emotionml+xml", + "eps": "application/postscript", + "epub": "application/epub+zip", + "exe": "application/octet-stream", + "exi": "application/exi", + "exp": "application/express", + "exr": "image/aces", + "ez": "application/andrew-inset", + "fdf": "application/fdf", + "fdt": "application/fdt+xml", + "fits": "image/fits", + "g3": "image/g3fax", + "gbr": "application/rpki-ghostbusters", + "geojson": "application/geo+json", + "gif": "image/gif", + "glb": "model/gltf-binary", + "gltf": "model/gltf+json", + "gml": "application/gml+xml", + "gpx": "application/gpx+xml", + "gram": "application/srgs", + "grxml": "application/srgs+xml", + "gxf": "application/gxf", + "gz": "application/gzip", + "h261": "video/h261", + "h263": "video/h263", + "h264": "video/h264", + "heic": "image/heic", + "heics": "image/heic-sequence", + "heif": "image/heif", + "heifs": "image/heif-sequence", + "hej2": "image/hej2k", + "held": "application/atsc-held+xml", + "hjson": "application/hjson", + "hlp": "application/winhlp", + "hqx": "application/mac-binhex40", + "hsj2": "image/hsj2", + "htm": "text/html", + "html": "text/html", + "ics": "text/calendar", + "ief": "image/ief", + "ifb": "text/calendar", + "iges": "model/iges", + "igs": "model/iges", + "img": "application/octet-stream", + "in": "text/plain", + "ini": "text/plain", + "ink": "application/inkml+xml", + "inkml": "application/inkml+xml", + "ipfix": "application/ipfix", + "iso": "application/octet-stream", + "its": "application/its+xml", + "jade": "text/jade", + "jar": "application/java-archive", + "jhc": "image/jphc", + "jls": "image/jls", + "jp2": "image/jp2", + "jpe": "image/jpeg", + "jpeg": "image/jpeg", + "jpf": "image/jpx", + "jpg": "image/jpeg", + "jpg2": "image/jp2", + "jpgm": "image/jpm", + "jpgv": "video/jpeg", + "jph": "image/jph", + "jpm": "image/jpm", + "jpx": "image/jpx", + "js": "text/javascript", + "json": "application/json", + "json5": "application/json5", + "jsonld": "application/ld+json", + "jsonml": "application/jsonml+json", + "jsx": "text/jsx", + "jt": "model/jt", + "jxr": "image/jxr", + "jxra": "image/jxra", + "jxrs": "image/jxrs", + "jxs": "image/jxs", + "jxsc": "image/jxsc", + "jxsi": "image/jxsi", + "jxss": "image/jxss", + "kar": "audio/midi", + "ktx": "image/ktx", + "ktx2": "image/ktx2", + "less": "text/less", + "lgr": "application/lgr+xml", + "list": "text/plain", + "litcoffee": "text/coffeescript", + "log": "text/plain", + "lostxml": "application/lost+xml", + "lrf": "application/octet-stream", + "m1v": "video/mpeg", + "m21": "application/mp21", + "m2a": "audio/mpeg", + "m2v": "video/mpeg", + "m3a": "audio/mpeg", + "m4a": "audio/mp4", + "m4p": "application/mp4", + "m4s": "video/iso.segment", + "ma": "application/mathematica", + "mads": "application/mads+xml", + "maei": "application/mmt-aei+xml", + "man": "text/troff", + "manifest": "text/cache-manifest", + "map": "application/json", + "mar": "application/octet-stream", + "markdown": "text/markdown", + "mathml": "application/mathml+xml", + "mb": "application/mathematica", + "mbox": "application/mbox", + "md": "text/markdown", + "mdx": "text/mdx", + "me": "text/troff", + "mesh": "model/mesh", + "meta4": "application/metalink4+xml", + "metalink": "application/metalink+xml", + "mets": "application/mets+xml", + "mft": "application/rpki-manifest", + "mid": "audio/midi", + "midi": "audio/midi", + "mime": "message/rfc822", + "mj2": "video/mj2", + "mjp2": "video/mj2", + "mjs": "text/javascript", + "mml": "text/mathml", + "mods": "application/mods+xml", + "mov": "video/quicktime", + "mp2": "audio/mpeg", + "mp21": "application/mp21", + "mp2a": "audio/mpeg", + "mp3": "audio/mpeg", + "mp4": "video/mp4", + "mp4a": "audio/mp4", + "mp4s": "application/mp4", + "mp4v": "video/mp4", + "mpd": "application/dash+xml", + "mpe": "video/mpeg", + "mpeg": "video/mpeg", + "mpf": "application/media-policy-dataset+xml", + "mpg": "video/mpeg", + "mpg4": "video/mp4", + "mpga": "audio/mpeg", + "mpp": "application/dash-patch+xml", + "mrc": "application/marc", + "mrcx": "application/marcxml+xml", + "ms": "text/troff", + "mscml": "application/mediaservercontrol+xml", + "msh": "model/mesh", + "msi": "application/octet-stream", + "msix": "application/msix", + "msixbundle": "application/msixbundle", + "msm": "application/octet-stream", + "msp": "application/octet-stream", + "mtl": "model/mtl", + "musd": "application/mmt-usd+xml", + "mxf": "application/mxf", + "mxmf": "audio/mobile-xmf", + "mxml": "application/xv+xml", + "n3": "text/n3", + "nb": "application/mathematica", + "nq": "application/n-quads", + "nt": "application/n-triples", + "obj": "model/obj", + "oda": "application/oda", + "oga": "audio/ogg", + "ogg": "audio/ogg", + "ogv": "video/ogg", + "ogx": "application/ogg", + "omdoc": "application/omdoc+xml", + "onepkg": "application/onenote", + "onetmp": "application/onenote", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "opf": "application/oebps-package+xml", + "opus": "audio/ogg", + "otf": "font/otf", + "owl": "application/rdf+xml", + "oxps": "application/oxps", + "p10": "application/pkcs10", + "p7c": "application/pkcs7-mime", + "p7m": "application/pkcs7-mime", + "p7s": "application/pkcs7-signature", + "p8": "application/pkcs8", + "pdf": "application/pdf", + "pfr": "application/font-tdpfr", + "pgp": "application/pgp-encrypted", + "pkg": "application/octet-stream", + "pki": "application/pkixcmp", + "pkipath": "application/pkix-pkipath", + "pls": "application/pls+xml", + "png": "image/png", + "prc": "model/prc", + "prf": "application/pics-rules", + "provx": "application/provenance+xml", + "ps": "application/postscript", + "pskcxml": "application/pskc+xml", + "pti": "image/prs.pti", + "qt": "video/quicktime", + "raml": "application/raml+yaml", + "rapd": "application/route-apd+xml", + "rdf": "application/rdf+xml", + "relo": "application/p2p-overlay+xml", + "rif": "application/reginfo+xml", + "rl": "application/resource-lists+xml", + "rld": "application/resource-lists-diff+xml", + "rmi": "audio/midi", + "rnc": "application/relax-ng-compact-syntax", + "rng": "application/xml", + "roa": "application/rpki-roa", + "roff": "text/troff", + "rq": "application/sparql-query", + "rs": "application/rls-services+xml", + "rsat": "application/atsc-rsat+xml", + "rsd": "application/rsd+xml", + "rsheet": "application/urc-ressheet+xml", + "rss": "application/rss+xml", + "rtf": "text/rtf", + "rtx": "text/richtext", + "rusd": "application/route-usd+xml", + "s3m": "audio/s3m", + "sbml": "application/sbml+xml", + "scq": "application/scvp-cv-request", + "scs": "application/scvp-cv-response", + "sdp": "application/sdp", + "senmlx": "application/senml+xml", + "sensmlx": "application/sensml+xml", + "ser": "application/java-serialized-object", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "sgi": "image/sgi", + "sgm": "text/sgml", + "sgml": "text/sgml", + "shex": "text/shex", + "shf": "application/shf+xml", + "shtml": "text/html", + "sieve": "application/sieve", + "sig": "application/pgp-signature", + "sil": "audio/silk", + "silo": "model/mesh", + "siv": "application/sieve", + "slim": "text/slim", + "slm": "text/slim", + "sls": "application/route-s-tsid+xml", + "smi": "application/smil+xml", + "smil": "application/smil+xml", + "snd": "audio/basic", + "so": "application/octet-stream", + "spdx": "text/spdx", + "spp": "application/scvp-vp-response", + "spq": "application/scvp-vp-request", + "spx": "audio/ogg", + "sql": "application/sql", + "sru": "application/sru+xml", + "srx": "application/sparql-results+xml", + "ssdl": "application/ssdl+xml", + "ssml": "application/ssml+xml", + "stk": "application/hyperstudio", + "stl": "model/stl", + "stpx": "model/step+xml", + "stpxz": "model/step-xml+zip", + "stpz": "model/step+zip", + "styl": "text/stylus", + "stylus": "text/stylus", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "swidtag": "application/swid+xml", + "t": "text/troff", + "t38": "image/t38", + "td": "application/urc-targetdesc+xml", + "tei": "application/tei+xml", + "teicorpus": "application/tei+xml", + "text": "text/plain", + "tfi": "application/thraud+xml", + "tfx": "image/tiff-fx", + "tif": "image/tiff", + "tiff": "image/tiff", + "toml": "application/toml", + "tr": "text/troff", + "trig": "application/trig", + "ts": "video/mp2t", + "tsd": "application/timestamped-data", + "tsv": "text/tab-separated-values", + "ttc": "font/collection", + "ttf": "font/ttf", + "ttl": "text/turtle", + "ttml": "application/ttml+xml", + "txt": "text/plain", + "u3d": "model/u3d", + "u8dsn": "message/global-delivery-status", + "u8hdr": "message/global-headers", + "u8mdn": "message/global-disposition-notification", + "u8msg": "message/global", + "ubj": "application/ubjson", + "uri": "text/uri-list", + "uris": "text/uri-list", + "urls": "text/uri-list", + "vcard": "text/vcard", + "vrml": "model/vrml", + "vtt": "text/vtt", + "vxml": "application/voicexml+xml", + "war": "application/java-archive", + "wasm": "application/wasm", + "wav": "audio/wav", + "weba": "audio/webm", + "webm": "video/webm", + "webmanifest": "application/manifest+json", + "webp": "image/webp", + "wgsl": "text/wgsl", + "wgt": "application/widget", + "wif": "application/watcherinfo+xml", + "wmf": "image/wmf", + "woff": "font/woff", + "woff2": "font/woff2", + "wrl": "model/vrml", + "wsdl": "application/wsdl+xml", + "wspolicy": "application/wspolicy+xml", + "x3d": "model/x3d+xml", + "x3db": "model/x3d+fastinfoset", + "x3dbz": "model/x3d+binary", + "x3dv": "model/x3d-vrml", + "x3dvz": "model/x3d+vrml", + "x3dz": "model/x3d+xml", + "xaml": "application/xaml+xml", + "xav": "application/xcap-att+xml", + "xca": "application/xcap-caps+xml", + "xcs": "application/calendar+xml", + "xdf": "application/xcap-diff+xml", + "xdssc": "application/dssc+xml", + "xel": "application/xcap-el+xml", + "xenc": "application/xenc+xml", + "xer": "application/patch-ops-error+xml", + "xfdf": "application/xfdf", + "xht": "application/xhtml+xml", + "xhtml": "application/xhtml+xml", + "xhvml": "application/xv+xml", + "xlf": "application/xliff+xml", + "xm": "audio/xm", + "xml": "text/xml", + "xns": "application/xcap-ns+xml", + "xop": "application/xop+xml", + "xpl": "application/xproc+xml", + "xsd": "application/xml", + "xsf": "application/prs.xsf+xml", + "xsl": "application/xml", + "xslt": "application/xml", + "xspf": "application/xspf+xml", + "xvm": "application/xv+xml", + "xvml": "application/xv+xml", + "yaml": "text/yaml", + "yang": "application/yang", + "yin": "application/yin+xml", + "yml": "text/yaml", + "zip": "application/zip" +}; + +function lookup(extn) { + let tmp = ('' + extn).trim().toLowerCase(); + let idx = tmp.lastIndexOf('.'); + return mimes$1[!~idx ? tmp : tmp.substring(++idx)]; +} + +const publicFilesMap = new WeakMap(); +async function initPublicFiles(config) { + let fileNames; + try { + fileNames = await recursiveReaddir(config.publicDir); + } + catch (e) { + if (e.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) { + return; + } + throw e; + } + const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config.publicDir.length))); + publicFilesMap.set(config, publicFiles); + return publicFiles; +} +function getPublicFiles(config) { + return publicFilesMap.get(config); +} +function checkPublicFile(url, config) { + // note if the file is in /public, the resolver would have returned it + // as-is so it's not going to be a fully resolved path. + const { publicDir } = config; + if (!publicDir || url[0] !== '/') { + return; + } + const fileName = cleanUrl(url); + // short-circuit if we have an in-memory publicFiles cache + const publicFiles = getPublicFiles(config); + if (publicFiles) { + return publicFiles.has(fileName) + ? normalizePath$3(path$o.join(publicDir, fileName)) + : undefined; + } + const publicFile = normalizePath$3(path$o.join(publicDir, fileName)); + if (!publicFile.startsWith(withTrailingSlash(publicDir))) { + // can happen if URL starts with '../' + return; + } + return fs$l.existsSync(publicFile) ? publicFile : undefined; +} + +// referenceId is base64url but replaces - with $ +const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g; +const jsSourceMapRE = /\.[cm]?js\.map$/; +const assetCache = new WeakMap(); +const generatedAssets = new WeakMap(); +// add own dictionary entry by directly assigning mrmime +function registerCustomMime() { + // https://github.com/lukeed/mrmime/issues/3 + mimes$1['ico'] = 'image/x-icon'; + // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#flac + mimes$1['flac'] = 'audio/flac'; + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types + mimes$1['eot'] = 'application/vnd.ms-fontobject'; +} +function renderAssetUrlInJS(ctx, config, chunk, opts, code) { + const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker); + let match; + let s; + // Urls added with JS using e.g. + // imgElement.src = "__VITE_ASSET__5aA0Ddc0__" are using quotes + // Urls added in CSS that is imported in JS end up like + // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aA0Ddc0__)}\n"; + // In both cases, the wrapping should already be fine + assetUrlRE.lastIndex = 0; + while ((match = assetUrlRE.exec(code))) { + s ||= new MagicString(code); + const [full, referenceId, postfix = ''] = match; + const file = ctx.getFileName(referenceId); + chunk.viteMetadata.importedAssets.add(cleanUrl(file)); + const filename = file + postfix; + const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime); + const replacementString = typeof replacement === 'string' + ? JSON.stringify(replacement).slice(1, -1) + : `"+${replacement.runtime}+"`; + s.update(match.index, match.index + full.length, replacementString); + } + // Replace __VITE_PUBLIC_ASSET__5aA0Ddc0__ with absolute paths + const publicAssetUrlMap = publicAssetUrlCache.get(config); + publicAssetUrlRE.lastIndex = 0; + while ((match = publicAssetUrlRE.exec(code))) { + s ||= new MagicString(code); + const [full, hash] = match; + const publicUrl = publicAssetUrlMap.get(hash).slice(1); + const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime); + const replacementString = typeof replacement === 'string' + ? JSON.stringify(replacement).slice(1, -1) + : `"+${replacement.runtime}+"`; + s.update(match.index, match.index + full.length, replacementString); + } + return s; +} +// During build, if we don't use a virtual file for public assets, rollup will +// watch for these ids resulting in watching the root of the file system in Windows, +const viteBuildPublicIdPrefix = '\0vite:asset:public'; +/** + * Also supports loading plain strings with import text from './foo.txt?raw' + */ +function assetPlugin(config) { + registerCustomMime(); + let moduleGraph; + return { + name: 'vite:asset', + buildStart() { + assetCache.set(config, new Map()); + generatedAssets.set(config, new Map()); + }, + configureServer(server) { + moduleGraph = server.moduleGraph; + }, + resolveId(id) { + if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { + return; + } + // imports to absolute urls pointing to files in /public + // will fail to resolve in the main resolver. handle them here. + const publicFile = checkPublicFile(id, config); + if (publicFile) { + return config.command === 'build' + ? `${viteBuildPublicIdPrefix}${id}` + : id; + } + }, + async load(id) { + if (id.startsWith(viteBuildPublicIdPrefix)) { + id = id.slice(viteBuildPublicIdPrefix.length); + } + if (id[0] === '\0') { + // Rollup convention, this id should be handled by the + // plugin that marked it with \0 + return; + } + // raw requests, read from disk + if (rawRE.test(id)) { + const file = checkPublicFile(id, config) || cleanUrl(id); + this.addWatchFile(file); + // raw query, read file and return as string + return `export default ${JSON.stringify(await fsp.readFile(file, 'utf-8'))}`; + } + if (!urlRE.test(id) && !config.assetsInclude(cleanUrl(id))) { + return; + } + id = removeUrlQuery(id); + let url = await fileToUrl$1(id, config, this); + // Inherit HMR timestamp if this asset was invalidated + if (moduleGraph) { + const mod = moduleGraph.getModuleById(id); + if (mod && mod.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); + } + } + return `export default ${JSON.stringify(url)}`; + }, + renderChunk(code, chunk, opts) { + const s = renderAssetUrlInJS(this, config, chunk, opts, code); + if (s) { + return { + code: s.toString(), + map: config.build.sourcemap + ? s.generateMap({ hires: 'boundary' }) + : null, + }; + } + else { + return null; + } + }, + generateBundle(_, bundle) { + // do not emit assets for SSR build + if (config.command === 'build' && + config.build.ssr && + !config.build.ssrEmitAssets) { + for (const file in bundle) { + if (bundle[file].type === 'asset' && + !file.endsWith('ssr-manifest.json') && + !jsSourceMapRE.test(file)) { + delete bundle[file]; + } + } + } + }, + }; +} +async function fileToUrl$1(id, config, ctx) { + if (config.command === 'serve') { + return fileToDevUrl(id, config); + } + else { + return fileToBuiltUrl(id, config, ctx); + } +} +function fileToDevUrl(id, config) { + let rtn; + if (checkPublicFile(id, config)) { + // in public dir during dev, keep the url as-is + rtn = id; + } + else if (id.startsWith(withTrailingSlash(config.root))) { + // in project root, infer short public path + rtn = '/' + path$o.posix.relative(config.root, id); + } + else { + // outside of project root, use absolute fs path + // (this is special handled by the serve static middleware + rtn = path$o.posix.join(FS_PREFIX, id); + } + const base = joinUrlSegments(config.server?.origin ?? '', config.base); + return joinUrlSegments(base, removeLeadingSlash(rtn)); +} +function getPublicAssetFilename(hash, config) { + return publicAssetUrlCache.get(config)?.get(hash); +} +const publicAssetUrlCache = new WeakMap(); +const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g; +function publicFileToBuiltUrl(url, config) { + if (config.command !== 'build') { + // We don't need relative base or renderBuiltUrl support during dev + return joinUrlSegments(config.base, url); + } + const hash = getHash(url); + let cache = publicAssetUrlCache.get(config); + if (!cache) { + cache = new Map(); + publicAssetUrlCache.set(config, cache); + } + if (!cache.get(hash)) { + cache.set(hash, url); + } + return `__VITE_PUBLIC_ASSET__${hash}__`; +} +const GIT_LFS_PREFIX = Buffer$1.from('version https://git-lfs.github.com'); +function isGitLfsPlaceholder(content) { + if (content.length < GIT_LFS_PREFIX.length) + return false; + // Check whether the content begins with the characteristic string of Git LFS placeholders + return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0; +} +/** + * Register an asset to be emitted as part of the bundle (if necessary) + * and returns the resolved public URL + */ +async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false, forceInline) { + if (!skipPublicCheck && checkPublicFile(id, config)) { + return publicFileToBuiltUrl(id, config); + } + const cache = assetCache.get(config); + const cached = cache.get(id); + if (cached) { + return cached; + } + const file = cleanUrl(id); + const content = await fsp.readFile(file); + let url; + if (shouldInline(config, file, id, content, forceInline)) { + if (config.build.lib && isGitLfsPlaceholder(content)) { + config.logger.warn(colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`)); + } + if (file.endsWith('.svg')) { + url = svgToDataURL(content); + } + else { + const mimeType = lookup(file) ?? 'application/octet-stream'; + // base64 inlined as a string + url = `data:${mimeType};base64,${content.toString('base64')}`; + } + } + else { + // emit as asset + const { search, hash } = parse$i(id); + const postfix = (search || '') + (hash || ''); + const referenceId = pluginContext.emitFile({ + // Ignore directory structure for asset file names + name: path$o.basename(file), + type: 'asset', + source: content, + }); + const originalName = normalizePath$3(path$o.relative(config.root, file)); + generatedAssets.get(config).set(referenceId, { originalName }); + url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE + } + cache.set(id, url); + return url; +} +async function urlToBuiltUrl(url, importer, config, pluginContext, forceInline) { + if (checkPublicFile(url, config)) { + return publicFileToBuiltUrl(url, config); + } + const file = url[0] === '/' + ? path$o.join(config.root, url) + : path$o.join(path$o.dirname(importer), url); + return fileToBuiltUrl(file, config, pluginContext, + // skip public check since we just did it above + true, forceInline); +} +const shouldInline = (config, file, id, content, forceInline) => { + if (config.build.lib) + return true; + if (forceInline !== undefined) + return forceInline; + let limit; + if (typeof config.build.assetsInlineLimit === 'function') { + const userShouldInline = config.build.assetsInlineLimit(file, content); + if (userShouldInline != null) + return userShouldInline; + limit = DEFAULT_ASSETS_INLINE_LIMIT; + } + else { + limit = Number(config.build.assetsInlineLimit); + } + if (file.endsWith('.html')) + return false; + // Don't inline SVG with fragments, as they are meant to be reused + if (file.endsWith('.svg') && id.includes('#')) + return false; + return content.length < limit && !isGitLfsPlaceholder(content); +}; +const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/; +// Inspired by https://github.com/iconify/iconify/blob/main/packages/utils/src/svg/url.ts +function svgToDataURL(content) { + const stringContent = content.toString(); + // If the SVG contains some text or HTML, any transformation is unsafe, and given that double quotes would then + // need to be escaped, the gain to use a data URI would be ridiculous if not negative + if (stringContent.includes('\s+<') + .replaceAll('"', "'") + .replaceAll('%', '%25') + .replaceAll('#', '%23') + .replaceAll('<', '%3c') + .replaceAll('>', '%3e') + // Spaces are not valid in srcset it has some use cases + // it can make the uncompressed URI slightly higher than base64, but will compress way better + // https://github.com/vitejs/vite/pull/14643#issuecomment-1766288673 + .replaceAll(/\s+/g, '%20')); + } +} + +const endsWithJSRE = /\.[cm]?js$/; +function manifestPlugin(config) { + const manifest = {}; + let outputCount; + return { + name: 'vite:manifest', + buildStart() { + outputCount = 0; + }, + generateBundle({ format }, bundle) { + function getChunkName(chunk) { + return getChunkOriginalFileName(chunk, config.root, format); + } + function getInternalImports(imports) { + const filteredImports = []; + for (const file of imports) { + if (bundle[file] === undefined) { + continue; + } + filteredImports.push(getChunkName(bundle[file])); + } + return filteredImports; + } + function createChunk(chunk) { + const manifestChunk = { + file: chunk.fileName, + }; + if (chunk.facadeModuleId) { + manifestChunk.src = getChunkName(chunk); + } + if (chunk.isEntry) { + manifestChunk.isEntry = true; + } + if (chunk.isDynamicEntry) { + manifestChunk.isDynamicEntry = true; + } + if (chunk.imports.length) { + const internalImports = getInternalImports(chunk.imports); + if (internalImports.length > 0) { + manifestChunk.imports = internalImports; + } + } + if (chunk.dynamicImports.length) { + const internalImports = getInternalImports(chunk.dynamicImports); + if (internalImports.length > 0) { + manifestChunk.dynamicImports = internalImports; + } + } + if (chunk.viteMetadata?.importedCss.size) { + manifestChunk.css = [...chunk.viteMetadata.importedCss]; + } + if (chunk.viteMetadata?.importedAssets.size) { + manifestChunk.assets = [...chunk.viteMetadata.importedAssets]; + } + return manifestChunk; + } + function createAsset(asset, src, isEntry) { + const manifestChunk = { + file: asset.fileName, + src, + }; + if (isEntry) + manifestChunk.isEntry = true; + return manifestChunk; + } + const fileNameToAssetMeta = new Map(); + const assets = generatedAssets.get(config); + assets.forEach((asset, referenceId) => { + try { + const fileName = this.getFileName(referenceId); + fileNameToAssetMeta.set(fileName, asset); + } + catch (error) { + // The asset was generated as part of a different output option. + // It was already handled during the previous run of this plugin. + assets.delete(referenceId); + } + }); + const fileNameToAsset = new Map(); + for (const file in bundle) { + const chunk = bundle[file]; + if (chunk.type === 'chunk') { + manifest[getChunkName(chunk)] = createChunk(chunk); + } + else if (chunk.type === 'asset' && typeof chunk.name === 'string') { + // Add every unique asset to the manifest, keyed by its original name + const assetMeta = fileNameToAssetMeta.get(chunk.fileName); + const src = assetMeta?.originalName ?? chunk.name; + const asset = createAsset(chunk, src, assetMeta?.isEntry); + // If JS chunk and asset chunk are both generated from the same source file, + // prioritize JS chunk as it contains more information + const file = manifest[src]?.file; + if (file && endsWithJSRE.test(file)) + continue; + manifest[src] = asset; + fileNameToAsset.set(chunk.fileName, asset); + } + } + // Add deduplicated assets to the manifest + assets.forEach(({ originalName }, referenceId) => { + if (!manifest[originalName]) { + const fileName = this.getFileName(referenceId); + const asset = fileNameToAsset.get(fileName); + if (asset) { + manifest[originalName] = asset; + } + } + }); + outputCount++; + const output = config.build.rollupOptions?.output; + const outputLength = Array.isArray(output) ? output.length : 1; + if (outputCount >= outputLength) { + this.emitFile({ + fileName: typeof config.build.manifest === 'string' + ? config.build.manifest + : '.vite/manifest.json', + type: 'asset', + source: JSON.stringify(sortObjectKeys(manifest), undefined, 2), + }); + } + }, + }; +} +function getChunkOriginalFileName(chunk, root, format) { + if (chunk.facadeModuleId) { + let name = normalizePath$3(path$o.relative(root, chunk.facadeModuleId)); + if (format === 'system' && !chunk.name.includes('-legacy')) { + const ext = path$o.extname(name); + const endPos = ext.length !== 0 ? -ext.length : undefined; + name = name.slice(0, endPos) + `-legacy` + ext; + } + return name.replace(/\0/g, ''); + } + else { + return `_` + path$o.basename(chunk.fileName); + } +} + +// This is based on @rollup/plugin-data-uri +// MIT Licensed https://github.com/rollup/plugins/blob/master/LICENSE +// ref https://github.com/vitejs/vite/issues/1428#issuecomment-757033808 +const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; +const base64RE = /base64/i; +const dataUriPrefix = `\0/@data-uri/`; +/** + * Build only, since importing from a data URI works natively. + */ +function dataURIPlugin() { + let resolved; + return { + name: 'vite:data-uri', + buildStart() { + resolved = new Map(); + }, + resolveId(id) { + if (!dataUriRE.test(id)) { + return; + } + const uri = new URL$3(id); + if (uri.protocol !== 'data:') { + return; + } + const match = uri.pathname.match(dataUriRE); + if (!match) { + return; + } + const [, mime, format, data] = match; + if (mime !== 'text/javascript') { + throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`); + } + // decode data + const base64 = format && base64RE.test(format.substring(1)); + const content = base64 + ? Buffer.from(data, 'base64').toString('utf-8') + : data; + resolved.set(id, content); + return dataUriPrefix + id; + }, + load(id) { + if (id.startsWith(dataUriPrefix)) { + return resolved.get(id.slice(dataUriPrefix.length)); + } + }, + }; +} + +/* es-module-lexer 1.4.1 */ +const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,k=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;k>0&&C.memory.grow(Math.ceil(k/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const o=[],D=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),k=C.se();let K;C.ip()&&(K=w(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),o.push({n:K,s:A,e:Q,ss:I,se:k,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),k=I[0],K=B<0?void 0:E.slice(B,g),o=K?K[0]:"";D.push({s:A,e:Q,ls:B,le:g,n:'"'===k||"'"===k?w(I):I,ln:'"'===o||"'"===o?w(K):K});}function w(A){try{return (0, eval)(A)}catch(A){}}return [o,D,!!C.f(),!!C.ms()]}function Q(A,Q){const B=A.length;let C=0;for(;C>>8;}}function B(A,Q){const B=A.length;let C=0;for(;CA.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E; + +var convertSourceMap$1 = {}; + +(function (exports) { + + Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + } + }); + + + Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + } + }); + + var decodeBase64; + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + decodeBase64 = decodeBase64WithBufferFrom; + } else { + decodeBase64 = decodeBase64WithNewBuffer; + } + } else { + decodeBase64 = decodeBase64WithAtob; + } + + function decodeBase64WithBufferFrom(base64) { + return Buffer.from(base64, 'base64').toString(); + } + + function decodeBase64WithNewBuffer(base64) { + if (typeof value === 'number') { + throw new TypeError('The value to decode must not be of type number.'); + } + return new Buffer(base64, 'base64').toString(); + } + + function decodeBase64WithAtob(base64) { + return decodeURIComponent(escape(atob(base64))); + } + + function stripComment(sm) { + return sm.split(',').pop(); + } + + function readFromFileMap(sm, read) { + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + + try { + var sm = read(filename); + if (sm != null && typeof sm.catch === 'function') { + return sm.catch(throwError); + } else { + return sm; + } + } catch (e) { + throwError(e); + } + + function throwError(e) { + throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + } + } + + function Converter (sm, opts) { + opts = opts || {}; + + if (opts.hasComment) { + sm = stripComment(sm); + } + + if (opts.encoding === 'base64') { + sm = decodeBase64(sm); + } else if (opts.encoding === 'uri') { + sm = decodeURIComponent(sm); + } + + if (opts.isJSON || opts.encoding) { + sm = JSON.parse(sm); + } + + this.sourcemap = sm; + } + + Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); + }; + + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + Converter.prototype.toBase64 = encodeBase64WithBufferFrom; + } else { + Converter.prototype.toBase64 = encodeBase64WithNewBuffer; + } + } else { + Converter.prototype.toBase64 = encodeBase64WithBtoa; + } + + function encodeBase64WithBufferFrom() { + var json = this.toJSON(); + return Buffer.from(json, 'utf8').toString('base64'); + } + + function encodeBase64WithNewBuffer() { + var json = this.toJSON(); + if (typeof json === 'number') { + throw new TypeError('The json to encode must not be of type number.'); + } + return new Buffer(json, 'utf8').toString('base64'); + } + + function encodeBase64WithBtoa() { + var json = this.toJSON(); + return btoa(unescape(encodeURIComponent(json))); + } + + Converter.prototype.toURI = function () { + var json = this.toJSON(); + return encodeURIComponent(json); + }; + + Converter.prototype.toComment = function (options) { + var encoding, content, data; + if (options != null && options.encoding === 'uri') { + encoding = ''; + content = this.toURI(); + } else { + encoding = ';base64'; + content = this.toBase64(); + } + data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; + return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; + + // returns copy instead of original + Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); + }; + + Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); + }; + + Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; + }; + + Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; + }; + + exports.fromObject = function (obj) { + return new Converter(obj); + }; + + exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); + }; + + exports.fromURI = function (uri) { + return new Converter(uri, { encoding: 'uri' }); + }; + + exports.fromBase64 = function (base64) { + return new Converter(base64, { encoding: 'base64' }); + }; + + exports.fromComment = function (comment) { + var m, encoding; + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + m = exports.commentRegex.exec(comment); + encoding = m && m[4] || 'uri'; + return new Converter(comment, { encoding: encoding, hasComment: true }); + }; + + function makeConverter(sm) { + return new Converter(sm, { isJSON: true }); + } + + exports.fromMapFileComment = function (comment, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileComment`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + + var sm = readFromFileMap(comment, read); + if (sm != null && typeof sm.then === 'function') { + return sm.then(makeConverter); + } else { + return makeConverter(sm); + } + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromMapFileSource = function (content, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileSource`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), read) : null; + }; + + exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); + }; + + exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); + }; + + exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; +} (convertSourceMap$1)); + +var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1); + +const debug$g = createDebugger('vite:sourcemap', { + onlyWhenFocused: true, +}); +// Virtual modules should be prefixed with a null byte to avoid a +// false positive "missing source" warning. We also check for certain +// prefixes used for special handling in esbuildDepPlugin. +const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/; +async function computeSourceRoute(map, file) { + let sourceRoot; + try { + // The source root is undefined for virtual modules and permission errors. + sourceRoot = await fsp.realpath(path$o.resolve(path$o.dirname(file), map.sourceRoot || '')); + } + catch { } + return sourceRoot; +} +async function injectSourcesContent(map, file, logger) { + let sourceRootPromise; + const missingSources = []; + const sourcesContent = map.sourcesContent || []; + const sourcesContentPromises = []; + for (let index = 0; index < map.sources.length; index++) { + const sourcePath = map.sources[index]; + if (!sourcesContent[index] && + sourcePath && + !virtualSourceRE.test(sourcePath)) { + sourcesContentPromises.push((async () => { + // inject content from source file when sourcesContent is null + sourceRootPromise ??= computeSourceRoute(map, file); + const sourceRoot = await sourceRootPromise; + let resolvedSourcePath = decodeURI(sourcePath); + if (sourceRoot) { + resolvedSourcePath = path$o.resolve(sourceRoot, resolvedSourcePath); + } + sourcesContent[index] = await fsp + .readFile(resolvedSourcePath, 'utf-8') + .catch(() => { + missingSources.push(resolvedSourcePath); + return null; + }); + })()); + } + } + await Promise.all(sourcesContentPromises); + map.sourcesContent = sourcesContent; + // Use this command… + // DEBUG="vite:sourcemap" vite build + // …to log the missing sources. + if (missingSources.length) { + logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); + debug$g?.(`Missing sources:\n ` + missingSources.join(`\n `)); + } +} +function genSourceMapUrl(map) { + if (typeof map !== 'string') { + map = JSON.stringify(map); + } + return `data:application/json;base64,${Buffer.from(map).toString('base64')}`; +} +function getCodeWithSourcemap(type, code, map) { + if (debug$g) { + code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; + } + if (type === 'js') { + code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; + } + else if (type === 'css') { + code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; + } + return code; +} +function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) { + let { x_google_ignoreList } = map; + if (x_google_ignoreList === undefined) { + x_google_ignoreList = []; + } + for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) { + const sourcePath = map.sources[sourcesIndex]; + if (!sourcePath) + continue; + const ignoreList = sourcemapIgnoreList(path$o.isAbsolute(sourcePath) + ? sourcePath + : path$o.resolve(path$o.dirname(sourcemapPath), sourcePath), sourcemapPath); + if (logger && typeof ignoreList !== 'boolean') { + logger.warn('sourcemapIgnoreList function must return a boolean.'); + } + if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) { + x_google_ignoreList.push(sourcesIndex); + } + } + if (x_google_ignoreList.length > 0) { + if (!map.x_google_ignoreList) + map.x_google_ignoreList = x_google_ignoreList; + } +} + +var tasks = {}; + +var utils$g = {}; + +var array$1 = {}; + +Object.defineProperty(array$1, "__esModule", { value: true }); +array$1.splitWhen = array$1.flatten = void 0; +function flatten$1(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +array$1.flatten = flatten$1; +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; +} +array$1.splitWhen = splitWhen; + +var errno$1 = {}; + +Object.defineProperty(errno$1, "__esModule", { value: true }); +errno$1.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +errno$1.isEnoentCodeError = isEnoentCodeError; + +var fs$h = {}; + +Object.defineProperty(fs$h, "__esModule", { value: true }); +fs$h.createDirentFromStats = void 0; +let DirentFromStats$1 = 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$1(name, stats) { + return new DirentFromStats$1(name, stats); +} +fs$h.createDirentFromStats = createDirentFromStats$1; + +var path$h = {}; + +Object.defineProperty(path$h, "__esModule", { value: true }); +path$h.convertPosixPathToPattern = path$h.convertWindowsPathToPattern = path$h.convertPathToPattern = path$h.escapePosixPath = path$h.escapeWindowsPath = path$h.escape = path$h.removeLeadingDotSegment = path$h.makeAbsolute = path$h.unixify = void 0; +const os$3 = require$$2; +const path$g = require$$0$4; +const IS_WINDOWS_PLATFORM = os$3.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, '/'); +} +path$h.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path$g.resolve(cwd, filepath); +} +path$h.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; +} +path$h.removeLeadingDotSegment = removeLeadingDotSegment; +path$h.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; +function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +path$h.escapeWindowsPath = escapeWindowsPath; +function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +path$h.escapePosixPath = escapePosixPath; +path$h.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; +function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath) + .replace(DOS_DEVICE_PATH_RE, '//$1') + .replace(WINDOWS_BACKSLASHES_RE, '/'); +} +path$h.convertWindowsPathToPattern = convertWindowsPathToPattern; +function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); +} +path$h.convertPosixPathToPattern = convertPosixPathToPattern; + +var pattern$1 = {}; + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob$1 = 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; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = isExtglob$1; +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; +}; + +var isGlob$2 = 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); +}; + +var isGlob$1 = isGlob$2; +var pathPosixDirname = require$$0$4.posix.dirname; +var isWin32 = require$$2.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} + */ +var globParent$2 = 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$1(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +var utils$f = {}; + +(function (exports) { + + exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; + }; + + /** + * Find a node of the given type + */ + + exports.find = (node, type) => node.nodes.find(node => 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) => { + let 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++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; + }; +} (utils$f)); + +const utils$e = utils$f; + +var stringify$7 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$e.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$2 = 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; +}; + +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +const isNumber$1 = isNumber$2; + +const toRegexRange$1 = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { + return toRegexRange$1.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange$1.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange$1.cache = {}; +toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); + +/** + * Expose `toRegexRange` + */ + +var toRegexRange_1 = toRegexRange$1; + +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +const util$1 = require$$0$6; +const toRegexRange = toRegexRange_1; + +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$6 = (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) => { + 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.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.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$1.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$6(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) + : 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$2 = (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$2(start, end, 1, { transform: step }); + } + + if (isObject(step)) { + return fill$2(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$2(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill$2; + +const fill$1 = fillRange; +const utils$d = utils$f; + +const compile$1 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$d.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + 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) { + let args = utils$d.reduce(node.nodes); + let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile$1; + +const fill = fillRange; +const stringify$5 = stringify$7; +const utils$c = utils$f; + +const append$1 = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils$c.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append$1(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele)); + } + } + } + return utils$c.flatten(result); +}; + +const expand$2 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let 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$1(q.pop(), stringify$5(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append$1(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$c.reduce(node.nodes); + + if (utils$c.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$5(node, options); + } + + q.push(append$1(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$c.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++) { + let 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$1(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append$1(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$c.flatten(walk(ast)); +}; + +var expand_1$1 = expand$2; + +var constants$3 = { + MAX_LENGTH: 1024 * 64, + + // 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 */ +}; + +const stringify$4 = stringify$7; + +/** + * 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 +} = constants$3; + +/** + * parse + */ + +const parse$d = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let 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})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let 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) { + let 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++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let 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; + } + + let 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; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify$4(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let 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(); + + let 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) + let parent = stack[stack.length - 1]; + let 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; +}; + +var parse_1$2 = parse$d; + +const stringify$3 = stringify$7; +const compile = compile_1; +const expand$1 = expand_1$1; +const parse$c = parse_1$2; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces$2 = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces$2.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces$2.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$2.parse = (input, options = {}) => parse$c(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$2.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify$3(braces$2.parse(input, options), options); + } + return stringify$3(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$2.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$2.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$2.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$2.parse(input, options); + } + + let result = expand$1(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$2.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces$2.compile(input, options) + : braces$2.expand(input, options); +}; + +/** + * Expose "braces" + */ + +var braces_1 = braces$2; + +const util = require$$0$6; +const braces$1 = braces_1; +const picomatch$2 = picomatch$3; +const utils$b = utils$k; +const isEmptyString = val => val === '' || val === './'; + +/** + * 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$1 = (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$2(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$1.match = micromatch$1; + +/** + * 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$1.matcher = (pattern, options) => picomatch$2(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$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); + +/** + * Backwards compatibility + */ + +micromatch$1.any = micromatch$1.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$1.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$1(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$1.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$1.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$1.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$1.matchKeys = (obj, patterns, options) => { + if (!utils$b.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch$1(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$1.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$2(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$1.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$2(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$1.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch$2(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$1.capture = (glob, input, options) => { + let posix = utils$b.isWindows(options); + let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils$b.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$1.makeRe = (...args) => picomatch$2.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$1.scan = (...args) => picomatch$2.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$1.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces$1(String(pattern), options)) { + res.push(picomatch$2.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$1.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + return braces$1(pattern, options); +}; + +/** + * Expand braces + */ + +micromatch$1.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch$1.braces(pattern, { ...options, expand: true }); +}; + +/** + * Expose micromatch + */ + +var micromatch_1 = micromatch$1; + +var micromatch$2 = /*@__PURE__*/getDefaultExportFromCjs(micromatch_1); + +Object.defineProperty(pattern$1, "__esModule", { value: true }); +pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; +const path$f = require$$0$4; +const globParent$1 = globParent$2; +const micromatch = micromatch_1; +const GLOBSTAR$1 = '**'; +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$1 = /(?!^)\/{2,}/g; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +pattern$1.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; +} +pattern$1.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; +} +pattern$1.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +pattern$1.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +pattern$1.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +pattern$1.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +pattern$1.getNegativePatterns = getNegativePatterns; +function getPositivePatterns$1(patterns) { + return patterns.filter(isPositivePattern); +} +pattern$1.getPositivePatterns = getPositivePatterns$1; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent$1(pattern, { flipBackslashes: false }); +} +pattern$1.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR$1); +} +pattern$1.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR$1); +} +pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path$f.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +pattern$1.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 !== ''); +} +pattern$1.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; +} +pattern$1.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +pattern$1.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +pattern$1.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +pattern$1.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$1, '/'); +} +pattern$1.removeDuplicateSlashes = removeDuplicateSlashes; + +var stream$4 = {}; + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ +const Stream = require$$0$7; +const PassThrough = Stream.PassThrough; +const slice = Array.prototype.slice; + +var merge2_1 = merge2$1; + +function merge2$1 () { + 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 +} + +Object.defineProperty(stream$4, "__esModule", { value: true }); +stream$4.merge = void 0; +const merge2 = merge2_1; +function merge$1(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; +} +stream$4.merge = merge$1; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} + +var string$2 = {}; + +Object.defineProperty(string$2, "__esModule", { value: true }); +string$2.isEmpty = string$2.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +string$2.isString = isString; +function isEmpty$1(input) { + return input === ''; +} +string$2.isEmpty = isEmpty$1; + +Object.defineProperty(utils$g, "__esModule", { value: true }); +utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0; +const array = array$1; +utils$g.array = array; +const errno = errno$1; +utils$g.errno = errno; +const fs$g = fs$h; +utils$g.fs = fs$g; +const path$e = path$h; +utils$g.path = path$e; +const pattern = pattern$1; +utils$g.pattern = pattern; +const stream$3 = stream$4; +utils$g.stream = stream$3; +const string$1 = string$2; +utils$g.string = string$1; + +Object.defineProperty(tasks, "__esModule", { value: true }); +tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; +const utils$a = utils$g; +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$a.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +tasks.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$a.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$a.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$a.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils$a.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; +} +tasks.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils$a.pattern.getPositivePatterns(patterns); +} +tasks.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$a.pattern.convertToPositivePattern); + return positive; +} +tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$a.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) + }; +} +tasks.convertPatternGroupToTask = convertPatternGroupToTask; + +var async$7 = {}; + +var async$6 = {}; + +var out$3 = {}; + +var async$5 = {}; + +var async$4 = {}; + +var out$2 = {}; + +var async$3 = {}; + +var out$1 = {}; + +var async$2 = {}; + +Object.defineProperty(async$2, "__esModule", { value: true }); +async$2.read = void 0; +function read$3(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback$2(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback$2(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback$2(callback, statError); + return; + } + callSuccessCallback$2(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback$2(callback, stat); + }); + }); +} +async$2.read = read$3; +function callFailureCallback$2(callback, error) { + callback(error); +} +function callSuccessCallback$2(callback, result) { + callback(null, result); +} + +var sync$8 = {}; + +Object.defineProperty(sync$8, "__esModule", { value: true }); +sync$8.read = void 0; +function read$2(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; + } +} +sync$8.read = read$2; + +var settings$3 = {}; + +var fs$f = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0__default; + 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; +} (fs$f)); + +Object.defineProperty(settings$3, "__esModule", { value: true }); +const fs$e = fs$f; +let Settings$2 = class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs$e.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; + } +}; +settings$3.default = Settings$2; + +Object.defineProperty(out$1, "__esModule", { value: true }); +out$1.statSync = out$1.stat = out$1.Settings = void 0; +const async$1 = async$2; +const sync$7 = sync$8; +const settings_1$3 = settings$3; +out$1.Settings = settings_1$3.default; +function stat$4(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback); + return; + } + async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); +} +out$1.stat = stat$4; +function statSync(path, optionsOrSettings) { + const settings = getSettings$2(optionsOrSettings); + return sync$7.read(path, settings); +} +out$1.statSync = statSync; +function getSettings$2(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$3.default) { + return settingsOrOptions; + } + return new settings_1$3.default(settingsOrOptions); +} + +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ + +let promise$1; + +var queueMicrotask_1 = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) + // reuse resolved promise, and allocate it lazily + : cb => (promise$1 || (promise$1 = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)); + +/*! run-parallel. MIT License. Feross Aboukhadijeh */ + +var runParallel_1 = runParallel; + +const queueMicrotask$1 = queueMicrotask_1; + +function runParallel (tasks, cb) { + let results, pending, keys; + let isSync = true; + + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + + function done (err) { + function end () { + if (cb) cb(err, results); + cb = null; + } + if (isSync) queueMicrotask$1(end); + else end(); + } + + function each (i, err, result) { + results[i] = result; + if (--pending === 0 || err) { + done(err); + } + } + + if (!pending) { + // empty + done(null); + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result); }); + }); + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result); }); + }); + } + + isSync = false; +} + +var constants$2 = {}; + +Object.defineProperty(constants$2, "__esModule", { value: true }); +constants$2.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. + */ +constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; + +var utils$9 = {}; + +var fs$d = {}; + +Object.defineProperty(fs$d, "__esModule", { value: true }); +fs$d.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); +} +fs$d.createDirentFromStats = createDirentFromStats; + +Object.defineProperty(utils$9, "__esModule", { value: true }); +utils$9.fs = void 0; +const fs$c = fs$d; +utils$9.fs = fs$c; + +var common$a = {}; + +Object.defineProperty(common$a, "__esModule", { value: true }); +common$a.joinPathSegments = void 0; +function joinPathSegments$1(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; +} +common$a.joinPathSegments = joinPathSegments$1; + +Object.defineProperty(async$3, "__esModule", { value: true }); +async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0; +const fsStat$5 = out$1; +const rpl = runParallel_1; +const constants_1$1 = constants$2; +const utils$8 = utils$9; +const common$9 = common$a; +function read$1(directory, settings, callback) { + if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes$1(directory, settings, callback); + return; + } + readdir$3(directory, settings, callback); +} +async$3.read = read$1; +function readdirWithFileTypes$1(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common$9.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback$1(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, rplEntries); + }); + }); +} +async$3.readdirWithFileTypes = readdirWithFileTypes$1; +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$8.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir$3(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common$9.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils$8.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, entries); + }); + }); +} +async$3.readdir = readdir$3; +function callFailureCallback$1(callback, error) { + callback(error); +} +function callSuccessCallback$1(callback, result) { + callback(null, result); +} + +var sync$6 = {}; + +Object.defineProperty(sync$6, "__esModule", { value: true }); +sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0; +const fsStat$4 = out$1; +const constants_1 = constants$2; +const utils$7 = utils$9; +const common$8 = common$a; +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir$2(directory, settings); +} +sync$6.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$8.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +sync$6.readdirWithFileTypes = readdirWithFileTypes; +function readdir$2(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common$8.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$7.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +sync$6.readdir = readdir$2; + +var settings$2 = {}; + +var fs$b = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0__default; + 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; +} (fs$b)); + +Object.defineProperty(settings$2, "__esModule", { value: true }); +const path$d = require$$0$4; +const fsStat$3 = out$1; +const fs$a = fs$b; +let Settings$1 = class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs$a.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat$3.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +}; +settings$2.default = Settings$1; + +Object.defineProperty(out$2, "__esModule", { value: true }); +out$2.Settings = out$2.scandirSync = out$2.scandir = void 0; +const async = async$3; +const sync$5 = sync$6; +const settings_1$2 = settings$2; +out$2.Settings = settings_1$2.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings$1(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); +} +out$2.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings$1(optionsOrSettings); + return sync$5.read(path, settings); +} +out$2.scandirSync = scandirSync; +function getSettings$1(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$2.default) { + return settingsOrOptions; + } + return new settings_1$2.default(settingsOrOptions); +} + +var queue = {exports: {}}; + +function reusify$1 (Constructor) { + var head = new Constructor(); + var tail = head; + + function get () { + var current = head; + + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + + current.next = null; + + return current + } + + function release (obj) { + tail.next = obj; + tail = obj; + } + + return { + get: get, + release: release + } +} + +var reusify_1 = reusify$1; + +/* eslint-disable no-var */ + +var reusify = reusify_1; + +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 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$4, + saturated: noop$4, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop$4, + 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; + for (var i = 0; i < self.concurrency; i++) { + _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$4; + current.errorHandler = errorHandler; + + if (_running === self.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$4; + + if (_running === self.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) { + 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$4; + } + + function killAndDrain () { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop$4; + } + + function error (handler) { + errorHandler = handler; + } +} + +function noop$4 () {} + +function Task () { + this.value = null; + this.callback = noop$4; + this.next = null; + this.release = noop$4; + 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$4; + 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$4); + + 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$4); + + return p + } + + function drained () { + var previousDrain = queue.drain; + + var p = new Promise(function (resolve) { + queue.drain = function () { + previousDrain(); + resolve(); + }; + }); + + return p + } +} + +queue.exports = fastqueue; +queue.exports.promise = queueAsPromised; + +var queueExports = queue.exports; + +var common$7 = {}; + +Object.defineProperty(common$7, "__esModule", { value: true }); +common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +common$7.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +common$7.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +common$7.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; +} +common$7.joinPathSegments = joinPathSegments; + +var reader$1 = {}; + +Object.defineProperty(reader$1, "__esModule", { value: true }); +const common$6 = common$7; +let Reader$1 = class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common$6.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +}; +reader$1.default = Reader$1; + +Object.defineProperty(async$4, "__esModule", { value: true }); +const events_1 = require$$0$5; +const fsScandir$2 = out$2; +const fastq = queueExports; +const common$5 = common$7; +const reader_1$4 = reader$1; +class AsyncReader extends reader_1$4.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir$2.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$5.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$5.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$5.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +async$4.default = AsyncReader; + +Object.defineProperty(async$5, "__esModule", { value: true }); +const async_1$4 = async$4; +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$4.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(); + } +} +async$5.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} + +var stream$2 = {}; + +Object.defineProperty(stream$2, "__esModule", { value: true }); +const stream_1$5 = require$$0$7; +const async_1$3 = async$4; +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$3.default(this._root, this._settings); + this._stream = new stream_1$5.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; + } +} +stream$2.default = StreamProvider; + +var sync$4 = {}; + +var sync$3 = {}; + +Object.defineProperty(sync$3, "__esModule", { value: true }); +const fsScandir$1 = out$2; +const common$4 = common$7; +const reader_1$3 = reader$1; +class SyncReader extends reader_1$3.default { + constructor() { + super(...arguments); + this._scandir = fsScandir$1.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$4.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common$4.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$4.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +sync$3.default = SyncReader; + +Object.defineProperty(sync$4, "__esModule", { value: true }); +const sync_1$3 = sync$3; +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1$3.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +sync$4.default = SyncProvider; + +var settings$1 = {}; + +Object.defineProperty(settings$1, "__esModule", { value: true }); +const path$c = require$$0$4; +const fsScandir = out$2; +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$c.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; + } +} +settings$1.default = Settings; + +Object.defineProperty(out$3, "__esModule", { value: true }); +out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0; +const async_1$2 = async$5; +const stream_1$4 = stream$2; +const sync_1$2 = sync$4; +const settings_1$1 = settings$1; +out$3.Settings = settings_1$1.default; +function walk$2(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +out$3.walk = walk$2; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1$2.default(directory, settings); + return provider.read(); +} +out$3.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1$4.default(directory, settings); + return provider.read(); +} +out$3.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$1.default) { + return settingsOrOptions; + } + return new settings_1$1.default(settingsOrOptions); +} + +var reader = {}; + +Object.defineProperty(reader, "__esModule", { value: true }); +const path$b = require$$0$4; +const fsStat$2 = out$1; +const utils$6 = utils$g; +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat$2.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path$b.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$6.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +reader.default = Reader; + +var stream$1 = {}; + +Object.defineProperty(stream$1, "__esModule", { value: true }); +const stream_1$3 = require$$0$7; +const fsStat$1 = out$1; +const fsWalk$2 = out$3; +const reader_1$2 = reader; +class ReaderStream extends reader_1$2.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk$2.walkStream; + this._stat = fsStat$1.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1$3.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); + }); + }); + } +} +stream$1.default = ReaderStream; + +Object.defineProperty(async$6, "__esModule", { value: true }); +const fsWalk$1 = out$3; +const reader_1$1 = reader; +const stream_1$2 = stream$1; +class ReaderAsync extends reader_1$1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk$1.walk; + this._readerStream = new stream_1$2.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)); + }); + } +} +async$6.default = ReaderAsync; + +var provider = {}; + +var deep = {}; + +var partial = {}; + +var matcher = {}; + +Object.defineProperty(matcher, "__esModule", { value: true }); +const utils$5 = utils$g; +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$5.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); + } +} +matcher.default = Matcher; + +Object.defineProperty(partial, "__esModule", { value: true }); +const matcher_1 = 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; + } +} +partial.default = PartialMatcher; + +Object.defineProperty(deep, "__esModule", { value: true }); +const utils$4 = utils$g; +const partial_1 = 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$4.pattern.isAffectDepthOfReadingPattern); + return utils$4.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$4.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$4.pattern.matchAny(entryPath, patternsRe); + } +} +deep.default = DeepFilter; + +var entry$1 = {}; + +Object.defineProperty(entry$1, "__esModule", { value: true }); +const utils$3 = utils$g; +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$3.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); + return (entry) => this._filter(entry, positiveRe, negativeRe); + } + _filter(entry, positiveRe, negativeRe) { + const filepath = utils$3.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { + return false; + } + const isDirectory = entry.dirent.isDirectory(); + const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, 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(); + } + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$3.pattern.matchAny(fullpath, patternsRe); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + // Trying to match files and directories by patterns. + const isMatched = utils$3.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$3.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; + } +} +entry$1.default = EntryFilter; + +var error$1 = {}; + +Object.defineProperty(error$1, "__esModule", { value: true }); +const utils$2 = utils$g; +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +error$1.default = ErrorFilter; + +var entry = {}; + +Object.defineProperty(entry, "__esModule", { value: true }); +const utils$1 = utils$g; +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$1.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$1.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 }); + } +} +entry.default = EntryTransformer; + +Object.defineProperty(provider, "__esModule", { value: true }); +const path$a = require$$0$4; +const deep_1 = deep; +const entry_1 = entry$1; +const error_1 = error$1; +const entry_2 = 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$a.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 + }; + } +} +provider.default = Provider; + +Object.defineProperty(async$7, "__esModule", { value: true }); +const async_1$1 = async$6; +const provider_1$2 = provider; +class ProviderAsync extends provider_1$2.default { + constructor() { + super(...arguments); + this._reader = new async_1$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); + } +} +async$7.default = ProviderAsync; + +var stream = {}; + +Object.defineProperty(stream, "__esModule", { value: true }); +const stream_1$1 = require$$0$7; +const stream_2 = stream$1; +const provider_1$1 = provider; +class ProviderStream extends provider_1$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$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); + } +} +stream.default = ProviderStream; + +var sync$2 = {}; + +var sync$1 = {}; + +Object.defineProperty(sync$1, "__esModule", { value: true }); +const fsStat = out$1; +const fsWalk = out$3; +const reader_1 = 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); + } +} +sync$1.default = ReaderSync; + +Object.defineProperty(sync$2, "__esModule", { value: true }); +const sync_1$1 = sync$1; +const provider_1 = provider; +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1$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); + } +} +sync$2.default = ProviderSync; + +var settings = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0__default; + const os = require$$2; + /** + * 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; +} (settings)); + +const taskManager = tasks; +const async_1 = async$7; +const stream_1 = stream; +const sync_1 = sync$2; +const settings_1 = settings; +const utils = utils$g; +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; + (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; + })(FastGlob.posix || (FastGlob.posix = {})); + (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; + })(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'); + } +} +var out = FastGlob; + +var glob = /*@__PURE__*/getDefaultExportFromCjs(out); + +var dist = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0; + const path = require$$0$4; + const fs = require$$0__default; + const os = require$$2; + const fsReadFileAsync = fs.promises.readFile; + function getDefaultSearchPlaces(name) { + return [ + 'package.json', + `.${name}rc.json`, + `.${name}rc.js`, + `.${name}rc.cjs`, + `.config/${name}rc`, + `.config/${name}rc.json`, + `.config/${name}rc.js`, + `.config/${name}rc.cjs`, + `${name}.config.js`, + `${name}.config.cjs`, + ]; + } + function parentDir(p) { + return path.dirname(p) || path.sep; + } + exports.defaultLoaders = Object.freeze({ + '.js': __require, + '.json': __require, + '.cjs': __require, + noExt(_, content) { + return JSON.parse(content); + }, + }); + function getExtDesc(ext) { + return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`; + } + function getOptions(name, options = {}) { + const conf = { + stopDir: os.homedir(), + searchPlaces: getDefaultSearchPlaces(name), + ignoreEmptySearchPlaces: true, + cache: true, + transform: (x) => x, + packageProp: [name], + ...options, + loaders: { ...exports.defaultLoaders, ...options.loaders }, + }; + conf.searchPlaces.forEach(place => { + const key = path.extname(place) || 'noExt'; + const loader = conf.loaders[key]; + if (!loader) { + throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`); + } + if (typeof loader !== 'function') { + throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`); + } + }); + return conf; + } + 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); + } + function validateFilePath(filepath) { + if (!filepath) + throw new Error('load must pass a non-empty string'); + } + 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'); + } + const makeEmplace = (enableCache) => (c, filepath, res) => { + if (enableCache) + c.set(filepath, res); + return res; + }; + function lilconfig(name, options) { + const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache, } = getOptions(name, options); + const searchCache = new Map(); + const loadCache = new Map(); + const emplace = makeEmplace(cache); + return { + async search(searchFrom = process.cwd()) { + const result = { + config: null, + filepath: '', + }; + 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 (_a) { + continue; + } + const content = String(await fsReadFileAsync(filepath)); + const loaderKey = path.extname(searchPlace) || 'noExt'; + const loader = loaders[loaderKey]; + 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; + } + 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 = 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, + })); + } + const result = { + config: null, + filepath: absPath, + }; + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + return emplace(loadCache, absPath, transform({ + config: undefined, + filepath: absPath, + isEmpty: true, + })); + 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(); + } + }, + }; + } + exports.lilconfig = lilconfig; + function lilconfigSync(name, options) { + const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache, } = getOptions(name, options); + const searchCache = new Map(); + const loadCache = new Map(); + const emplace = makeEmplace(cache); + return { + search(searchFrom = process.cwd()) { + const result = { + config: null, + filepath: '', + }; + 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 (_a) { + continue; + } + const loaderKey = path.extname(searchPlace) || 'noExt'; + const loader = loaders[loaderKey]; + const content = String(fs.readFileSync(filepath)); + 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; + } + 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 = 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, + }; + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + return emplace(loadCache, absPath, transform({ + filepath: absPath, + config: undefined, + isEmpty: true, + })); + 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(); + } + }, + }; + } + exports.lilconfigSync = lilconfigSync; +} (dist)); + +const ALIAS = Symbol.for('yaml.alias'); +const DOC = Symbol.for('yaml.document'); +const MAP = Symbol.for('yaml.map'); +const PAIR = Symbol.for('yaml.pair'); +const SCALAR$1 = Symbol.for('yaml.scalar'); +const SEQ = Symbol.for('yaml.seq'); +const NODE_TYPE = Symbol.for('yaml.node.type'); +const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS; +const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC; +const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP; +const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR; +const isScalar$1 = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR$1; +const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ; +function isCollection$1(node) { + if (node && typeof node === 'object') + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode$1(node) { + if (node && typeof node === 'object') + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR$1: + case SEQ: + return true; + } + return false; +} +const hasAnchor = (node) => (isScalar$1(node) || isCollection$1(node)) && !!node.anchor; + +const BREAK$1 = Symbol('break visit'); +const SKIP$1 = Symbol('skip children'); +const REMOVE$1 = Symbol('remove node'); +/** + * Apply a visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +function visit$1(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE$1) + node.contents = null; + } + else + visit_(null, node, visitor_, Object.freeze([])); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visit$1.BREAK = BREAK$1; +/** Do not visit the children of the current node */ +visit$1.SKIP = SKIP$1; +/** Remove the current node */ +visit$1.REMOVE = REMOVE$1; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode$1(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== 'symbol') { + if (isCollection$1(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node.items.splice(i, 1); + i -= 1; + } + } + } + else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_('key', node.key, visitor, path); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node.key = null; + const cv = visit_('value', node.value, visitor, path); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node.value = null; + } + } + return ctrl; +} +/** + * Apply an async visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `Promise`: Must resolve to one of the following values + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE$1) + node.contents = null; + } + else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visitAsync.BREAK = BREAK$1; +/** Do not visit the children of the current node */ +visitAsync.SKIP = SKIP$1; +/** Remove the current node */ +visitAsync.REMOVE = REMOVE$1; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode$1(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== 'symbol') { + if (isCollection$1(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node.items.splice(i, 1); + i -= 1; + } + } + } + else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_('key', node.key, visitor, path); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node.key = null; + const cv = await visitAsync_('value', node.value, visitor, path); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === 'object' && + (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === 'function') + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar$1(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return undefined; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection$1(parent)) { + parent.items[key] = node; + } + else if (isPair(parent)) { + if (key === 'key') + parent.key = node; + else + parent.value = node; + } + else if (isDocument(parent)) { + parent.contents = node; + } + else { + const pt = isAlias(parent) ? 'alias' : 'scalar'; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +const escapeChars = { + '!': '%21', + ',': '%2C', + '[': '%5B', + ']': '%5D', + '{': '%7B', + '}': '%7D' +}; +const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]); +class Directives { + constructor(yaml, tags) { + /** + * The directives-end/doc-start marker `---`. If `null`, a marker may still be + * included in the document's stringified representation. + */ + this.docStart = null; + /** The doc-end marker `...`. */ + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case '1.1': + this.atNextDocument = true; + break; + case '1.2': + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: '1.2' + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case '%TAG': { + if (parts.length !== 2) { + onError(0, '%TAG directive should contain exactly two parts'); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case '%YAML': { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, '%YAML directive should contain exactly one part'); + return false; + } + const [version] = parts; + if (version === '1.1' || version === '1.2') { + this.yaml.version = version; + return true; + } + else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === '!') + return '!'; // non-specific tag + if (source[0] !== '!') { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === '<') { + const verbatim = source.slice(2, -1); + if (verbatim === '!' || verbatim === '!!') { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== '>') + onError('Verbatim tags must end with a >'); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } + catch (error) { + onError(String(error)); + return null; + } + } + if (handle === '!') + return source; // local tag + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === '!' ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit + ? [`%YAML ${this.yaml.version || '1.2'}`] + : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode$1(doc.contents)) { + const tags = {}; + visit$1(doc.contents, (_key, node) => { + if (isNode$1(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } + else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === '!!' && prefix === 'tag:yaml.org,2002:') + continue; + if (!doc || tagNames.some(tn => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join('\n'); + } +} +Directives.defaultYaml = { explicit: false, version: '1.2' }; +Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' }; + +/** + * Verify that the input string is a valid anchor. + * + * Will throw on errors. + */ +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = new Set(); + visit$1(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */ +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + if (!prevAnchors) + prevAnchors = anchorNames(doc); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === 'object' && + ref.anchor && + (isScalar$1(ref.node) || isCollection$1(ref.node))) { + ref.node.anchor = ref.anchor; + } + else { + const error = new Error('Failed to resolve repeated object (this should not happen)'); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +/** + * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec, + * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the + * 2021 edition: https://tc39.es/ecma262/#sec-json.parse + * + * Includes extensions for handling Map and Set objects. + */ +function applyReviver(reviver, obj, key, val) { + if (val && typeof val === 'object') { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === undefined) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } + else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } + else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === undefined) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } + else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key, val); +} + +/** + * Recursively convert any node or its contents to native JavaScript + * + * @param value - The input value + * @param arg - If `value` defines a `toJSON()` method, use this + * as its first argument + * @param ctx - Conversion context, originally set in Document#toJS(). If + * `{ keep: true }` is not set, output should be suitable for JSON + * stringification. + */ +function toJS(value, arg, ctx) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + if (!ctx || !hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: undefined }; + ctx.anchors.set(value, data); + ctx.onCreate = res => { + data.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === 'bigint' && !ctx?.keep) + return Number(value); + return value; +} + +class NodeBase { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError('A document argument is required'); + const ctx = { + anchors: new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100 + }; + const res = toJS(this, '', ctx); + if (typeof onAnchor === 'function') + for (const { count, res } of ctx.anchors.values()) + onAnchor(res, count); + return typeof reviver === 'function' + ? applyReviver(reviver, { '': res }, '', res) + : res; + } +} + +class Alias extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, 'tag', { + set() { + throw new Error('Alias nodes cannot have tags'); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc) { + let found = undefined; + visit$1(doc, { + Node: (_key, node) => { + if (node === this) + return visit$1.BREAK; + if (node.anchor === this.source) + found = node; + } + }); + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + // Resolve anchors for Node.prototype.toJS() + toJS(source, null, ctx); + data = anchors.get(source); + } + /* istanbul ignore if */ + if (!data || data.res === undefined) { + const msg = 'This should not happen: Alias anchor was not resolved?'; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = 'Excessive alias count indicates a resource exhaustion attack'; + throw new ReferenceError(msg); + } + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +} +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } + else if (isCollection$1(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } + else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object'); +class Scalar extends NodeBase { + constructor(value) { + super(SCALAR$1); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +} +Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED'; +Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL'; +Scalar.PLAIN = 'PLAIN'; +Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE'; +Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE'; + +const defaultTagPrefix = 'tag:yaml.org,2002:'; +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter(t => t.tag === tagName); + const tagObj = match.find(t => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find(t => t.identify?.(value) && !t.format); +} +function createNode(value, tagName, ctx) { + if (isDocument(value)) + value = value.contents; + if (isNode$1(value)) + return value; + if (isPair(value)) { + const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map.items.push(value); + return map; + } + if (value instanceof String || + value instanceof Number || + value instanceof Boolean || + (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere + ) { + // https://tc39.es/ecma262/#sec-serializejsonproperty + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + // Detect duplicate references to the same object & use Alias nodes for all + // after first. The `ref` wrapper allows for circular references to resolve. + let ref = undefined; + if (aliasDuplicateObjects && value && typeof value === 'object') { + ref = sourceObjects.get(value); + if (ref) { + if (!ref.anchor) + ref.anchor = onAnchor(value); + return new Alias(ref.anchor); + } + else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith('!!')) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + value = value.toJSON(); + } + if (!value || typeof value !== 'object') { + const node = new Scalar(value); + if (ref) + ref.node = node; + return node; + } + tagObj = + value instanceof Map + ? schema[MAP] + : Symbol.iterator in Object(value) + ? schema[SEQ] + : schema[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode + ? tagObj.createNode(ctx.schema, value, ctx) + : typeof tagObj?.nodeClass?.from === 'function' + ? tagObj.nodeClass.from(ctx.schema, value, ctx) + : new Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === 'number' && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } + else { + v = new Map([[k, v]]); + } + } + return createNode(v, undefined, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error('This should not happen, please report a bug.'); + }, + schema, + sourceObjects: new Map() + }); +} +// Type guard is intentionally a little wrong so as to be more useful, +// as it does not cover untypable empty non-string iterables (e.g. []). +const isEmptyPath = (path) => path == null || + (typeof path === 'object' && !!path[Symbol.iterator]().next().done); +class Collection extends NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, 'schema', { + value: schema, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) + copy.schema = schema; + copy.items = copy.items.map(it => isNode$1(it) || isPair(it) ? it.clone(schema) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection$1(node)) + node.addIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection$1(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar$1(node) ? node.value : node; + else + return isCollection$1(node) ? node.getIn(rest, keepScalar) : undefined; + } + hasAllNullValues(allowScalar) { + return this.items.every(node => { + if (!isPair(node)) + return false; + const n = node.value; + return (n == null || + (allowScalar && + isScalar$1(n) && + n.value == null && + !n.commentBefore && + !n.comment && + !n.tag)); + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection$1(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } + else { + const node = this.get(key, true); + if (isCollection$1(node)) + node.setIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +} +Collection.maxFlowStringSingleLineLength = 60; + +/** + * Stringifies a comment. + * + * Empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ +const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#'); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +const lineComment = (str, indent, comment) => str.endsWith('\n') + ? indentComment(comment, indent) + : comment.includes('\n') + ? '\n' + indentComment(comment, indent) + : (str.endsWith(' ') ? '' : ' ') + comment; + +const FOLD_FLOW = 'flow'; +const FOLD_BLOCK = 'block'; +const FOLD_QUOTED = 'quoted'; +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + */ +function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === 'number') { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i); + if (i !== -1) + end = i + endStep; + } + for (let ch; (ch = text[(i += 1)]);) { + if (mode === FOLD_QUOTED && ch === '\\') { + escStart = i; + switch (text[i + 1]) { + case 'x': + i += 3; + break; + case 'u': + i += 5; + break; + case 'U': + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === '\n') { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i); + end = i + endStep; + split = undefined; + } + else { + if (ch === ' ' && + prev && + prev !== ' ' && + prev !== '\n' && + prev !== '\t') { + // space surrounded by non-space can be replaced with newline + indent + const next = text[i + 1]; + if (next && next !== ' ' && next !== '\n' && next !== '\t') + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } + else if (mode === FOLD_QUOTED) { + // white-space collected at end may stretch past lineWidth + while (prev === ' ' || prev === '\t') { + prev = ch; + ch = text[(i += 1)]; + overflow = true; + } + // Account for newline escape, but don't break preceding escape + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + // Bail out if lineWidth & minContentWidth are shorter than an escape string + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } + else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) + res = `\n${indent}${text.slice(0, end)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + return res; +} +/** + * Presumes `i + 1` is at the start of a line + * @returns index of last newline in more-indented block + */ +function consumeMoreIndentedLines(text, i) { + let ch = text[i + 1]; + while (ch === ' ' || ch === '\t') { + do { + ch = text[(i += 1)]; + } while (ch && ch !== '\n'); + ch = text[i + 1]; + } + return i; +} + +const getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +// Also checks for lines starting with %, as parsing the output as YAML 1.1 will +// presume that's starting a new document. +const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === '\n') { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + let str = ''; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { + // space before newline needs to be escaped to not be folded + str += json.slice(start, i) + '\\ '; + i += 1; + start = i; + ch = '\\'; + } + if (ch === '\\') + switch (json[i + 1]) { + case 'u': + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case '0000': + str += '\\0'; + break; + case '0007': + str += '\\a'; + break; + case '000b': + str += '\\v'; + break; + case '001b': + str += '\\e'; + break; + case '0085': + str += '\\N'; + break; + case '00a0': + str += '\\_'; + break; + case '2028': + str += '\\L'; + break; + case '2029': + str += '\\P'; + break; + default: + if (code.substr(0, 2) === '00') + str += '\\x' + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case 'n': + if (implicitKey || + json[i + 2] === '"' || + json.length < minMultiLineLength) { + i += 1; + } + else { + // folding will eat first newline + str += json.slice(start, i) + '\n\n'; + while (json[i + 2] === '\\' && + json[i + 3] === 'n' && + json[i + 4] !== '"') { + str += '\n'; + i += 2; + } + str += indent; + // space after newline needs to be escaped to not be folded + if (json[i + 2] === ' ') + str += '\\'; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey + ? str + : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || + (ctx.implicitKey && value.includes('\n')) || + /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline + ) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey + ? res + : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +// The negative lookbehind avoids a polynomial search, +// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind +let blockEndNewlines; +try { + blockEndNewlines = new RegExp('(^|(?\n'; + // determine chomping from whitespace at value end + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== '\n' && ch !== '\t' && ch !== ' ') + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf('\n'); + if (endNlPos === -1) { + chomp = '-'; // strip + } + else if (value === end || endNlPos !== end.length - 1) { + chomp = '+'; // keep + if (onChompKeep) + onChompKeep(); + } + else { + chomp = ''; // clip + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === '\n') + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + // determine indent indicator from whitespace at value start + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === ' ') + startWithSpace = true; + else if (ch === '\n') + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? '2' : '1'; // root is at -1 + let header = (literal ? '|' : '>') + (startWithSpace ? indentSize : '') + chomp; + if (comment) { + header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' ')); + if (onComment) + onComment(); + } + if (literal) { + value = value.replace(/\n+/g, `$&${indent}`); + return `${header}\n${indent}${start}${value}${end}`; + } + value = value + .replace(/\n+/g, '\n$&') + .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded + // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent + .replace(/\n+/g, `$&${indent}`); + const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true)); + return `${header}\n${indent}${body}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if ((implicitKey && value.includes('\n')) || + (inFlow && /[[\]{},]/.test(value))) { + return quotedString(value, ctx); + } + if (!value || + /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + // not allowed: + // - empty string, '-' or '?' + // - start with an indicator character (except [?:-]) or /[?-] / + // - '\n ', ': ' or ' \n' anywhere + // - '#' not preceded by a non-space char + // - end with ' ' or ':' + return implicitKey || inFlow || !value.includes('\n') + ? quotedString(value, ctx) + : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && + !inFlow && + type !== Scalar.PLAIN && + value.includes('\n')) { + // Where allowed & type not set explicitly, prefer block style for multiline strings + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === '') { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } + else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$&\n${indent}`); + // Verify that output will be parsed as a string, as e.g. plain numbers and + // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), + // and others in v1.1. + if (actualString) { + const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey + ? str + : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === 'string' + ? item + : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + // force double quotes on control characters & unpaired surrogates + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow + ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers + : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = (implicitKey && defaultKeyType) || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: 'PLAIN', + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: 'false', + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: 'null', + simpleKeys: false, + singleQuote: null, + trueStr: 'true', + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case 'block': + inFlow = false; + break; + case 'flow': + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '', + indent: '', + indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ', + inFlow, + options: opt + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter(t => t.tag === item.tag); + if (match.length > 0) + return match.find(t => t.format === item.format) ?? match[0]; + } + let tagObj = undefined; + let obj; + if (isScalar$1(item)) { + obj = item.value; + const match = tags.filter(t => t.identify?.(obj)); + tagObj = + match.find(t => t.format === item.format) ?? match.find(t => !t.format); + } + else { + obj = item; + tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? typeof obj; + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +// needs to be called before value stringifier to allow for circular anchor refs +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ''; + const props = []; + const anchor = (isScalar$1(node) || isCollection$1(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag; + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(' '); +} +function stringify$2(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } + else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = undefined; + const node = isNode$1(item) + ? item + : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) }); + if (!tagObj) + tagObj = getTagObject(ctx.doc.schema.tags, node); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === 'function' + ? tagObj.stringify(node, ctx, onComment, onChompKeep) + : isScalar$1(node) + ? stringifyString(node, ctx, onComment, onChompKeep) + : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return isScalar$1(node) || str[0] === '{' || str[0] === '[' + ? `${props} ${str}` + : `${props}\n${ctx.indent}${str}`; +} + +function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = (isNode$1(key) && key.comment) || null; + if (simpleKeys) { + if (keyComment) { + throw new Error('With simple keys, key nodes cannot have comments'); + } + if (isCollection$1(key)) { + const msg = 'With simple keys, collection cannot be used as a key value'; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && + (!key || + (keyComment && value == null && !ctx.inFlow) || + isCollection$1(key) || + (isScalar$1(key) + ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL + : typeof key === 'object')); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify$2(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true)); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === '' ? '?' : explicitKey ? `? ${str}` : str; + } + } + else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str}\n${indent}:`; + } + else { + str = `${str}:`; + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode$1(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } + else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === 'object') + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar$1(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && + indentStep.length >= 2 && + !ctx.inFlow && + !explicitKey && + isSeq(value) && + !value.flow && + !value.tag && + !value.anchor) { + // If indentSeq === false, consider '- ' as part of indentation where possible + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify$2(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true)); + let ws = ' '; + if (keyComment || vsb || vcb) { + ws = vsb ? '\n' : ''; + if (vcb) { + const cs = commentString(vcb); + ws += `\n${indentComment(cs, ctx.indent)}`; + } + if (valueStr === '' && !ctx.inFlow) { + if (ws === '\n') + ws = '\n\n'; + } + else { + ws += `\n${ctx.indent}`; + } + } + else if (!explicitKey && isCollection$1(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf('\n'); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === '&' || vs0 === '!')) { + let sp0 = valueStr.indexOf(' '); + if (vs0 === '&' && + sp0 !== -1 && + sp0 < nl0 && + valueStr[sp0 + 1] === '!') { + sp0 = valueStr.indexOf(' ', sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = `\n${ctx.indent}`; + } + } + else if (valueStr === '' || valueStr[0] === '\n') { + ws = ''; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } + else if (valueComment && !valueCommentDone) { + str += lineComment(str, ctx.indent, commentString(valueComment)); + } + else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; +} + +function warn(logLevel, warning) { + if (logLevel === 'debug' || logLevel === 'warn') { + // https://github.com/typescript-eslint/typescript-eslint/issues/7478 + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (typeof process !== 'undefined' && process.emitWarning) + process.emitWarning(warning); + else + console.warn(warning); + } +} + +const MERGE_KEY = '<<'; +function addPairToJSMap(ctx, map, { key, value }) { + if (ctx?.doc.schema.merge && isMergeKey(key)) { + value = isAlias(value) ? value.resolve(ctx.doc) : value; + if (isSeq(value)) + for (const it of value.items) + mergeToJSMap(ctx, map, it); + else if (Array.isArray(value)) + for (const it of value) + mergeToJSMap(ctx, map, it); + else + mergeToJSMap(ctx, map, value); + } + else { + const jsKey = toJS(key, '', ctx); + if (map instanceof Map) { + map.set(jsKey, toJS(value, jsKey, ctx)); + } + else if (map instanceof Set) { + map.add(jsKey); + } + else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value, stringKey, ctx); + if (stringKey in map) + Object.defineProperty(map, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map[stringKey] = jsValue; + } + } + return map; +} +const isMergeKey = (key) => key === MERGE_KEY || + (isScalar$1(key) && + key.value === MERGE_KEY && + (!key.type || key.type === Scalar.PLAIN)); +// If the value associated with a merge key is a single mapping node, each of +// its key/value pairs is inserted into the current mapping, unless the key +// already exists in it. If the value associated with the merge key is a +// sequence, then this sequence is expected to contain mapping nodes and each +// of these nodes is merged in turn according to its order in the sequence. +// Keys in mapping nodes earlier in the sequence override keys specified in +// later mapping nodes. -- http://yaml.org/type/merge.html +function mergeToJSMap(ctx, map, value) { + const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (!isMap(source)) + throw new Error('Merge sources must be maps or map aliases'); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) + map.set(key, value); + } + else if (map instanceof Set) { + map.add(key); + } + else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ''; + if (typeof jsKey !== 'object') + return String(jsKey); + if (isNode$1(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +function createPair(key, value, ctx) { + const k = createNode(key, undefined, ctx); + const v = createNode(value, undefined, ctx); + return new Pair(k, v); +} +class Pair { + constructor(key, value = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value; + } + clone(schema) { + let { key, value } = this; + if (isNode$1(key)) + key = key.clone(schema); + if (isNode$1(value)) + value = value.clone(schema); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc + ? stringifyPair(this, ctx, onComment, onChompKeep) + : JSON.stringify(this); + } +} + +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; // flag for the preceding node's status + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode$1(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment = item.comment; + } + else if (isPair(item)) { + const ik = isNode$1(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str = stringify$2(item, itemCtx, () => (comment = null), () => (chompKeep = true)); + if (comment) + str += lineComment(str, itemIndent, commentString(comment)); + if (chompKeep && comment) + chompKeep = false; + lines.push(blockItemPrefix + str); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } + else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? `\n${indent}${line}` : '\n'; + } + } + if (comment) { + str += '\n' + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } + else if (chompKeep && onChompKeep) + onChompKeep(); + return str; +} +function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode$1(item)) { + if (item.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } + else if (isPair(item)) { + const ik = isNode$1(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(''); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode$1(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } + else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify$2(item, itemCtx, () => (comment = null)); + if (i < items.length - 1) + str += ','; + if (comment) + str += lineComment(str, itemIndent, commentString(comment)); + if (!reqNewline && (lines.length > linesAtValue || str.includes('\n'))) + reqNewline = true; + lines.push(str); + linesAtValue = lines.length; + } + let str; + const { start, end } = flowChars; + if (lines.length === 0) { + str = start + end; + } + else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = len > Collection.maxFlowStringSingleLineLength; + } + if (reqNewline) { + str = start; + for (const line of lines) + str += line ? `\n${indentStep}${indent}${line}` : '\n'; + str += `\n${indent}${end}`; + } + else { + str = `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`; + } + } + if (comment) { + str += lineComment(str, indent, commentString(comment)); + if (onComment) + onComment(); + } + return str; +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ''); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); // Avoid double indent on first line + } +} + +function findPair(items, key) { + const k = isScalar$1(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar$1(it.key) && it.key.value === k) + return it; + } + } + return undefined; +} +class YAMLMap extends Collection { + static get tagName() { + return 'tag:yaml.org,2002:map'; + } + constructor(schema) { + super(MAP, schema); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map = new this(schema); + const add = (key, value) => { + if (typeof replacer === 'function') + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== undefined || keepUndefined) + map.items.push(createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } + else if (obj && typeof obj === 'object') { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema.sortMapEntries === 'function') { + map.items.sort(schema.sortMapEntries); + } + return map; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== 'object' || !('key' in pair)) { + // In TypeScript, this never happens. + _pair = new Pair(pair, pair?.value); + } + else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + // For scalars, keep the old node & its comments and anchors + if (isScalar$1(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } + else if (sortEntries) { + const i = this.items.findIndex(item => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } + else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar$1(node) ? node.value : node) ?? undefined; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map); + for (const item of this.items) + addPairToJSMap(ctx, map, item); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: '', + flowChars: { start: '{', end: '}' }, + itemIndent: ctx.indent || '', + onChompKeep, + onComment + }); + } +} + +const map$1 = { + collection: 'map', + default: true, + nodeClass: YAMLMap, + tag: 'tag:yaml.org,2002:map', + resolve(map, onError) { + if (!isMap(map)) + onError('Expected a mapping for this tag'); + return map; + }, + createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx) +}; + +class YAMLSeq extends Collection { + static get tagName() { + return 'tag:yaml.org,2002:seq'; + } + constructor(schema) { + super(SEQ, schema); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + return undefined; + const it = this.items[idx]; + return !keepScalar && isScalar$1(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === 'number' && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar$1(prev) && isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) + ctx.onCreate(seq); + let i = 0; + for (const item of this.items) + seq.push(toJS(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: '- ', + flowChars: { start: '[', end: ']' }, + itemIndent: (ctx.indent || '') + ' ', + onChompKeep, + onComment + }); + } + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === 'function') { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode(it, undefined, ctx)); + } + } + return seq; + } +} +function asItemIndex(key) { + let idx = isScalar$1(key) ? key.value : key; + if (idx && typeof idx === 'string') + idx = Number(idx); + return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0 + ? idx + : null; +} + +const seq = { + collection: 'seq', + default: true, + nodeClass: YAMLSeq, + tag: 'tag:yaml.org,2002:seq', + resolve(seq, onError) { + if (!isSeq(seq)) + onError('Expected a sequence for this tag'); + return seq; + }, + createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx) +}; + +const string = { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: str => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +const nullTag = { + identify: value => value == null, + createNode: () => new Scalar(null), + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source) + ? source + : ctx.options.nullStr +}; + +const boolTag = { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === 't' || source[0] === 'T'; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === 'bigint') + return String(value); + const num = typeof value === 'number' ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf'; + let n = JSON.stringify(value); + if (!format && + minFractionDigits && + (!tag || tag === 'tag:yaml.org,2002:float') && + /^\d/.test(n)) { + let i = n.indexOf('.'); + if (i < 0) { + i = n.length; + n += '.'; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += '0'; + } + return n; +} + +const floatNaN$1 = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN))$/, + resolve: str => str.slice(-3).toLowerCase() === 'nan' + ? NaN + : str[0] === '-' + ? Number.NEGATIVE_INFINITY + : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp$1 = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } +}; +const float$1 = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar(parseFloat(str)); + const dot = str.indexOf('.'); + if (dot !== -1 && str[str.length - 1] === '0') + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +const intIdentify$2 = (value) => typeof value === 'bigint' || Number.isInteger(value); +const intResolve$1 = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix)); +function intStringify$1(node, radix, prefix) { + const { value } = node; + if (intIdentify$2(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber(node); +} +const intOct$1 = { + identify: value => intIdentify$2(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt), + stringify: node => intStringify$1(node, 8, '0o') +}; +const int$1 = { + identify: intIdentify$2, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex$1 = { + identify: value => intIdentify$2(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt), + stringify: node => intStringify$1(node, 16, '0x') +}; + +const schema$2 = [ + map$1, + seq, + string, + nullTag, + boolTag, + intOct$1, + int$1, + intHex$1, + floatNaN$1, + floatExp$1, + float$1 +]; + +function intIdentify$1(value) { + return typeof value === 'bigint' || Number.isInteger(value); +} +const stringifyJSON = ({ value }) => JSON.stringify(value); +const jsonScalars = [ + { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: str => str, + stringify: stringifyJSON + }, + { + identify: value => value == null, + createNode: () => new Scalar(null), + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^true|false$/, + resolve: str => str === 'true', + stringify: stringifyJSON + }, + { + identify: intIdentify$1, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: str => parseFloat(str), + stringify: stringifyJSON + } +]; +const jsonError = { + default: true, + tag: '', + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } +}; +const schema$1 = [map$1, seq].concat(jsonScalars, jsonError); + +const binary = { + identify: value => value instanceof Uint8Array, + default: false, + tag: 'tag:yaml.org,2002:binary', + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof Buffer === 'function') { + return Buffer.from(src, 'base64'); + } + else if (typeof atob === 'function') { + // On IE 11, atob() can't handle newlines + const str = atob(src.replace(/[\n\r]/g, '')); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } + else { + onError('This environment does not support reading binary tags; either Buffer or atob is required'); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + const buf = value; // checked earlier by binary.identify() + let str; + if (typeof Buffer === 'function') { + str = + buf instanceof Buffer + ? buf.toString('base64') + : Buffer.from(buf.buffer).toString('base64'); + } + else if (typeof btoa === 'function') { + let s = ''; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } + else { + throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); + } + if (!type) + type = Scalar.BLOCK_LITERAL; + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' '); + } + return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } +}; + +function resolvePairs(seq, onError) { + if (isSeq(seq)) { + for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError('Each pair must have its own sequence indicator'); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore + ? `${item.commentBefore}\n${pair.key.commentBefore}` + : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment + ? `${item.comment}\n${cn.comment}` + : item.comment; + } + item = pair; + } + seq.items[i] = isPair(item) ? item : new Pair(item); + } + } + else + onError('Expected a sequence for this tag'); + return seq; +} +function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs = new YAMLSeq(schema); + pairs.tag = 'tag:yaml.org,2002:pairs'; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === 'function') + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } + else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } + else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } + else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } + else { + key = it; + } + pairs.items.push(createPair(key, value, ctx)); + } + return pairs; +} +const pairs = { + collection: 'seq', + default: false, + tag: 'tag:yaml.org,2002:pairs', + resolve: resolvePairs, + createNode: createPairs +}; + +class YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map = new Map(); + if (ctx?.onCreate) + ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (isPair(pair)) { + key = toJS(pair.key, '', ctx); + value = toJS(pair.value, key, ctx); + } + else { + key = toJS(pair, '', ctx); + } + if (map.has(key)) + throw new Error('Ordered maps must not include duplicate keys'); + map.set(key, value); + } + return map; + } + static from(schema, iterable, ctx) { + const pairs = createPairs(schema, iterable, ctx); + const omap = new this(); + omap.items = pairs.items; + return omap; + } +} +YAMLOMap.tag = 'tag:yaml.org,2002:omap'; +const omap = { + collection: 'seq', + identify: value => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: 'tag:yaml.org,2002:omap', + resolve(seq, onError) { + const pairs = resolvePairs(seq, onError); + const seenKeys = []; + for (const { key } of pairs.items) { + if (isScalar$1(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } + else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) +}; + +function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; +} +const trueTag = { + identify: value => value === true, + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +const falseTag = { + identify: value => value === false, + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +const floatNaN = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === 'nan' + ? NaN + : str[0] === '-' + ? Number.NEGATIVE_INFINITY + : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, '')), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } +}; +const float = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar(parseFloat(str.replace(/_/g, ''))); + const dot = str.indexOf('.'); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ''); + if (f[f.length - 1] === '0') + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value); +function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === '-' || sign === '+') + offset += 1; + str = str.substring(offset).replace(/_/g, ''); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n = BigInt(str); + return sign === '-' ? BigInt(-1) * n : n; + } + const n = parseInt(str, radix); + return sign === '-' ? -1 * n : n; +} +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber(node); +} +const intBin = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'BIN', + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: node => intStringify(node, 2, '0b') +}; +const intOct = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: node => intStringify(node, 8, '0') +}; +const int = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex = { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: node => intStringify(node, 16, '0x') +}; + +class YAMLSet extends YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && + typeof key === 'object' && + 'key' in key && + 'value' in key && + key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) + ? isScalar$1(pair.key) + ? pair.key.value + : pair.key + : pair; + } + set(key, value) { + if (typeof value !== 'boolean') + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } + else if (!prev && value) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error('Set items must all have null values'); + } + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === 'function') + value = replacer.call(iterable, value, value); + set.items.push(createPair(value, null, ctx)); + } + return set; + } +} +YAMLSet.tag = 'tag:yaml.org,2002:set'; +const set = { + collection: 'map', + identify: value => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: 'tag:yaml.org,2002:set', + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map, onError) { + if (isMap(map)) { + if (map.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map); + else + onError('Set items must all have null values'); + } + else + onError('Expected a mapping for this tag'); + return map; + } +}; + +/** Internal types handle bigint as number, because TS can't figure it out. */ +function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === '-' || sign === '+' ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts + .replace(/_/g, '') + .split(':') + .reduce((res, p) => res * num(60) + num(p), num(0)); + return (sign === '-' ? num(-1) * res : res); +} +/** + * hhhh:mm:ss.sss + * + * Internal types handle bigint as number, because TS can't figure it out. + */ +function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === 'bigint') + num = n => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber(node); + let sign = ''; + if (value < 0) { + sign = '-'; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; // seconds, including ms + if (value < 60) { + parts.unshift(0); // at least one : is required + } + else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); // minutes + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); // hours + } + } + return (sign + + parts + .map(n => String(n).padStart(2, '0')) + .join(':') + .replace(/000000\d*$/, '') // % 60 may introduce error + ); +} +const intTime = { + identify: value => typeof value === 'bigint' || Number.isInteger(value), + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'TIME', + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'TIME', + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: str => parseSexagesimal(str, false), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: value => value instanceof Date, + default: true, + tag: 'tag:yaml.org,2002:timestamp', + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd + '(?:' + // time is optional + '(?:t|T|[ \\t]+)' + // t | T | whitespace + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? + '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 + ')?$'), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd'); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== 'Z') { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 60000 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') +}; + +const schema = [ + map$1, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct, + int, + intHex, + floatNaN, + floatExp, + float, + binary, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +const schemas = new Map([ + ['core', schema$2], + ['failsafe', [map$1, seq, string]], + ['json', schema$1], + ['yaml11', schema], + ['yaml-1.1', schema] +]); +const tagsByName = { + binary, + bool: boolTag, + float: float$1, + floatExp: floatExp$1, + floatNaN: floatNaN$1, + floatTime, + int: int$1, + intHex: intHex$1, + intOct: intOct$1, + intTime, + map: map$1, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +const coreKnownTags = { + 'tag:yaml.org,2002:binary': binary, + 'tag:yaml.org,2002:omap': omap, + 'tag:yaml.org,2002:pairs': pairs, + 'tag:yaml.org,2002:set': set, + 'tag:yaml.org,2002:timestamp': timestamp +}; +function getTags(customTags, schemaName) { + let tags = schemas.get(schemaName); + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()) + .filter(key => key !== 'yaml11') + .map(key => JSON.stringify(key)) + .join(', '); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } + else if (typeof customTags === 'function') { + tags = customTags(tags.slice()); + } + return tags.map(tag => { + if (typeof tag !== 'string') + return tag; + const tagObj = tagsByName[tag]; + if (tagObj) + return tagObj; + const keys = Object.keys(tagsByName) + .map(key => JSON.stringify(key)) + .join(', '); + throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); + }); +} + +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +class Schema { + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) + ? getTags(compat, 'compat') + : compat + ? getTags(null, compat) + : null; + this.merge = !!merge; + this.name = (typeof schema === 'string' && schema) || 'core'; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map$1 }); + Object.defineProperty(this, SCALAR$1, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + // Used by createMap() + this.sortMapEntries = + typeof sortMapEntries === 'function' + ? sortMapEntries + : sortMapEntries === true + ? sortMapEntriesByKey + : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } +} + +function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } + else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push('---'); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(''); + const cs = commentString(doc.commentBefore); + lines.unshift(indentComment(cs, '')); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode$1(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(''); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(indentComment(cs, '')); + } + // top-level block scalars need to be indented if followed by a comment + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? undefined : () => (chompKeep = true); + let body = stringify$2(doc.contents, ctx, () => (contentComment = null), onChompKeep); + if (contentComment) + body += lineComment(body, '', commentString(contentComment)); + if ((body[0] === '|' || body[0] === '>') && + lines[lines.length - 1] === '---') { + // Top-level block scalars with a preceding doc marker ought to use the + // same line for their header. + lines[lines.length - 1] = `--- ${body}`; + } + else + lines.push(body); + } + else { + lines.push(stringify$2(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes('\n')) { + lines.push('...'); + lines.push(indentComment(cs, '')); + } + else { + lines.push(`... ${cs}`); + } + } + else { + lines.push('...'); + } + } + else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ''); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') + lines.push(''); + lines.push(indentComment(commentString(dc), '')); + } + } + return lines.join('\n') + '\n'; +} + +class Document { + constructor(value, replacer, options) { + /** A comment before this Document */ + this.commentBefore = null; + /** A comment immediately after this Document */ + this.comment = null; + /** Errors encountered during parsing. */ + this.errors = []; + /** Warnings encountered during parsing. */ + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === 'function' || Array.isArray(replacer)) { + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: 'warn', + prettyErrors: true, + strict: true, + uniqueKeys: true, + version: '1.2' + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } + else + this.directives = new Directives({ version }); + this.setSchema(version, options); + // @ts-expect-error We can't really know that this matches Contents. + this.contents = + value === undefined ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + // @ts-expect-error We can't really know that this matches Contents. + copy.contents = isNode$1(this.contents) + ? this.contents.clone(copy.schema) + : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name; + } + return new Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = undefined; + if (typeof replacer === 'function') { + value = replacer.call({ '': value }, '', value); + _replacer = replacer; + } + else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || 'a'); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode(value, tag, ctx); + if (flow && isCollection$1(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + // @ts-expect-error Presumed impossible if Strict extends false + this.contents = null; + return true; + } + return assertCollection(this.contents) + ? this.contents.deleteIn(path) + : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection$1(this.contents) + ? this.contents.get(key, keepScalar) + : undefined; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar$1(this.contents) + ? this.contents.value + : this.contents; + return isCollection$1(this.contents) + ? this.contents.getIn(path, keepScalar) + : undefined; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection$1(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== undefined; + return isCollection$1(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = collectionFromPath(this.schema, [key], value); + } + else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (isEmptyPath(path)) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = value; + } + else if (this.contents == null) { + // @ts-expect-error We can't really know that this matches Contents. + this.contents = collectionFromPath(this.schema, Array.from(path), value); + } + else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === 'number') + version = String(version); + let opt; + switch (version) { + case '1.1': + if (this.directives) + this.directives.yaml.version = '1.1'; + else + this.directives = new Directives({ version: '1.1' }); + opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' }; + break; + case '1.2': + case 'next': + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt = { merge: false, resolveKnownTags: true, schema: 'core' }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + // Not using `instanceof Schema` to allow for duck typing + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? '', ctx); + if (typeof onAnchor === 'function') + for (const { count, res } of ctx.anchors.values()) + onAnchor(res, count); + return typeof reviver === 'function' + ? applyReviver(reviver, { '': res }, '', res) + : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error('Document with errors cannot be stringified'); + if ('indent' in options && + (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +} +function assertCollection(contents) { + if (isCollection$1(contents)) + return true; + throw new Error('Expected a YAML collection as document contents'); +} + +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +} +class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super('YAMLParseError', pos, code, message); + } +} +class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super('YAMLWarning', pos, code, message); + } +} +const prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map(pos => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src + .substring(lc.lineStarts[line - 1], lc.lineStarts[line]) + .replace(/[\n\r]+$/, ''); + // Trim to max 80 chars, keeping col position near the middle + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = '…' + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + '…'; + // Include previous line in context if pointing at line start + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + // Regexp won't match if start is trimmed + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + '…\n'; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end && end.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = ' '.repeat(ci) + '^'.repeat(count); + error.message += `:\n\n${lineStr}\n${pointer}\n`; + } +}; + +function resolveProps(tokens, { flow, indicator, next, offset, onError, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ''; + let commentSep = ''; + let hasNewline = false; + let hasNewlineAfterProp = false; + let reqSpace = false; + let anchor = null; + let tag = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== 'space' && + token.type !== 'newline' && + token.type !== 'comma') + onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space'); + reqSpace = false; + } + switch (token.type) { + case 'space': + // At the doc level, tabs at line start may be parsed + // as leading white space rather than indentation. + // In a flow collection, only the parser handles indent. + if (!flow && + atNewline && + indicator !== 'doc-start' && + token.source[0] === '\t') + onError(token, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation'); + hasSpace = true; + break; + case 'comment': { + if (!hasSpace) + onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters'); + const cb = token.source.substring(1) || ' '; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ''; + atNewline = false; + break; + } + case 'newline': + if (atNewline) { + if (comment) + comment += token.source; + else + spaceBefore = true; + } + else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + hasNewlineAfterProp = true; + hasSpace = true; + break; + case 'anchor': + if (anchor) + onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor'); + if (token.source.endsWith(':')) + onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true); + anchor = token; + if (start === null) + start = token.offset; + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case 'tag': { + if (tag) + onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag'); + tag = token; + if (start === null) + start = token.offset; + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + // Could here handle preceding comments differently + if (anchor || tag) + onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`); + found = token; + atNewline = false; + hasSpace = false; + break; + case 'comma': + if (flow) { + if (comma) + onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && + next && + next.type !== 'space' && + next.type !== 'newline' && + next.type !== 'comma' && + (next.type !== 'scalar' || next.source !== '')) + onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space'); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + hasNewlineAfterProp, + anchor, + tag, + end, + start: start ?? end + }; +} + +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case 'alias': + case 'scalar': + case 'double-quoted-scalar': + case 'single-quoted-scalar': + if (key.source.includes('\n')) + return true; + if (key.end) + for (const st of key.end) + if (st.type === 'newline') + return true; + return false; + case 'flow-collection': + for (const it of key.items) { + for (const st of it.start) + if (st.type === 'newline') + return true; + if (it.sep) + for (const st of it.sep) + if (st.type === 'newline') + return true; + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === 'flow-collection') { + const end = fc.end[0]; + if (end.indent === indent && + (end.source === ']' || end.source === '}') && + containsNewline(fc)) { + const msg = 'Flow end indicator should be more indented than parent'; + onError(end, 'BAD_INDENT', msg, true); + } + } +} + +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === 'function' + ? uniqueKeys + : (a, b) => a === b || + (isScalar$1(a) && + isScalar$1(b) && + a.value === b.value && + !(a.value === '<<' && ctx.schema.merge)); + return items.some(pair => isEqual(pair.key, search)); +} + +const startColMsg = 'All mapping items must start at the same column'; +function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + // key properties + const keyProps = resolveProps(start, { + indicator: 'explicit-key-ind', + next: key ?? sep?.[0], + offset, + onError, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === 'block-seq') + onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key'); + else if ('indent' in key && key.indent !== bm.indent) + onError(offset, 'BAD_INDENT', startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map.comment) + map.comment += '\n' + keyProps.comment; + else + map.comment = keyProps.comment; + } + continue; + } + if (keyProps.hasNewlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line'); + } + } + else if (keyProps.found?.indent !== bm.indent) { + onError(offset, 'BAD_INDENT', startColMsg); + } + // key value + const keyStart = keyProps.end; + const keyNode = key + ? composeNode(ctx, key, keyProps, onError) + : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + if (mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique'); + // value properties + const valueProps = resolveProps(sep ?? [], { + indicator: 'map-value-ind', + next: value, + offset: keyNode.range[2], + onError, + startOnNewline: !key || key.type === 'block-scalar' + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === 'block-map' && !valueProps.hasNewline) + onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings'); + if (ctx.options.strict && + keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key'); + } + // value value + const valueNode = value + ? composeNode(ctx, value, valueProps, onError) + : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + else { + // key with no value + if (implicitKey) + onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values'); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += '\n' + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content'); + map.range = [bm.offset, offset, commentEnd ?? offset]; + return map; +} + +function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps(start, { + indicator: 'seq-item-ind', + next: value, + offset, + onError, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value && value.type === 'block-seq') + onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column'); + else + onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator'); + } + else { + commentEnd = props.end; + if (props.comment) + seq.comment = props.comment; + continue; + } + } + const node = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq.items.push(node); + } + seq.range = [bs.offset, offset, commentEnd ?? offset]; + return seq; +} + +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ''; + if (end) { + let hasSpace = false; + let sep = ''; + for (const token of end) { + const { source, type } = token; + switch (type) { + case 'space': + hasSpace = true; + break; + case 'comment': { + if (reqSpace && !hasSpace) + onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters'); + const cb = source.substring(1) || ' '; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ''; + break; + } + case 'newline': + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +const blockMsg = 'Block collections are not allowed within flow collections'; +const isBlock$1 = (token) => token && (token.type === 'block-map' || token.type === 'block-seq'); +function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { + const isMap = fc.start.source === '{'; + const fcName = isMap ? 'flow map' : 'flow sequence'; + const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap : YAMLSeq)); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: 'explicit-key-ind', + next: key ?? sep?.[0], + offset, + onError, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += '\n' + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap && ctx.options.strict && containsNewline(key)) + onError(key, // checked by containsNewline() + 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line'); + } + if (i === 0) { + if (props.comma) + onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`); + } + else { + if (!props.comma) + onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ''; + loop: for (const st of start) { + switch (st.type) { + case 'comma': + case 'space': + break; + case 'comment': + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += '\n' + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap && !sep && !props.found) { + // item is a value in a seq + // → key & sep are empty, start does not include ? or : + const valueNode = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock$1(value)) + onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg); + } + else { + // item is a key+value pair + // key value + const keyStart = props.end; + const keyNode = key + ? composeNode(ctx, key, props, onError) + : composeEmptyNode(ctx, keyStart, start, null, props, onError); + if (isBlock$1(key)) + onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg); + // value properties + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: 'map-value-ind', + next: value, + offset: keyNode.range[2], + onError, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === 'newline') { + onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line'); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key'); + } + } + else if (value) { + if ('source' in value && value.source && value.source[0] === ':') + onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`); + else + onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`); + } + // value value + const valueNode = value + ? composeNode(ctx, value, valueProps, onError) + : valueProps.found + ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) + : null; + if (valueNode) { + if (isBlock$1(value)) + onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg); + } + else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += '\n' + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap) { + const map = coll; + if (mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique'); + map.items.push(pair); + } + else { + const map = new YAMLMap(ctx.schema); + map.flow = true; + map.items.push(pair); + coll.items.push(map); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap ? '}' : ']'; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce && ce.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot + ? `${name} must end with a ${expectedEnd}` + : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += '\n' + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } + else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +function resolveCollection(CN, ctx, token, onError, tagName, tag) { + const coll = token.type === 'block-map' + ? resolveBlockMap(CN, ctx, token, onError, tag) + : token.type === 'block-seq' + ? resolveBlockSeq(CN, ctx, token, onError, tag) + : resolveFlowCollection(CN, ctx, token, onError, tag); + const Coll = coll.constructor; + // If we got a tagName matching the class, or the tag name is '!', + // then use the tagName from the node class used to create it. + if (tagName === '!' || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN, ctx, token, tagToken, onError) { + const tagName = !tagToken + ? null + : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg)); + const expType = token.type === 'block-map' + ? 'map' + : token.type === 'block-seq' + ? 'seq' + : token.start.source === '{' + ? 'map' + : 'seq'; + // shortcut: check if it's a generic YAMLMap or YAMLSeq + // before jumping into the custom tag logic. + if (!tagToken || + !tagName || + tagName === '!' || + (tagName === YAMLMap.tagName && expType === 'map') || + (tagName === YAMLSeq.tagName && expType === 'seq') || + !expType) { + return resolveCollection(CN, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt && kt.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } + else { + if (kt?.collection) { + onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true); + } + else { + onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll; + const node = isNode$1(res) + ? res + : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +function resolveBlockScalar(scalar, strict, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, strict, onError); + if (!header) + return { value: '', type: null, comment: '', range: [start, start, start] }; + const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + // determine the end of content & start of chomping + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === '' || content === '\r') + chompStart = i; + else + break; + } + // shortcut for empty contents + if (chompStart === 0) { + const value = header.chomp === '+' && lines.length > 0 + ? '\n'.repeat(Math.max(1, lines.length - 1)) + : ''; + let end = start + header.length; + if (scalar.source) + end += scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; + } + // find the indentation level to trim from start + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === '' || content === '\r') { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } + else { + if (indent.length < trimIndent) { + const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; + onError(offset + indent.length, 'MISSING_CHAR', message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + break; + } + offset += indent.length + content.length + 1; + } + // include trailing more-indented empty lines in content + for (let i = lines.length - 1; i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ''; + let sep = ''; + let prevMoreIndented = false; + // leading whitespace is kept intact + for (let i = 0; i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + '\n'; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === '\r'; + if (crlf) + content = content.slice(0, -1); + /* istanbul ignore if already caught in lexer */ + if (content && indent.length < trimIndent) { + const src = header.indent + ? 'explicit indentation indicator' + : 'first line'; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message); + indent = ''; + } + if (type === Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = '\n'; + } + else if (indent.length > trimIndent || content[0] === '\t') { + // more-indented content within a folded block + if (sep === ' ') + sep = '\n'; + else if (!prevMoreIndented && sep === '\n') + sep = '\n\n'; + value += sep + indent.slice(trimIndent) + content; + sep = '\n'; + prevMoreIndented = true; + } + else if (content === '') { + // empty line + if (sep === '\n') + value += '\n'; + else + sep = '\n'; + } + else { + value += sep + content; + sep = ' '; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case '-': + break; + case '+': + for (let i = chompStart; i < lines.length; ++i) + value += '\n' + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== '\n') + value += '\n'; + break; + default: + value += '\n'; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + /* istanbul ignore if should not happen */ + if (props[0].type !== 'block-scalar-header') { + onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found'); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ''; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === '-' || ch === '+')) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ''; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case 'space': + hasSpace = true; + // fallthrough + case 'newline': + length += token.source.length; + break; + case 'comment': + if (strict && !hasSpace) { + const message = 'Comments must be separated from other tokens by white space characters'; + onError(token, 'MISSING_CHAR', message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case 'error': + onError(token, 'UNEXPECTED_TOKEN', token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, 'UNEXPECTED_TOKEN', message); + const ts = token.source; + if (ts && typeof ts === 'string') + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +/** @returns Array of lines split up as `[indent, content]` */ +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] + ? [m[1], first.slice(m[1].length)] + : ['', first]; + const lines = [line0]; + for (let i = 1; i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; +} + +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case 'scalar': + _type = Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case 'single-quoted-scalar': + _type = Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case 'double-quoted-scalar': + _type = Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`); + return { + value: '', + type: null, + comment: '', + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ''; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case '\t': + badChar = 'a tab character'; + break; + case ',': + badChar = 'flow indicator character ,'; + break; + case '%': + badChar = 'directive indicator character %'; + break; + case '|': + case '>': { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case '@': + case '`': { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`); + return foldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, 'MISSING_CHAR', "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function foldLines(source) { + /** + * The negative lookbehind here and in the `re` RegExp is to + * prevent causing a polynomial search time in certain cases. + * + * The try-catch is for Safari, which doesn't support this yet: + * https://caniuse.com/js-regexp-lookbehind + */ + let first, line; + try { + first = new RegExp('(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } + else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, 'MISSING_CHAR', 'Missing closing "quote'); + return res; +} +/** + * Fold a single newline into a space, multiple newlines to N - 1 newlines. + * Presumes `source[offset] === '\n'` + */ +function foldNewline(source, offset) { + let fold = ''; + let ch = source[offset + 1]; + while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { + if (ch === '\r' && source[offset + 2] !== '\n') + break; + if (ch === '\n') + fold += '\n'; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = ' '; + return { fold, offset }; +} +const escapeCodes = { + '0': '\0', + a: '\x07', + b: '\b', + e: '\x1b', + f: '\f', + n: '\n', + r: '\r', + t: '\t', + v: '\v', + N: '\u0085', + _: '\u00a0', + L: '\u2028', + P: '\u2029', + ' ': ' ', + '"': '"', + '/': '/', + '\\': '\\', + '\t': '\t' +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + if (isNaN(code)) { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`); + return raw; + } + return String.fromCodePoint(code); +} + +function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === 'block-scalar' + ? resolveBlockScalar(token, ctx.options.strict, onError) + : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken + ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg)) + : null; + const tag = tagToken && tagName + ? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError) + : token.type === 'scalar' + ? findScalarTagByTest(ctx, value, token, onError) + : ctx.schema[SCALAR$1]; + let scalar; + try { + const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options); + scalar = isScalar$1(res) ? res : new Scalar(res); + } + catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg); + scalar = new Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema, value, tagName, tagToken, onError) { + if (tagName === '!') + return schema[SCALAR$1]; // non-specific tag + const matchWithTest = []; + for (const tag of schema.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + // Ensure that the known tag is available for stringifying, + // but does not get used by default. + schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })); + return kt; + } + onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str'); + return schema[SCALAR$1]; +} +function findScalarTagByTest({ directives, schema }, value, token, onError) { + const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[SCALAR$1]; + if (schema.compat) { + const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ?? + schema[SCALAR$1]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, 'TAG_RESOLVE_FAILED', msg, true); + } + } + return tag; +} + +function emptyScalarPosition(offset, before, pos) { + if (before) { + if (pos === null) + pos = before.length; + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case 'space': + case 'comment': + case 'newline': + offset -= st.source.length; + continue; + } + // Technically, an empty scalar is immediately after the last non-empty + // node, but it's more useful to place it after any whitespace. + st = before[++i]; + while (st?.type === 'space') { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +const CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case 'alias': + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties'); + break; + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + case 'block-scalar': + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case 'block-map': + case 'block-seq': + case 'flow-collection': + node = composeCollection(CN, ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + default: { + const message = token.type === 'error' + ? token.message + : `Unsupported token (type: ${token.type})`; + onError(token, 'UNEXPECTED_TOKEN', message); + node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError); + isSrcToken = false; + } + } + if (anchor && node.anchor === '') + onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string'); + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === 'scalar' && token.source === '') + node.comment = comment; + else + node.commentBefore = comment; + } + // @ts-expect-error Type checking misses meaning of isSrcToken + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: 'scalar', + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: '' + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === '') + onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string'); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === '') + onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string'); + if (alias.source.endsWith(':')) + onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(undefined, opts); + const ctx = { + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: 'doc-start', + next: value ?? end?.[0], + offset, + onError, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && + (value.type === 'block-map' || value.type === 'block-seq') && + !props.hasNewline) + onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker'); + } + // @ts-expect-error If Contents is set, let's trust the user + doc.contents = value + ? composeNode(ctx, value, props, onError) + : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +function getErrorPos(src) { + if (typeof src === 'number') + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === 'string' ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ''; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case '#': + comment += + (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') + + (source.substring(1) || ' '); + atComment = true; + afterEmptyLine = false; + break; + case '%': + if (prelude[i + 1]?.[0] !== '#') + i += 1; + atComment = false; + break; + default: + // This may be wrong after doc-end, but in that case it doesn't matter + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +/** + * Compose a stream of CST nodes into a stream of YAML Documents. + * + * ```ts + * import { Composer, Parser } from 'yaml' + * + * const src: string = ... + * const tokens = new Parser().parse(src) + * const docs = new Composer().compose(tokens) + * ``` + */ +class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + this.directives = new Directives({ version: options.version || '1.2' }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + //console.log({ dc: doc.comment, prelude, comment }) + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment; + } + else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } + else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } + else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case 'directive': + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, 'BAD_DIRECTIVE', message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case 'document': { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line'); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case 'byte-order-mark': + case 'space': + break; + case 'comment': + case 'newline': + this.prelude.push(token.source); + break; + case 'error': { + const msg = token.source + ? `${token.message}: ${JSON.stringify(token.source)}` + : token.message; + const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case 'doc-end': { + if (!this.doc) { + const msg = 'Unexpected doc-end without preceding document'; + this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } + else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(undefined, opts); + if (this.atDirectives) + this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line'); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +} + +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return resolveFlowScalar(token, strict, _onError); + case 'block-scalar': + return resolveBlockScalar(token, strict, _onError); + } + } + return null; +} +/** + * Create a new scalar token with `value` + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param value The string representation of the value, which will have its content properly indented. + * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.indent The indent level of the token. + * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value. + * @param context.offset The offset position of the token. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context; + const source = stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? ' '.repeat(indent) : '', + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: 'newline', offset: -1, indent, source: '\n' } + ]; + switch (source[0]) { + case '|': + case '>': { + const he = source.indexOf('\n'); + const head = source.substring(0, he); + const body = source.substring(he + 1) + '\n'; + const props = [ + { type: 'block-scalar-header', offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: 'newline', offset: -1, indent, source: '\n' }); + return { type: 'block-scalar', offset, indent, props, source: body }; + } + case '"': + return { type: 'double-quoted-scalar', offset, indent, source, end }; + case "'": + return { type: 'single-quoted-scalar', offset, indent, source, end }; + default: + return { type: 'scalar', offset, indent, source, end }; + } +} +/** + * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have. + * + * Best efforts are made to retain any comments previously associated with the `token`, + * though all contents within a collection's `items` will be overwritten. + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key. + * @param value The string representation of the value, which will have its content properly indented. + * @param context.afterKey In most cases, values after a key should have an additional level of indentation. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ +function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = 'indent' in token ? token.indent : null; + if (afterKey && typeof indent === 'number') + indent += 2; + if (!type) + switch (token.type) { + case 'single-quoted-scalar': + type = 'QUOTE_SINGLE'; + break; + case 'double-quoted-scalar': + type = 'QUOTE_DOUBLE'; + break; + case 'block-scalar': { + const header = token.props[0]; + if (header.type !== 'block-scalar-header') + throw new Error('Invalid block scalar header'); + type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL'; + break; + } + default: + type = 'PLAIN'; + } + const source = stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '', + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case '|': + case '>': + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, 'double-quoted-scalar'); + break; + case "'": + setFlowScalarValue(token, source, 'single-quoted-scalar'); + break; + default: + setFlowScalarValue(token, source, 'scalar'); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf('\n'); + const head = source.substring(0, he); + const body = source.substring(he + 1) + '\n'; + if (token.type === 'block-scalar') { + const header = token.props[0]; + if (header.type !== 'block-scalar-header') + throw new Error('Invalid block scalar header'); + header.source = head; + token.source = body; + } + else { + const { offset } = token; + const indent = 'indent' in token ? token.indent : -1; + const props = [ + { type: 'block-scalar-header', offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined)) + props.push({ type: 'newline', offset: -1, indent, source: '\n' }); + for (const key of Object.keys(token)) + if (key !== 'type' && key !== 'offset') + delete token[key]; + Object.assign(token, { type: 'block-scalar', indent, props, source: body }); + } +} +/** @returns `true` if last token is a newline */ +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case 'space': + case 'comment': + props.push(st); + break; + case 'newline': + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case 'scalar': + case 'double-quoted-scalar': + case 'single-quoted-scalar': + token.type = type; + token.source = source; + break; + case 'block-scalar': { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === 'block-scalar-header') + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case 'block-map': + case 'block-seq': { + const offset = token.offset + source.length; + const nl = { type: 'newline', offset, indent: token.indent, source: '\n' }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = 'indent' in token ? token.indent : -1; + const end = 'end' in token && Array.isArray(token.end) + ? token.end.filter(st => st.type === 'space' || + st.type === 'comment' || + st.type === 'newline') + : []; + for (const key of Object.keys(token)) + if (key !== 'type' && key !== 'offset') + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +/** + * Stringify a CST document, token, or collection item + * + * Fair warning: This applies no validation whatsoever, and + * simply concatenates the sources in their logical order. + */ +const stringify$1 = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case 'block-scalar': { + let res = ''; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case 'block-map': + case 'block-seq': { + let res = ''; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case 'flow-collection': { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case 'document': { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ('end' in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value }) { + let res = ''; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; +} + +const BREAK = Symbol('break visit'); +const SKIP = Symbol('skip children'); +const REMOVE = Symbol('remove item'); +/** + * Apply a visitor to a CST document or item. + * + * Walks through the tree (depth-first) starting from the root, calling a + * `visitor` function with two arguments when entering each item: + * - `item`: The current item, which included the following members: + * - `start: SourceToken[]` – Source tokens before the key or value, + * possibly including its anchor or tag. + * - `key?: Token | null` – Set for pair values. May then be `null`, if + * the key before the `:` separator is empty. + * - `sep?: SourceToken[]` – Source tokens between the key and the value, + * which should include the `:` map value indicator if `value` is set. + * - `value?: Token` – The value of a sequence item, or of a map pair. + * - `path`: The steps from the root to the current node, as an array of + * `['key' | 'value', number]` tuples. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this token, continue with + * next sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current item, then continue with the next one + * - `number`: Set the index of the next step. This is useful especially if + * the index of the current token has changed. + * - `function`: Define the next visitor for this item. After the original + * visitor is called on item entry, next visitors are called after handling + * a non-empty `key` and when exiting the item. + */ +function visit(cst, visitor) { + if ('type' in cst && cst.type === 'document') + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +// Without the `as symbol` casts, TS declares these in the `visit` +// namespace using `var`, but then complains about that because +// `unique symbol` must be `const`. +/** Terminate visit traversal completely */ +visit.BREAK = BREAK; +/** Do not visit the children of the current item */ +visit.SKIP = SKIP; +/** Remove the current item */ +visit.REMOVE = REMOVE; +/** Find the item at `path` from `cst` as the root */ +visit.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && 'items' in tok) { + item = tok.items[index]; + } + else + return undefined; + } + return item; +}; +/** + * Get the immediate parent collection of the item at `path` from `cst` as the root. + * + * Throws an error if the collection is not found, which should never happen if the item itself exists. + */ +visit.parentCollection = (cst, path) => { + const parent = visit.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && 'items' in coll) + return coll; + throw new Error('Parent collection not found'); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === 'symbol') + return ctrl; + for (const field of ['key', 'value']) { + const token = item[field]; + if (token && 'items' in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === 'number') + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === 'function' && field === 'key') + ctrl = ctrl(item, path); + } + } + return typeof ctrl === 'function' ? ctrl(item, path) : ctrl; +} + +/** The byte order mark */ +const BOM = '\u{FEFF}'; +/** Start of doc-mode */ +const DOCUMENT = '\x02'; // C0: Start of Text +/** Unexpected end of flow-mode */ +const FLOW_END = '\x18'; // C0: Cancel +/** Next token is a scalar value */ +const SCALAR = '\x1f'; // C0: Unit Separator +/** @returns `true` if `token` is a flow or block collection */ +const isCollection = (token) => !!token && 'items' in token; +/** @returns `true` if `token` is a flow or block scalar; not an alias */ +const isScalar = (token) => !!token && + (token.type === 'scalar' || + token.type === 'single-quoted-scalar' || + token.type === 'double-quoted-scalar' || + token.type === 'block-scalar'); +/* istanbul ignore next */ +/** Get a printable representation of a lexer token */ +function prettyToken(token) { + switch (token) { + case BOM: + return ''; + case DOCUMENT: + return ''; + case FLOW_END: + return ''; + case SCALAR: + return ''; + default: + return JSON.stringify(token); + } +} +/** Identify the type of a lexer token. May return `null` for unknown tokens. */ +function tokenType(source) { + switch (source) { + case BOM: + return 'byte-order-mark'; + case DOCUMENT: + return 'doc-mode'; + case FLOW_END: + return 'flow-error-end'; + case SCALAR: + return 'scalar'; + case '---': + return 'doc-start'; + case '...': + return 'doc-end'; + case '': + case '\n': + case '\r\n': + return 'newline'; + case '-': + return 'seq-item-ind'; + case '?': + return 'explicit-key-ind'; + case ':': + return 'map-value-ind'; + case '{': + return 'flow-map-start'; + case '}': + return 'flow-map-end'; + case '[': + return 'flow-seq-start'; + case ']': + return 'flow-seq-end'; + case ',': + return 'comma'; + } + switch (source[0]) { + case ' ': + case '\t': + return 'space'; + case '#': + return 'comment'; + case '%': + return 'directive-line'; + case '*': + return 'alias'; + case '&': + return 'anchor'; + case '!': + return 'tag'; + case "'": + return 'single-quoted-scalar'; + case '"': + return 'double-quoted-scalar'; + case '|': + case '>': + return 'block-scalar-header'; + } + return null; +} + +var cst = { + __proto__: null, + BOM: BOM, + DOCUMENT: DOCUMENT, + FLOW_END: FLOW_END, + SCALAR: SCALAR, + createScalarToken: createScalarToken, + isCollection: isCollection, + isScalar: isScalar, + prettyToken: prettyToken, + resolveAsScalar: resolveAsScalar, + setScalarValue: setScalarValue, + stringify: stringify$1, + tokenType: tokenType, + visit: visit +}; + +/* +START -> stream + +stream + directive -> line-end -> stream + indent + line-end -> stream + [else] -> line-start + +line-end + comment -> line-end + newline -> . + input-end -> END + +line-start + doc-start -> doc + doc-end -> stream + [else] -> indent -> block-start + +block-start + seq-item-start -> block-start + explicit-key-start -> block-start + map-value-start -> block-start + [else] -> doc + +doc + line-end -> line-start + spaces -> doc + anchor -> doc + tag -> doc + flow-start -> flow -> doc + flow-end -> error -> doc + seq-item-start -> error -> doc + explicit-key-start -> error -> doc + map-value-start -> doc + alias -> doc + quote-start -> quoted-scalar -> doc + block-scalar-header -> line-end -> block-scalar(min) -> line-start + [else] -> plain-scalar(false, min) -> doc + +flow + line-end -> flow + spaces -> flow + anchor -> flow + tag -> flow + flow-start -> flow -> flow + flow-end -> . + seq-item-start -> error -> flow + explicit-key-start -> flow + map-value-start -> flow + alias -> flow + quote-start -> quoted-scalar -> flow + comma -> flow + [else] -> plain-scalar(true, 0) -> flow + +quoted-scalar + quote-end -> . + [else] -> quoted-scalar + +block-scalar(min) + newline + peek(indent < min) -> . + [else] -> block-scalar(min) + +plain-scalar(is-flow, min) + scalar-end(is-flow) -> . + peek(newline + (indent < min)) -> . + [else] -> plain-scalar(min) +*/ +function isEmpty(ch) { + switch (ch) { + case undefined: + case ' ': + case '\n': + case '\r': + case '\t': + return true; + default: + return false; + } +} +const hexDigits = '0123456789ABCDEFabcdef'.split(''); +const tagChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split(''); +const invalidFlowScalarChars = ',[]{}'.split(''); +const invalidAnchorChars = ' ,[]{}\n\r\t'.split(''); +const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.includes(ch); +/** + * Splits an input string into lexical tokens, i.e. smaller strings that are + * easily identifiable by `tokens.tokenType()`. + * + * Lexing starts always in a "stream" context. Incomplete input may be buffered + * until a complete token can be emitted. + * + * In addition to slices of the original input, the following control characters + * may also be emitted: + * + * - `\x02` (Start of Text): A document starts with the next token + * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error) + * - `\x1f` (Unit Separator): Next token is a scalar value + * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents + */ +class Lexer { + constructor() { + /** + * Flag indicating whether the end of the current buffer marks the end of + * all input + */ + this.atEnd = false; + /** + * Explicit indent set in block scalar header, as an offset from the current + * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not + * explicitly set. + */ + this.blockScalarIndent = -1; + /** + * Block scalars that include a + (keep) chomping indicator in their header + * include trailing empty lines, which are otherwise excluded from the + * scalar's contents. + */ + this.blockScalarKeep = false; + /** Current input */ + this.buffer = ''; + /** + * Flag noting whether the map value indicator : can immediately follow this + * node within a flow context. + */ + this.flowKey = false; + /** Count of surrounding flow collection levels. */ + this.flowLevel = 0; + /** + * Minimum level of indentation required for next lines to be parsed as a + * part of the current scalar value. + */ + this.indentNext = 0; + /** Indentation level of the current line. */ + this.indentValue = 0; + /** Position of the next \n character. */ + this.lineEndPos = null; + /** Stores the state of the lexer if reaching the end of incpomplete input */ + this.next = null; + /** A pointer to `buffer`; the current position of the lexer. */ + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? 'stream'; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === ' ' || ch === '\t') + ch = this.buffer[++i]; + if (!ch || ch === '#' || ch === '\n') + return true; + if (ch === '\r') + return this.buffer[i + 1] === '\n'; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === ' ') + ch = this.buffer[++indent + offset]; + if (ch === '\r') { + const next = this.buffer[indent + offset + 1]; + if (next === '\n' || (!next && !this.atEnd)) + return offset + indent + 1; + } + return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd) + ? offset + indent + : -1; + } + if (ch === '-' || ch === '.') { + const dt = this.buffer.substr(offset, 3); + if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== 'number' || (end !== -1 && end < this.pos)) { + end = this.buffer.indexOf('\n', this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === '\r') + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case 'stream': + return yield* this.parseStream(); + case 'line-start': + return yield* this.parseLineStart(); + case 'block-start': + return yield* this.parseBlockStart(); + case 'doc': + return yield* this.parseDocument(); + case 'flow': + return yield* this.parseFlowCollection(); + case 'quoted-scalar': + return yield* this.parseQuotedScalar(); + case 'block-scalar': + return yield* this.parseBlockScalar(); + case 'plain-scalar': + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext('stream'); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === '%') { + let dirEnd = line.length; + const cs = line.indexOf('#'); + if (cs !== -1) { + const ch = line[cs - 1]; + if (ch === ' ' || ch === '\t') + dirEnd = cs - 1; + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === ' ' || ch === '\t') + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); // possible comment + this.pushNewline(); + return 'stream'; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return 'stream'; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext('line-start'); + if (ch === '-' || ch === '.') { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext('line-start'); + const s = this.peek(3); + if (s === '---' && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return 'doc'; + } + else if (s === '...' && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + return 'stream'; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext('block-start'); + if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return yield* this.parseBlockStart(); + } + return 'doc'; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext('doc'); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case '#': + yield* this.pushCount(line.length - n); + // fallthrough + case undefined: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case '{': + case '[': + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return 'flow'; + case '}': + case ']': + // this is an error + yield* this.pushCount(1); + return 'doc'; + case '*': + yield* this.pushUntil(isNotAnchorChar); + return 'doc'; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case '|': + case '>': + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } + else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext('flow'); + if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') || + (indent === 0 && + (line.startsWith('---') || line.startsWith('...')) && + isEmpty(line[3]))) { + // Allowing for the terminal ] or } at the same (rather than greater) + // indent level as the initial [ or { is technically invalid, but + // failing here would be surprising to users. + const atFlowEndMarker = indent === this.indentNext - 1 && + this.flowLevel === 1 && + (line[0] === ']' || line[0] === '}'); + if (!atFlowEndMarker) { + // this is an error + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ',') { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case undefined: + return 'flow'; + case '#': + yield* this.pushCount(line.length - n); + return 'flow'; + case '{': + case '[': + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return 'flow'; + case '}': + case ']': + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? 'flow' : 'doc'; + case '*': + yield* this.pushUntil(isNotAnchorChar); + return 'flow'; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ':': { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ',') { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return 'flow'; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } + else { + // double-quote + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === '\\') + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + // Only looking for newlines within the quotes + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf('\n', this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf('\n', cs); + } + if (nl !== -1) { + // this is an error caused by an unexpected unindent + end = nl - (qb[nl - 1] === '\r' ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext('quoted-scalar'); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? 'flow' : 'doc'; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === '+') + this.blockScalarKeep = true; + else if (ch > '0' && ch <= '9') + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== '-') + break; + } + return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#'); + } + *parseBlockScalar() { + let nl = this.pos - 1; // may be -1 if this.pos === 0 + let indent = 0; + let ch; + loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) { + switch (ch) { + case ' ': + indent += 1; + break; + case '\n': + nl = i; + indent = 0; + break; + case '\r': { + const next = this.buffer[i + 1]; + if (!next && !this.atEnd) + return this.setNext('block-scalar'); + if (next === '\n') + break; + } // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext('block-scalar'); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else + this.indentNext += this.blockScalarIndent; + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf('\n', cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext('block-scalar'); + nl = this.buffer.length; + } + } + if (!this.blockScalarKeep) { + do { + let i = nl - 1; + let ch = this.buffer[i]; + if (ch === '\r') + ch = this.buffer[--i]; + const lastChar = i; // Drop the line if last char not more indented + while (ch === ' ' || ch === '\t') + ch = this.buffer[--i]; + if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar) + nl = i; + else + break; + } while (true); + } + yield SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while ((ch = this.buffer[++i])) { + if (ch === ':') { + const next = this.buffer[i + 1]; + if (isEmpty(next) || (inFlow && next === ',')) + break; + end = i; + } + else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === '\r') { + if (next === '\n') { + i += 1; + ch = '\n'; + next = this.buffer[i + 1]; + } + else + end = i; + } + if (next === '#' || (inFlow && invalidFlowScalarChars.includes(next))) + break; + if (ch === '\n') { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); // to advance, but still account for ' #' + } + } + else { + if (inFlow && invalidFlowScalarChars.includes(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext('plain-scalar'); + yield SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? 'flow' : 'doc'; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } + else if (allowEmpty) + yield ''; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case '!': + return ((yield* this.pushTag()) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + case '&': + return ((yield* this.pushUntil(isNotAnchorChar)) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + case '-': // this is an error + case '?': // this is an error outside flow collections + case ':': { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || (inFlow && invalidFlowScalarChars.includes(ch1))) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return ((yield* this.pushCount(1)) + + (yield* this.pushSpaces(true)) + + (yield* this.pushIndicators())); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === '<') { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== '>') + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false); + } + else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.includes(ch)) + ch = this.buffer[++i]; + else if (ch === '%' && + hexDigits.includes(this.buffer[i + 1]) && + hexDigits.includes(this.buffer[i + 2])) { + ch = this.buffer[(i += 3)]; + } + else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === '\n') + return yield* this.pushCount(1); + else if (ch === '\r' && this.charAt(1) === '\n') + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === ' ' || (allowTabs && ch === '\t')); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +} + +/** + * Tracks newlines during parsing in order to provide an efficient API for + * determining the one-indexed `{ line, col }` position for any offset + * within the input. + */ +class LineCounter { + constructor() { + this.lineStarts = []; + /** + * Should be called in ascending order. Otherwise, call + * `lineCounter.lineStarts.sort()` before calling `linePos()`. + */ + this.addNewLine = (offset) => this.lineStarts.push(offset); + /** + * Performs a binary search and returns the 1-indexed { line, col } + * position of `offset`. If `line === 0`, `addNewLine` has never been + * called or `offset` is before the first known newline. + */ + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = (low + high) >> 1; // Math.floor((low + high) / 2) + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +} + +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case 'space': + case 'comment': + case 'newline': + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + case 'flow-collection': + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case 'document': + return parent.start; + case 'block-map': { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case 'block-seq': + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +/** Note: May modify input array */ +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case 'doc-start': + case 'explicit-key-ind': + case 'map-value-ind': + case 'seq-item-ind': + case 'newline': + break loop; + } + } + while (prev[++i]?.type === 'space') { + /* loop */ + } + return prev.splice(i, prev.length); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === 'flow-seq-start') { + for (const it of fc.items) { + if (it.sep && + !it.value && + !includesToken(it.start, 'explicit-key-ind') && + !includesToken(it.sep, 'map-value-ind')) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } + else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } +} +/** + * A YAML concrete syntax tree (CST) parser + * + * ```ts + * const src: string = ... + * for (const token of new Parser().parse(src)) { + * // token: Token + * } + * ``` + * + * To use the parser with a user-provided lexer: + * + * ```ts + * function* parse(source: string, lexer: Lexer) { + * const parser = new Parser() + * for (const lexeme of lexer.lex(source)) + * yield* parser.next(lexeme) + * yield* parser.end() + * } + * + * const src: string = ... + * const lexer = new Lexer() + * for (const token of parse(src, lexer)) { + * // token: Token + * } + * ``` + */ +let Parser$1 = class Parser { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + /** If true, space and sequence indicators count as indentation */ + this.atNewLine = true; + /** If true, next token is a scalar value */ + this.atScalar = false; + /** Current indentation level */ + this.indent = 0; + /** Current offset since the start of parsing */ + this.offset = 0; + /** On the same line with a block map key */ + this.onKeyLine = false; + /** Top indicates the node that's currently being built */ + this.stack = []; + /** The source of the current token, set in parse() */ + this.source = ''; + /** The type of the current token, set in parse() */ + this.type = ''; + // Must be defined after `next()` + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: 'error', offset: this.offset, message, source }); + this.offset += source.length; + } + else if (type === 'scalar') { + this.atNewLine = false; + this.atScalar = true; + this.type = 'scalar'; + } + else { + this.type = type; + yield* this.step(); + switch (type) { + case 'newline': + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case 'space': + if (this.atNewLine && source[0] === ' ') + this.indent += source.length; + break; + case 'explicit-key-ind': + case 'map-value-ind': + case 'seq-item-ind': + if (this.atNewLine) + this.indent += source.length; + break; + case 'doc-mode': + case 'flow-error-end': + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === 'doc-end' && (!top || top.type !== 'doc-end')) { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: 'doc-end', + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case 'document': + return yield* this.document(top); + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return yield* this.scalar(top); + case 'block-scalar': + return yield* this.blockScalar(top); + case 'block-map': + return yield* this.blockMap(top); + case 'block-seq': + return yield* this.blockSequence(top); + case 'flow-collection': + return yield* this.flowCollection(top); + case 'doc-end': + return yield* this.documentEnd(top); + } + /* istanbul ignore next should not happen */ + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + /* istanbul ignore if should not happen */ + if (!token) { + const message = 'Tried to pop an empty stack'; + yield { type: 'error', offset: this.offset, source: '', message }; + } + else if (this.stack.length === 0) { + yield token; + } + else { + const top = this.peek(1); + if (token.type === 'block-scalar') { + // Block scalars use their parent rather than header indent + token.indent = 'indent' in top ? top.indent : 0; + } + else if (token.type === 'flow-collection' && top.type === 'document') { + // Ignore all indent for top-level flow collections + token.indent = 0; + } + if (token.type === 'flow-collection') + fixFlowSeqItems(token); + switch (top.type) { + case 'document': + top.value = token; + break; + case 'block-scalar': + top.props.push(token); // error + break; + case 'block-map': { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } + else if (it.sep) { + it.value = token; + } + else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !includesToken(it.start, 'explicit-key-ind'); + return; + } + break; + } + case 'block-seq': { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case 'flow-collection': { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === 'document' || + top.type === 'block-map' || + top.type === 'block-seq') && + (token.type === 'block-map' || token.type === 'block-seq')) { + const last = token.items[token.items.length - 1]; + if (last && + !last.sep && + !last.value && + last.start.length > 0 && + findNonEmptyIndex(last.start) === -1 && + (token.indent === 0 || + last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) { + if (top.type === 'document') + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case 'directive-line': + yield { type: 'directive', offset: this.offset, source: this.source }; + return; + case 'byte-order-mark': + case 'space': + case 'comment': + case 'newline': + yield this.sourceToken; + return; + case 'doc-mode': + case 'doc-start': { + const doc = { + type: 'document', + offset: this.offset, + start: [] + }; + if (this.type === 'doc-start') + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: 'error', + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case 'doc-start': { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } + else + doc.start.push(this.sourceToken); + return; + } + case 'anchor': + case 'tag': + case 'space': + case 'comment': + case 'newline': + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: 'error', + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === 'map-value-ind') { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } + else + sep = [this.sourceToken]; + const map = { + type: 'block-map', + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } + else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case 'space': + case 'comment': + case 'newline': + scalar.props.push(this.sourceToken); + return; + case 'scalar': + scalar.source = this.source; + // block-scalar source includes trailing newline + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf('\n') + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf('\n', nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map) { + const it = map.items[map.items.length - 1]; + // it.sep is true-ish if pair already has key or : separator + switch (this.type) { + case 'newline': + this.onKeyLine = false; + if (it.value) { + const end = 'end' in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === 'comment') + end?.push(this.sourceToken); + else + map.items.push({ start: [this.sourceToken] }); + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + it.start.push(this.sourceToken); + } + return; + case 'space': + case 'comment': + if (it.value) { + map.items.push({ start: [this.sourceToken] }); + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + if (this.atIndentedComment(it.start, map.indent)) { + const prev = map.items[map.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map.indent) { + const atNextItem = !this.onKeyLine && this.indent === map.indent && it.sep; + // For empty nodes, assign newline-separated not indented empty tokens to following node + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case 'newline': + nl.push(i); + break; + case 'space': + break; + case 'comment': + if (st.indent > map.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case 'anchor': + case 'tag': + if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + this.onKeyLine = true; + } + else if (it.sep) { + it.sep.push(this.sourceToken); + } + else { + it.start.push(this.sourceToken); + } + return; + case 'explicit-key-ind': + if (!it.sep && !includesToken(it.start, 'explicit-key-ind')) { + it.start.push(this.sourceToken); + } + else if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + } + else { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }); + } + this.onKeyLine = true; + return; + case 'map-value-ind': + if (includesToken(it.start, 'explicit-key-ind')) { + if (!it.sep) { + if (includesToken(it.start, 'newline')) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } + else { + const start = getFirstKeyStartProps(it.start); + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } + } + else if (it.value) { + map.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } + else if (includesToken(it.sep, 'map-value-ind')) { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } + else if (isFlowToken(it.key) && + !includesToken(it.sep, 'newline')) { + const start = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + // @ts-expect-error type guard is wrong here + delete it.key, delete it.sep; + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key, sep }] + }); + } + else if (start.length > 0) { + // Not actually at next item + it.sep = it.sep.concat(start, this.sourceToken); + } + else { + it.sep.push(this.sourceToken); + } + } + else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } + else if (it.value || atNextItem) { + map.items.push({ start, key: null, sep: [this.sourceToken] }); + } + else if (includesToken(it.sep, 'map-value-ind')) { + this.stack.push({ + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } + else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } + else if (it.sep) { + this.stack.push(fs); + } + else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map); + if (bv) { + if (atNextItem && + bv.type !== 'block-seq' && + includesToken(it.start, 'explicit-key-ind')) { + map.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case 'newline': + if (it.value) { + const end = 'end' in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === 'comment') + end?.push(this.sourceToken); + else + seq.items.push({ start: [this.sourceToken] }); + } + else + it.start.push(this.sourceToken); + return; + case 'space': + case 'comment': + if (it.value) + seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const prev = seq.items[seq.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case 'anchor': + case 'tag': + if (it.value || this.indent <= seq.indent) + break; + it.start.push(this.sourceToken); + return; + case 'seq-item-ind': + if (this.indent !== seq.indent) + break; + if (it.value || includesToken(it.start, 'seq-item-ind')) + seq.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === 'flow-error-end') { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top && top.type === 'flow-collection'); + } + else if (fc.end.length === 0) { + switch (this.type) { + case 'comma': + case 'explicit-key-ind': + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case 'map-value-ind': + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case 'space': + case 'comment': + case 'newline': + case 'anchor': + case 'tag': + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case 'flow-map-end': + case 'flow-seq-end': + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + /* istanbul ignore else should not happen */ + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } + else { + const parent = this.peek(2); + if (parent.type === 'block-map' && + ((this.type === 'map-value-ind' && parent.indent === fc.indent) || + (this.type === 'newline' && + !parent.items[parent.items.length - 1].sep))) { + yield* this.pop(); + yield* this.step(); + } + else if (this.type === 'map-value-ind' && + parent.type !== 'flow-collection') { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map = { + type: 'block-map', + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } + else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf('\n') + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf('\n', nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case 'alias': + case 'scalar': + case 'single-quoted-scalar': + case 'double-quoted-scalar': + return this.flowScalar(this.type); + case 'block-scalar-header': + return { + type: 'block-scalar', + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: '' + }; + case 'flow-map-start': + case 'flow-seq-start': + return { + type: 'flow-collection', + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case 'seq-item-ind': + return { + type: 'block-seq', + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case 'explicit-key-ind': { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start }] + }; + } + case 'map-value-ind': { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: 'block-map', + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== 'comment') + return false; + if (this.indent <= indent) + return false; + return start.every(st => st.type === 'newline' || st.type === 'space'); + } + *documentEnd(docEnd) { + if (this.type !== 'doc-mode') { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === 'newline') + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case 'comma': + case 'doc-start': + case 'doc-end': + case 'flow-seq-end': + case 'flow-map-end': + case 'map-value-ind': + yield* this.pop(); + yield* this.step(); + break; + case 'newline': + this.onKeyLine = false; + // fallthrough + case 'space': + case 'comment': + default: + // all other values are errors + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === 'newline') + yield* this.pop(); + } + } +}; + +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null; + return { lineCounter, prettyErrors }; +} +/** + * Parse the input as a stream of YAML documents. + * + * Documents should be separated from each other by `...` or `---` marker lines. + * + * @returns If an empty `docs` array is returned, it will be of type + * EmptyStream and contain additional stream information. In + * TypeScript, you should use `'empty' in docs` as a type guard for it. + */ +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser$1(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +/** Parse an input string into a single YAML.Document */ +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser$1(lineCounter?.addNewLine); + const composer = new Composer(options); + // `doc` is always set by compose.end(true) at the very latest + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== 'silent') { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()')); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse$b(src, reviver, options) { + let _reviver = undefined; + if (typeof reviver === 'function') { + _reviver = reviver; + } + else if (options === undefined && reviver && typeof reviver === 'object') { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach(warning => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== 'silent') + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === 'function' || Array.isArray(replacer)) { + _replacer = replacer; + } + else if (options === undefined && replacer) { + options = replacer; + } + if (typeof options === 'string') + options = options.length; + if (typeof options === 'number') { + const indent = Math.round(options); + options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === undefined) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return undefined; + } + return new Document(value, _replacer, options).toString(options); +} + +var YAML = { + __proto__: null, + Alias: Alias, + CST: cst, + Composer: Composer, + Document: Document, + Lexer: Lexer, + LineCounter: LineCounter, + Pair: Pair, + Parser: Parser$1, + Scalar: Scalar, + Schema: Schema, + YAMLError: YAMLError, + YAMLMap: YAMLMap, + YAMLParseError: YAMLParseError, + YAMLSeq: YAMLSeq, + YAMLWarning: YAMLWarning, + isAlias: isAlias, + isCollection: isCollection$1, + isDocument: isDocument, + isMap: isMap, + isNode: isNode$1, + isPair: isPair, + isScalar: isScalar$1, + isSeq: isSeq, + parse: parse$b, + parseAllDocuments: parseAllDocuments, + parseDocument: parseDocument, + stringify: stringify, + visit: visit$1, + visitAsync: visitAsync +}; + +// `export * as default from ...` fails on Webpack v4 +// https://github.com/eemeli/yaml/issues/228 + +var browser$2 = { + __proto__: null, + Alias: Alias, + CST: cst, + Composer: Composer, + Document: Document, + Lexer: Lexer, + LineCounter: LineCounter, + Pair: Pair, + Parser: Parser$1, + Scalar: Scalar, + Schema: Schema, + YAMLError: YAMLError, + YAMLMap: YAMLMap, + YAMLParseError: YAMLParseError, + YAMLSeq: YAMLSeq, + YAMLWarning: YAMLWarning, + default: YAML, + isAlias: isAlias, + isCollection: isCollection$1, + isDocument: isDocument, + isMap: isMap, + isNode: isNode$1, + isPair: isPair, + isScalar: isScalar$1, + isSeq: isSeq, + parse: parse$b, + parseAllDocuments: parseAllDocuments, + parseDocument: parseDocument, + stringify: stringify, + visit: visit$1, + visitAsync: visitAsync +}; + +var require$$3 = /*@__PURE__*/getAugmentedNamespace(browser$2); + +// eslint-disable-next-line n/no-deprecated-api +const { createRequire, createRequireFromPath } = require$$0$8; + +function req$2 (name, rootFile) { + const create = createRequire || createRequireFromPath; + const require = create(rootFile); + return require(name) +} + +var req_1 = req$2; + +const req$1 = req_1; + +/** + * 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$1(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$1(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$1(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 +}; + +var options_1 = options; + +const req = req_1; + +/** + * 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 +}; + +var plugins_1 = plugins; + +const resolve = require$$0$4.resolve; +const url$4 = require$$0$9; + +const config$1 = dist; +const yaml = require$$3; + +const loadOptions = options_1; +const loadPlugins = plugins_1; + +/* 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$4.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$1.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 + */ +var src$1 = rc; + +var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1); + +// Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell +// License: MIT. +var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; +RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu; +Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; +Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu; +StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y; +NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; +Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y; +WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu; +LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; +MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y; +SingleLineComment = /\/\/.*/y; +JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; +JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu; +JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y; +JSXText = /[^<>{}]+/y; +TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; +TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; +KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; +KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; +Newline = RegExp(LineTerminatorSequence.source); +var jsTokens_1 = function*(input, {jsx = false} = {}) { + var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; + ({length} = input); + lastIndex = 0; + lastSignificantToken = ""; + stack = [ + {tag: "JS"} + ]; + braces = []; + parenNesting = 0; + postfixIncDec = false; + while (lastIndex < length) { + mode = stack[stack.length - 1]; + switch (mode.tag) { + case "JS": + case "JSNonExpressionParen": + case "InterpolationInTemplate": + case "InterpolationInJSX": + if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + RegularExpressionLiteral.lastIndex = lastIndex; + if (match = RegularExpressionLiteral.exec(input)) { + lastIndex = RegularExpressionLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "RegularExpressionLiteral", + value: match[0], + closed: match[1] !== void 0 && match[1] !== "\\" + }); + continue; + } + } + Punctuator.lastIndex = lastIndex; + if (match = Punctuator.exec(input)) { + punctuator = match[0]; + nextLastIndex = Punctuator.lastIndex; + nextLastSignificantToken = punctuator; + switch (punctuator) { + case "(": + if (lastSignificantToken === "?NonExpressionParenKeyword") { + stack.push({ + tag: "JSNonExpressionParen", + nesting: parenNesting + }); + } + parenNesting++; + postfixIncDec = false; + break; + case ")": + parenNesting--; + postfixIncDec = true; + if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { + stack.pop(); + nextLastSignificantToken = "?NonExpressionParenEnd"; + postfixIncDec = false; + } + break; + case "{": + Punctuator.lastIndex = 0; + isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); + braces.push(isExpression); + postfixIncDec = false; + break; + case "}": + switch (mode.tag) { + case "InterpolationInTemplate": + if (braces.length === mode.nesting) { + Template.lastIndex = lastIndex; + match = Template.exec(input); + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + postfixIncDec = false; + yield ({ + type: "TemplateMiddle", + value: match[0] + }); + } else { + stack.pop(); + postfixIncDec = true; + yield ({ + type: "TemplateTail", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "InterpolationInJSX": + if (braces.length === mode.nesting) { + stack.pop(); + lastIndex += 1; + lastSignificantToken = "}"; + yield ({ + type: "JSXPunctuator", + value: "}" + }); + continue; + } + } + postfixIncDec = braces.pop(); + nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; + break; + case "]": + postfixIncDec = true; + break; + case "++": + case "--": + nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; + break; + case "<": + if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + stack.push({tag: "JSXTag"}); + lastIndex += 1; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: punctuator + }); + continue; + } + postfixIncDec = false; + break; + default: + postfixIncDec = false; + } + lastIndex = nextLastIndex; + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "Punctuator", + value: punctuator + }); + continue; + } + Identifier.lastIndex = lastIndex; + if (match = Identifier.exec(input)) { + lastIndex = Identifier.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "for": + case "if": + case "while": + case "with": + if (lastSignificantToken !== "." && lastSignificantToken !== "?.") { + nextLastSignificantToken = "?NonExpressionParenKeyword"; + } + } + lastSignificantToken = nextLastSignificantToken; + postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); + yield ({ + type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", + value: match[0] + }); + continue; + } + StringLiteral.lastIndex = lastIndex; + if (match = StringLiteral.exec(input)) { + lastIndex = StringLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "StringLiteral", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + NumericLiteral.lastIndex = lastIndex; + if (match = NumericLiteral.exec(input)) { + lastIndex = NumericLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "NumericLiteral", + value: match[0] + }); + continue; + } + Template.lastIndex = lastIndex; + if (match = Template.exec(input)) { + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + stack.push({ + tag: "InterpolationInTemplate", + nesting: braces.length + }); + postfixIncDec = false; + yield ({ + type: "TemplateHead", + value: match[0] + }); + } else { + postfixIncDec = true; + yield ({ + type: "NoSubstitutionTemplate", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "JSXTag": + case "JSXTagEnd": + JSXPunctuator.lastIndex = lastIndex; + if (match = JSXPunctuator.exec(input)) { + lastIndex = JSXPunctuator.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "<": + stack.push({tag: "JSXTag"}); + break; + case ">": + stack.pop(); + if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { + nextLastSignificantToken = "?JSX"; + postfixIncDec = true; + } else { + stack.push({tag: "JSXChildren"}); + } + break; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + nextLastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + break; + case "/": + if (lastSignificantToken === "<") { + stack.pop(); + if (stack[stack.length - 1].tag === "JSXChildren") { + stack.pop(); + } + stack.push({tag: "JSXTagEnd"}); + } + } + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "JSXPunctuator", + value: match[0] + }); + continue; + } + JSXIdentifier.lastIndex = lastIndex; + if (match = JSXIdentifier.exec(input)) { + lastIndex = JSXIdentifier.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXIdentifier", + value: match[0] + }); + continue; + } + JSXString.lastIndex = lastIndex; + if (match = JSXString.exec(input)) { + lastIndex = JSXString.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXString", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + break; + case "JSXChildren": + JSXText.lastIndex = lastIndex; + if (match = JSXText.exec(input)) { + lastIndex = JSXText.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXText", + value: match[0] + }); + continue; + } + switch (input[lastIndex]) { + case "<": + stack.push({tag: "JSXTag"}); + lastIndex++; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: "<" + }); + continue; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + lastIndex++; + lastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + yield ({ + type: "JSXPunctuator", + value: "{" + }); + continue; + } + } + WhiteSpace.lastIndex = lastIndex; + if (match = WhiteSpace.exec(input)) { + lastIndex = WhiteSpace.lastIndex; + yield ({ + type: "WhiteSpace", + value: match[0] + }); + continue; + } + LineTerminatorSequence.lastIndex = lastIndex; + if (match = LineTerminatorSequence.exec(input)) { + lastIndex = LineTerminatorSequence.lastIndex; + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + yield ({ + type: "LineTerminatorSequence", + value: match[0] + }); + continue; + } + MultiLineComment.lastIndex = lastIndex; + if (match = MultiLineComment.exec(input)) { + lastIndex = MultiLineComment.lastIndex; + if (Newline.test(match[0])) { + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + } + yield ({ + type: "MultiLineComment", + value: match[0], + closed: match[1] !== void 0 + }); + continue; + } + SingleLineComment.lastIndex = lastIndex; + if (match = SingleLineComment.exec(input)) { + lastIndex = SingleLineComment.lastIndex; + postfixIncDec = false; + yield ({ + type: "SingleLineComment", + value: match[0] + }); + continue; + } + firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); + lastIndex += firstCodePoint.length; + lastSignificantToken = firstCodePoint; + postfixIncDec = false; + yield ({ + type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", + value: firstCodePoint + }); + } + return void 0; +}; + +var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokens_1); + +function stripLiteralJsTokens(code, options) { + const FILL = options?.fillChar ?? " "; + const FILL_COMMENT = " "; + let result = ""; + const filter = options?.filter ?? (() => true); + const tokens = []; + for (const token of jsTokens(code, { jsx: false })) { + tokens.push(token); + if (token.type === "SingleLineComment") { + result += FILL_COMMENT.repeat(token.value.length); + continue; + } + if (token.type === "MultiLineComment") { + result += token.value.replace(/[^\n]/g, FILL_COMMENT); + continue; + } + if (token.type === "StringLiteral") { + const body = token.value.slice(1, -1); + if (filter(body)) { + result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1]; + continue; + } + } + if (token.type === "NoSubstitutionTemplate") { + const body = token.value.slice(1, -1); + if (filter(body)) { + result += `\`${body.replace(/[^\n]/g, FILL)}\``; + continue; + } + } + if (token.type === "RegularExpressionLiteral") { + const body = token.value; + if (filter(body)) { + result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`); + continue; + } + } + if (token.type === "TemplateHead") { + const body = token.value.slice(1, -2); + if (filter(body)) { + result += `\`${body.replace(/[^\n]/g, FILL)}\${`; + continue; + } + } + if (token.type === "TemplateTail") { + const body = token.value.slice(0, -2); + if (filter(body)) { + result += `}${body.replace(/[^\n]/g, FILL)}\``; + continue; + } + } + if (token.type === "TemplateMiddle") { + const body = token.value.slice(1, -2); + if (filter(body)) { + result += `}${body.replace(/[^\n]/g, FILL)}\${`; + continue; + } + } + result += token.value; + } + return { + result, + tokens + }; +} + +function stripLiteral(code, options) { + return stripLiteralDetailed(code, options).result; +} +function stripLiteralDetailed(code, options) { + return stripLiteralJsTokens(code, options); +} + +var main$1 = {exports: {}}; + +var name = "dotenv"; +var version$2 = "16.4.4"; +var description = "Loads environment variables from .env file"; +var main = "lib/main.js"; +var types$2 = "lib/main.d.ts"; +var exports = { + ".": { + types: "./lib/main.d.ts", + require: "./lib/main.js", + "default": "./lib/main.js" + }, + "./config": "./config.js", + "./config.js": "./config.js", + "./lib/env-options": "./lib/env-options.js", + "./lib/env-options.js": "./lib/env-options.js", + "./lib/cli-options": "./lib/cli-options.js", + "./lib/cli-options.js": "./lib/cli-options.js", + "./package.json": "./package.json" +}; +var scripts = { + "dts-check": "tsc --project tests/types/tsconfig.json", + lint: "standard", + "lint-readme": "standard-markdown", + pretest: "npm run lint && npm run dts-check", + test: "tap tests/*.js --100 -Rspec", + "test:coverage": "tap --coverage-report=lcov", + prerelease: "npm test", + release: "standard-version" +}; +var repository = { + type: "git", + url: "git://github.com/motdotla/dotenv.git" +}; +var funding = "https://dotenvx.com"; +var keywords$2 = [ + "dotenv", + "env", + ".env", + "environment", + "variables", + "config", + "settings" +]; +var readmeFilename = "README.md"; +var license = "BSD-2-Clause"; +var devDependencies = { + "@definitelytyped/dtslint": "^0.0.133", + "@types/node": "^18.11.3", + decache: "^4.6.1", + sinon: "^14.0.1", + standard: "^17.0.0", + "standard-markdown": "^7.1.0", + "standard-version": "^9.5.0", + tap: "^16.3.0", + tar: "^6.1.11", + typescript: "^4.8.4" +}; +var engines = { + node: ">=12" +}; +var browser$1 = { + fs: false +}; +var require$$4 = { + name: name, + version: version$2, + description: description, + main: main, + types: types$2, + exports: exports, + scripts: scripts, + repository: repository, + funding: funding, + keywords: keywords$2, + readmeFilename: readmeFilename, + license: license, + devDependencies: devDependencies, + engines: engines, + browser: browser$1 +}; + +const fs$9 = require$$0__default; +const path$9 = require$$0$4; +const os$2 = require$$2; +const crypto$1 = require$$0$a; +const packageJson = require$$4; + +const version$1 = packageJson.version; + +const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + +// Parse src into an Object +function parse$a (src) { + const obj = {}; + + // Convert buffer to string + let lines = src.toString(); + + // Convert line breaks to same format + lines = lines.replace(/\r\n?/mg, '\n'); + + let match; + while ((match = LINE.exec(lines)) != null) { + const key = match[1]; + + // Default undefined or null to empty string + let value = (match[2] || ''); + + // Remove whitespace + value = value.trim(); + + // Check if double quoted + const maybeQuote = value[0]; + + // Remove surrounding quotes + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'); + + // Expand newlines if double quoted + if (maybeQuote === '"') { + value = value.replace(/\\n/g, '\n'); + value = value.replace(/\\r/g, '\r'); + } + + // Add to object + obj[key] = value; + } + + return obj +} + +function _parseVault (options) { + const vaultPath = _vaultPath(options); + + // Parse .env.vault + const result = DotenvModule.configDotenv({ path: vaultPath }); + if (!result.parsed) { + const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); + err.code = 'MISSING_DATA'; + throw err + } + + // handle scenario for comma separated keys - for use with key rotation + // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" + const keys = _dotenvKey(options).split(','); + const length = keys.length; + + let decrypted; + for (let i = 0; i < length; i++) { + try { + // Get full key + const key = keys[i].trim(); + + // Get instructions for decrypt + const attrs = _instructions(result, key); + + // Decrypt + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); + + break + } catch (error) { + // last key + if (i + 1 >= length) { + throw error + } + // try next key + } + } + + // Parse decrypted .env string + return DotenvModule.parse(decrypted) +} + +function _log (message) { + console.log(`[dotenv@${version$1}][INFO] ${message}`); +} + +function _warn (message) { + console.log(`[dotenv@${version$1}][WARN] ${message}`); +} + +function _debug (message) { + console.log(`[dotenv@${version$1}][DEBUG] ${message}`); +} + +function _dotenvKey (options) { + // prioritize developer directly setting options.DOTENV_KEY + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY + } + + // secondary infra already contains a DOTENV_KEY environment variable + if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { + return process.env.DOTENV_KEY + } + + // fallback to empty string + return '' +} + +function _instructions (result, dotenvKey) { + // Parse DOTENV_KEY. Format is a URI + let uri; + try { + uri = new URL(dotenvKey); + } catch (error) { + if (error.code === 'ERR_INVALID_URL') { + const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } + + throw error + } + + // Get decrypt key + const key = uri.password; + if (!key) { + const err = new Error('INVALID_DOTENV_KEY: Missing key part'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } + + // Get environment + const environment = uri.searchParams.get('environment'); + if (!environment) { + const err = new Error('INVALID_DOTENV_KEY: Missing environment part'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } + + // Get ciphertext payload + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; + const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION + if (!ciphertext) { + const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); + err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'; + throw err + } + + return { ciphertext, key } +} + +function _vaultPath (options) { + let possibleVaultPath = null; + + if (options && options.path && options.path.length > 0) { + if (Array.isArray(options.path)) { + for (const filepath of options.path) { + if (fs$9.existsSync(filepath)) { + possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`; + } + } + } else { + possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`; + } + } else { + possibleVaultPath = path$9.resolve(process.cwd(), '.env.vault'); + } + + if (fs$9.existsSync(possibleVaultPath)) { + return possibleVaultPath + } + + return null +} + +function _resolveHome (envPath) { + return envPath[0] === '~' ? path$9.join(os$2.homedir(), envPath.slice(1)) : envPath +} + +function _configVault (options) { + _log('Loading env from encrypted .env.vault'); + + const parsed = DotenvModule._parseVault(options); + + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + DotenvModule.populate(processEnv, parsed, options); + + return { parsed } +} + +function configDotenv (options) { + const dotenvPath = path$9.resolve(process.cwd(), '.env'); + let encoding = 'utf8'; + const debug = Boolean(options && options.debug); + + if (options && options.encoding) { + encoding = options.encoding; + } else { + if (debug) { + _debug('No encoding is specified. UTF-8 is used by default'); + } + } + + let optionPathsThatExist = []; + if (options && options.path) { + if (!Array.isArray(options.path)) { + if (fs$9.existsSync(options.path)) { + optionPathsThatExist = [_resolveHome(options.path)]; + } + } else { + for (const filepath of options.path) { + if (fs$9.existsSync(filepath)) { + optionPathsThatExist.push(_resolveHome(filepath)); + } + } + } + + if (!optionPathsThatExist.length) { + optionPathsThatExist = [dotenvPath]; + } + } + + // If we have options.path, and it had valid paths, use them. Else fall back to .env + const pathsToProcess = optionPathsThatExist.length ? optionPathsThatExist : [dotenvPath]; + + // Build the parsed data in a temporary object (because we need to return it). Once we have the final + // parsed data, we will combine it with process.env (or options.processEnv if provided). + + const parsed = {}; + try { + for (const path of pathsToProcess) { + // Specifying an encoding returns a string instead of a buffer + const singleFileParsed = DotenvModule.parse(fs$9.readFileSync(path, { encoding })); + DotenvModule.populate(parsed, singleFileParsed, options); + } + + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + DotenvModule.populate(processEnv, parsed, options); + } catch (e) { + if (debug) { + _debug(`Failed to load ${pathsToProcess} ${e.message}`); + } + return { error: e } + } + return { parsed } +} + +// Populates process.env from .env file +function config (options) { + // fallback to original dotenv if DOTENV_KEY is not set + if (_dotenvKey(options).length === 0) { + return DotenvModule.configDotenv(options) + } + + const vaultPath = _vaultPath(options); + + // dotenvKey exists but .env.vault file does not exist + if (!vaultPath) { + _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); + + return DotenvModule.configDotenv(options) + } + + return DotenvModule._configVault(options) +} + +function decrypt (encrypted, keyStr) { + const key = Buffer.from(keyStr.slice(-64), 'hex'); + let ciphertext = Buffer.from(encrypted, 'base64'); + + const nonce = ciphertext.subarray(0, 12); + const authTag = ciphertext.subarray(-16); + ciphertext = ciphertext.subarray(12, -16); + + try { + const aesgcm = crypto$1.createDecipheriv('aes-256-gcm', key, nonce); + aesgcm.setAuthTag(authTag); + return `${aesgcm.update(ciphertext)}${aesgcm.final()}` + } catch (error) { + const isRange = error instanceof RangeError; + const invalidKeyLength = error.message === 'Invalid key length'; + const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'; + + if (isRange || invalidKeyLength) { + const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)'); + err.code = 'INVALID_DOTENV_KEY'; + throw err + } else if (decryptionFailed) { + const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY'); + err.code = 'DECRYPTION_FAILED'; + throw err + } else { + throw error + } + } +} + +// Populate process.env with parsed values +function populate (processEnv, parsed, options = {}) { + const debug = Boolean(options && options.debug); + const override = Boolean(options && options.override); + + if (typeof parsed !== 'object') { + const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate'); + err.code = 'OBJECT_REQUIRED'; + throw err + } + + // Set process.env + for (const key of Object.keys(parsed)) { + if (Object.prototype.hasOwnProperty.call(processEnv, key)) { + if (override === true) { + processEnv[key] = parsed[key]; + } + + if (debug) { + if (override === true) { + _debug(`"${key}" is already defined and WAS overwritten`); + } else { + _debug(`"${key}" is already defined and was NOT overwritten`); + } + } + } else { + processEnv[key] = parsed[key]; + } + } +} + +const DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config, + decrypt, + parse: parse$a, + populate +}; + +main$1.exports.configDotenv = DotenvModule.configDotenv; +main$1.exports._configVault = DotenvModule._configVault; +main$1.exports._parseVault = DotenvModule._parseVault; +main$1.exports.config = DotenvModule.config; +main$1.exports.decrypt = DotenvModule.decrypt; +var parse_1$1 = main$1.exports.parse = DotenvModule.parse; +main$1.exports.populate = DotenvModule.populate; + +main$1.exports = DotenvModule; + +// * / +// * (\\)? # is it escaped with a backslash? +// * (\$) # literal $ +// * (?!\() # shouldnt be followed by parenthesis +// * (\{?) # first brace wrap opening +// * ([\w.]+) # key +// * (?::-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))? # optional default nested 3 times +// * (\}?) # last brace warp closing +// * /xi + +const DOTENV_SUBSTITUTION_REGEX = /(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi; + +function _resolveEscapeSequences (value) { + return value.replace(/\\\$/g, '$') +} + +function interpolate (value, processEnv, parsed) { + return value.replace(DOTENV_SUBSTITUTION_REGEX, (match, escaped, dollarSign, openBrace, key, defaultValue, closeBrace) => { + if (escaped === '\\') { + return match.slice(1) + } else { + if (processEnv[key]) { + if (processEnv[key] === parsed[key]) { + return processEnv[key] + } else { + // scenario: PASSWORD_EXPAND_NESTED=${PASSWORD_EXPAND} + return interpolate(processEnv[key], processEnv, parsed) + } + } + + if (parsed[key]) { + // avoid recursion from EXPAND_SELF=$EXPAND_SELF + if (parsed[key] === value) { + return parsed[key] + } else { + return interpolate(parsed[key], processEnv, parsed) + } + } + + if (defaultValue) { + if (defaultValue.startsWith('$')) { + return interpolate(defaultValue, processEnv, parsed) + } else { + return defaultValue + } + } + + return '' + } + }) +} + +function expand (options) { + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + for (const key in options.parsed) { + let value = options.parsed[key]; + + const inProcessEnv = Object.prototype.hasOwnProperty.call(processEnv, key); + if (inProcessEnv) { + if (processEnv[key] === options.parsed[key]) { + // assume was set to processEnv from the .env file if the values match and therefore interpolate + value = interpolate(value, processEnv, options.parsed); + } else { + // do not interpolate - assume processEnv had the intended value even if containing a $. + value = processEnv[key]; + } + } else { + // not inProcessEnv so assume interpolation for this .env key + value = interpolate(value, processEnv, options.parsed); + } + + options.parsed[key] = _resolveEscapeSequences(value); + } + + for (const processKey in options.parsed) { + processEnv[processKey] = options.parsed[processKey]; + } + + return options +} + +var expand_1 = expand; + +function getEnvFilesForMode(mode, envDir) { + return [ + /** default file */ `.env`, + /** local file */ `.env.local`, + /** mode file */ `.env.${mode}`, + /** mode local file */ `.env.${mode}.local`, + ].map((file) => normalizePath$3(path$o.join(envDir, file))); +} +function loadEnv(mode, envDir, prefixes = 'VITE_') { + if (mode === 'local') { + throw new Error(`"local" cannot be used as a mode name because it conflicts with ` + + `the .local postfix for .env files.`); + } + prefixes = arraify(prefixes); + const env = {}; + const envFiles = getEnvFilesForMode(mode, envDir); + const parsed = Object.fromEntries(envFiles.flatMap((filePath) => { + if (!tryStatSync(filePath)?.isFile()) + return []; + return Object.entries(parse_1$1(fs$l.readFileSync(filePath))); + })); + // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this + if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) { + process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV; + } + // support BROWSER and BROWSER_ARGS env variables + if (parsed.BROWSER && process.env.BROWSER === undefined) { + process.env.BROWSER = parsed.BROWSER; + } + if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) { + process.env.BROWSER_ARGS = parsed.BROWSER_ARGS; + } + // let environment variables use each other. make a copy of `process.env` so that `dotenv-expand` + // doesn't re-assign the expanded values to the global `process.env`. + const processEnv = { ...process.env }; + expand_1({ parsed, processEnv }); + // only keys that start with prefix are exposed to client + for (const [key, value] of Object.entries(parsed)) { + if (prefixes.some((prefix) => key.startsWith(prefix))) { + env[key] = value; + } + } + // check if there are actual env variables starting with VITE_* + // these are typically provided inline and should be prioritized + for (const key in process.env) { + if (prefixes.some((prefix) => key.startsWith(prefix))) { + env[key] = process.env[key]; + } + } + return env; +} +function resolveEnvPrefix({ envPrefix = 'VITE_', }) { + envPrefix = arraify(envPrefix); + if (envPrefix.includes('')) { + throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`); + } + return envPrefix; +} + +const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'; +const resolvedModulePreloadPolyfillId = '\0' + modulePreloadPolyfillId + '.js'; +function modulePreloadPolyfillPlugin(config) { + // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis` + const skip = config.command !== 'build' || config.build.ssr; + let polyfillString; + return { + name: 'vite:modulepreload-polyfill', + resolveId(id) { + if (id === modulePreloadPolyfillId) { + return resolvedModulePreloadPolyfillId; + } + }, + load(id) { + if (id === resolvedModulePreloadPolyfillId) { + if (skip) { + return ''; + } + if (!polyfillString) { + polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`; + } + return { code: polyfillString, moduleSideEffects: true }; + } + }, + }; +} +function polyfill() { + const relList = document.createElement('link').relList; + if (relList && relList.supports && relList.supports('modulepreload')) { + return; + } + for (const link of document.querySelectorAll('link[rel="modulepreload"]')) { + processPreload(link); + } + new MutationObserver((mutations) => { + for (const mutation of mutations) { + if (mutation.type !== 'childList') { + continue; + } + for (const node of mutation.addedNodes) { + if (node.tagName === 'LINK' && node.rel === 'modulepreload') + processPreload(node); + } + } + }).observe(document, { childList: true, subtree: true }); + function getFetchOpts(link) { + const fetchOpts = {}; + if (link.integrity) + fetchOpts.integrity = link.integrity; + if (link.referrerPolicy) + fetchOpts.referrerPolicy = link.referrerPolicy; + if (link.crossOrigin === 'use-credentials') + fetchOpts.credentials = 'include'; + else if (link.crossOrigin === 'anonymous') + fetchOpts.credentials = 'omit'; + else + fetchOpts.credentials = 'same-origin'; + return fetchOpts; + } + function processPreload(link) { + if (link.ep) + // ep marker = processed + return; + link.ep = true; + // prepopulate the load record + const fetchOpts = getFetchOpts(link); + fetch(link.href, fetchOpts); + } +} + +const htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(js|css)$/; +const isHtmlProxyRE = /\?html-proxy\b/; +const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g; +// Do not allow preceding '.', but do allow preceding '...' for spread operations +const inlineImportRE = /(?]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is; +const moduleScriptRE = /[ \t]*]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i; +const modulePreloadLinkRE = /[ \t]*]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i; +const importMapAppendRE = new RegExp([moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join('|'), 'i'); +const isHTMLProxy = (id) => isHtmlProxyRE.test(id); +const isHTMLRequest = (request) => htmlLangRE.test(request); +// HTML Proxy Caches are stored by config -> filePath -> index +const htmlProxyMap = new WeakMap(); +// HTML Proxy Transform result are stored by config +// `${hash(importer)}_${query.index}` -> transformed css code +// PS: key like `hash(/vite/playground/assets/index.html)_1`) +const htmlProxyResult = new Map(); +function htmlInlineProxyPlugin(config) { + // Should do this when `constructor` rather than when `buildStart`, + // `buildStart` will be triggered multiple times then the cached result will be emptied. + // https://github.com/vitejs/vite/issues/6372 + htmlProxyMap.set(config, new Map()); + return { + name: 'vite:html-inline-proxy', + resolveId(id) { + if (isHTMLProxy(id)) { + return id; + } + }, + load(id) { + const proxyMatch = id.match(htmlProxyRE$1); + if (proxyMatch) { + const index = Number(proxyMatch[1]); + const file = cleanUrl(id); + const url = file.replace(normalizePath$3(config.root), ''); + const result = htmlProxyMap.get(config).get(url)?.[index]; + if (result) { + return result; + } + else { + throw new Error(`No matching HTML proxy module found from ${id}`); + } + } + }, + }; +} +function addToHTMLProxyCache(config, filePath, index, result) { + if (!htmlProxyMap.get(config)) { + htmlProxyMap.set(config, new Map()); + } + if (!htmlProxyMap.get(config).get(filePath)) { + htmlProxyMap.get(config).set(filePath, []); + } + htmlProxyMap.get(config).get(filePath)[index] = result; +} +function addToHTMLProxyTransformResult(hash, code) { + htmlProxyResult.set(hash, code); +} +// this extends the config in @vue/compiler-sfc with +const assetAttrsConfig = { + link: ['href'], + video: ['src', 'poster'], + source: ['src', 'srcset'], + img: ['src', 'srcset'], + image: ['xlink:href', 'href'], + use: ['xlink:href', 'href'], +}; +// Some `` elements should not be inlined in build. Excluding: +// - `shortcut` : only valid for IE <9, use `icon` +// - `mask-icon` : deprecated since Safari 12 (for pinned tabs) +// - `apple-touch-icon-precomposed` : only valid for iOS <7 (for avoiding gloss effect) +const noInlineLinkRels = new Set([ + 'icon', + 'apple-touch-icon', + 'apple-touch-startup-image', + 'manifest', +]); +const isAsyncScriptMap = new WeakMap(); +function nodeIsElement(node) { + return node.nodeName[0] !== '#'; +} +function traverseNodes(node, visitor) { + visitor(node); + if (nodeIsElement(node) || + node.nodeName === '#document' || + node.nodeName === '#document-fragment') { + node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor)); + } +} +async function traverseHtml(html, filePath, visitor) { + // lazy load compiler + const { parse } = await import('./dep-kjUoH5nk.js'); + const ast = parse(html, { + scriptingEnabled: false, + sourceCodeLocationInfo: true, + onParseError: (e) => { + handleParseError(e, html, filePath); + }, + }); + traverseNodes(ast, visitor); +} +function getScriptInfo(node) { + let src; + let sourceCodeLocation; + let isModule = false; + let isAsync = false; + for (const p of node.attrs) { + if (p.prefix !== undefined) + continue; + if (p.name === 'src') { + if (!src) { + src = p; + sourceCodeLocation = node.sourceCodeLocation?.attrs['src']; + } + } + else if (p.name === 'type' && p.value && p.value === 'module') { + isModule = true; + } + else if (p.name === 'async') { + isAsync = true; + } + } + return { src, sourceCodeLocation, isModule, isAsync }; +} +const attrValueStartRE = /=\s*(.)/; +function overwriteAttrValue(s, sourceCodeLocation, newValue) { + const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset); + const valueStart = srcString.match(attrValueStartRE); + if (!valueStart) { + // overwrite attr value can only be called for a well-defined value + throw new Error(`[vite:html] internal error, failed to overwrite attribute value`); + } + const wrapOffset = valueStart[1] === '"' || valueStart[1] === "'" ? 1 : 0; + const valueOffset = valueStart.index + valueStart[0].length - 1; + s.update(sourceCodeLocation.startOffset + valueOffset + wrapOffset, sourceCodeLocation.endOffset - wrapOffset, newValue); + return s; +} +/** + * Format parse5 @type {ParserError} to @type {RollupError} + */ +function formatParseError(parserError, id, html) { + const formattedError = { + code: parserError.code, + message: `parse5 error code ${parserError.code}`, + frame: generateCodeFrame(html, parserError.startOffset, parserError.endOffset), + loc: { + file: id, + line: parserError.startLine, + column: parserError.startCol, + }, + }; + return formattedError; +} +function handleParseError(parserError, html, filePath) { + switch (parserError.code) { + case 'missing-doctype': + // ignore missing DOCTYPE + return; + case 'abandoned-head-element-child': + // Accept elements without closing tag in + return; + case 'duplicate-attribute': + // Accept duplicate attributes #9566 + // The first attribute is used, browsers silently ignore duplicates + return; + case 'non-void-html-element-start-tag-with-trailing-solidus': + // Allow self closing on non-void elements #10439 + return; + } + const parseError = formatParseError(parserError, filePath, html); + throw new Error(`Unable to parse HTML; ${parseError.message}\n` + + ` at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` + + `${parseError.frame}`); +} +/** + * Compiles index.html into an entry js module + */ +function buildHtmlPlugin(config) { + const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins, config.logger); + preHooks.unshift(preImportMapHook(config)); + preHooks.push(htmlEnvHook(config)); + postHooks.push(postImportMapHook()); + const processedHtml = new Map(); + const isExcludedUrl = (url) => url[0] === '#' || isExternalUrl(url) || isDataUrl(url); + // Same reason with `htmlInlineProxyPlugin` + isAsyncScriptMap.set(config, new Map()); + return { + name: 'vite:build-html', + async transform(html, id) { + if (id.endsWith('.html')) { + id = normalizePath$3(id); + const relativeUrlPath = path$o.posix.relative(config.root, id); + const publicPath = `/${relativeUrlPath}`; + const publicBase = getBaseInHTML(relativeUrlPath, config); + const publicToRelative = (filename, importer) => publicBase + filename; + const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(url.slice(1), 'public', relativeUrlPath, 'html', config, publicToRelative); + // Determines true start position for the node, either the < character + // position, or the newline at the end of the previous line's node. + const nodeStartWithLeadingWhitespace = (node) => { + const startOffset = node.sourceCodeLocation.startOffset; + if (startOffset === 0) + return 0; + // Gets the offset for the start of the line including the + // newline trailing the previous node + const lineStartOffset = startOffset - node.sourceCodeLocation.startCol; + // + // + // + // Here we want to target the newline at the end of the previous line + // as the start position for our target. + // + // + // + // + // However, if there is content between our target node start and the + // previous newline, we cannot strip it out without risking content deletion. + let isLineEmpty = false; + try { + const line = s.slice(Math.max(0, lineStartOffset), startOffset); + isLineEmpty = !line.trim(); + } + catch { + // magic-string may throw if there's some content removed in the sliced string, + // which we ignore and assume the line is not empty + } + return isLineEmpty ? lineStartOffset : startOffset; + }; + // pre-transform + html = await applyHtmlTransforms(html, preHooks, { + path: publicPath, + filename: id, + }); + let js = ''; + const s = new MagicString(html); + const scriptUrls = []; + const styleUrls = []; + let inlineModuleIndex = -1; + let everyScriptIsAsync = true; + let someScriptsAreAsync = false; + let someScriptsAreDefer = false; + const assetUrlsPromises = []; + // for each encountered asset url, rewrite original html so that it + // references the post-build location, ignoring empty attributes and + // attributes that directly reference named output. + const namedOutput = Object.keys(config?.build?.rollupOptions?.input || {}); + const processAssetUrl = async (url, shouldInline) => { + if (url !== '' && // Empty attribute + !namedOutput.includes(url) && // Direct reference to named output + !namedOutput.includes(removeLeadingSlash(url)) // Allow for absolute references as named output can't be an absolute path + ) { + try { + return await urlToBuiltUrl(url, id, config, this, shouldInline); + } + catch (e) { + if (e.code !== 'ENOENT') { + throw e; + } + } + } + return url; + }; + await traverseHtml(html, id, (node) => { + if (!nodeIsElement(node)) { + return; + } + let shouldRemove = false; + // script tags + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule, isAsync } = getScriptInfo(node); + const url = src && src.value; + const isPublicFile = !!(url && checkPublicFile(url, config)); + if (isPublicFile) { + // referencing public dir url, prefix with base + overwriteAttrValue(s, sourceCodeLocation, toOutputPublicFilePath(url)); + } + if (isModule) { + inlineModuleIndex++; + if (url && !isExcludedUrl(url) && !isPublicFile) { + // + const filePath = id.replace(normalizePath$3(config.root), ''); + addToHTMLProxyCache(config, filePath, inlineModuleIndex, { + code: contents, + }); + js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`; + shouldRemove = true; + } + everyScriptIsAsync &&= isAsync; + someScriptsAreAsync ||= isAsync; + someScriptsAreDefer ||= !isAsync; + } + else if (url && !isPublicFile) { + if (!isExcludedUrl(url)) { + config.logger.warn(` asset + for (const { start, end, url } of scriptUrls) { + if (checkPublicFile(url, config)) { + s.update(start, end, toOutputPublicFilePath(url)); + } + else if (!isExcludedUrl(url)) { + s.update(start, end, await urlToBuiltUrl(url, id, config, this)); + } + } + // ignore if its url can't be resolved + const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({ + ...styleUrl, + resolved: await this.resolve(styleUrl.url, id), + }))); + for (const { start, end, url, resolved } of resolvedStyleUrls) { + if (resolved == null) { + config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`); + const importExpression = `\nimport ${JSON.stringify(url)}`; + js = js.replace(importExpression, ''); + } + else { + s.remove(start, end); + } + } + processedHtml.set(id, s.toString()); + // inject module preload polyfill only when configured and needed + const { modulePreload } = config.build; + if (modulePreload !== false && + modulePreload.polyfill && + (someScriptsAreAsync || someScriptsAreDefer)) { + js = `import "${modulePreloadPolyfillId}";\n${js}`; + } + // Force rollup to keep this module from being shared between other entry points. + // If the resulting chunk is empty, it will be removed in generateBundle. + return { code: js, moduleSideEffects: 'no-treeshake' }; + } + }, + async generateBundle(options, bundle) { + const analyzedChunk = new Map(); + const inlineEntryChunk = new Set(); + const getImportedChunks = (chunk, seen = new Set()) => { + const chunks = []; + chunk.imports.forEach((file) => { + const importee = bundle[file]; + if (importee?.type === 'chunk' && !seen.has(file)) { + seen.add(file); + // post-order traversal + chunks.push(...getImportedChunks(importee, seen)); + chunks.push(importee); + } + }); + return chunks; + }; + const toScriptTag = (chunk, toOutputPath, isAsync) => ({ + tag: 'script', + attrs: { + ...(isAsync ? { async: true } : {}), + type: 'module', + // crossorigin must be set not only for serving assets in a different origin + // but also to make it possible to preload the script using ``. + // ``); + preTransformRequest(server, modulePath, base); + }; + await traverseHtml(html, filename, (node) => { + if (!nodeIsElement(node)) { + return; + } + // script tags + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule } = getScriptInfo(node); + if (src) { + const processedUrl = processNodeUrl(src.value, isSrcSet(src), config, htmlPath, originalUrl, server, !isModule); + if (processedUrl !== src.value) { + overwriteAttrValue(s, sourceCodeLocation, processedUrl); + } + } + else if (isModule && node.childNodes.length) { + addInlineModule(node, 'js'); + } + else if (node.childNodes.length) { + const scriptNode = node.childNodes[node.childNodes.length - 1]; + for (const { url, start, end, } of extractImportExpressionFromClassicScript(scriptNode)) { + const processedUrl = processNodeUrl(url, false, config, htmlPath, originalUrl); + if (processedUrl !== url) { + s.update(start, end, processedUrl); + } + } + } + } + const inlineStyle = findNeedTransformStyleAttribute(node); + if (inlineStyle) { + inlineModuleIndex++; + inlineStyles.push({ + index: inlineModuleIndex, + location: inlineStyle.location, + code: inlineStyle.attr.value, + }); + } + if (node.nodeName === 'style' && node.childNodes.length) { + const children = node.childNodes[0]; + styleUrl.push({ + start: children.sourceCodeLocation.startOffset, + end: children.sourceCodeLocation.endOffset, + code: children.value, + }); + } + // elements with [href/src] attrs + const assetAttrs = assetAttrsConfig[node.nodeName]; + if (assetAttrs) { + for (const p of node.attrs) { + const attrKey = getAttrKey(p); + if (p.value && assetAttrs.includes(attrKey)) { + const processedUrl = processNodeUrl(p.value, isSrcSet(p), config, htmlPath, originalUrl); + if (processedUrl !== p.value) { + overwriteAttrValue(s, node.sourceCodeLocation.attrs[attrKey], processedUrl); + } + } + } + } + }); + await Promise.all([ + ...styleUrl.map(async ({ start, end, code }, index) => { + const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`; + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url, false); + ensureWatchedFile(watcher, mod.file, config.root); + const result = await server.pluginContainer.transform(code, mod.id); + let content = ''; + if (result) { + if (result.map && 'version' in result.map) { + if (result.map.mappings) { + await injectSourcesContent(result.map, proxyModulePath, config.logger); + } + content = getCodeWithSourcemap('css', result.code, result.map); + } + else { + content = result.code; + } + } + s.overwrite(start, end, content); + }), + ...inlineStyles.map(async ({ index, location, code }) => { + // will transform with css plugin and cache result with css-post plugin + const url = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`; + const mod = await moduleGraph.ensureEntryFromUrl(url, false); + ensureWatchedFile(watcher, mod.file, config.root); + await server?.pluginContainer.transform(code, mod.id); + const hash = getHash(cleanUrl(mod.id)); + const result = htmlProxyResult.get(`${hash}_${index}`); + overwriteAttrValue(s, location, result ?? ''); + }), + ]); + html = s.toString(); + return { + html, + tags: [ + { + tag: 'script', + attrs: { + type: 'module', + src: path$o.posix.join(base, CLIENT_PUBLIC_PATH), + }, + injectTo: 'head-prepend', + }, + ], + }; +}; +function indexHtmlMiddleware(root, server) { + const isDev = isDevServer(server); + const fsUtils = getFsUtils(server.config); + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteIndexHtmlMiddleware(req, res, next) { + if (res.writableEnded) { + return next(); + } + const url = req.url && cleanUrl(req.url); + // htmlFallbackMiddleware appends '.html' to URLs + if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') { + let filePath; + if (isDev && url.startsWith(FS_PREFIX)) { + filePath = decodeURIComponent(fsPathFromId(url)); + } + else { + filePath = path$o.join(root, decodeURIComponent(url)); + } + if (fsUtils.existsSync(filePath)) { + const headers = isDev + ? server.config.server.headers + : server.config.preview.headers; + try { + let html = await fsp.readFile(filePath, 'utf-8'); + if (isDev) { + html = await server.transformIndexHtml(url, html, req.originalUrl); + } + return send(req, res, html, 'html', { headers }); + } + catch (e) { + return next(e); + } + } + } + next(); + }; +} +function preTransformRequest(server, url, base) { + if (!server.config.server.preTransformRequests) + return; + // transform all url as non-ssr as html includes client-side assets only + try { + url = unwrapId(stripBase(decodeURI(url), base)); + } + catch { + // ignore + return; + } + server.warmupRequest(url); +} + +const logTime = createDebugger('vite:time'); +function timeMiddleware(root) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteTimeMiddleware(req, res, next) { + const start = performance.now(); + const end = res.end; + res.end = (...args) => { + logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); + return end.call(res, ...args); + }; + next(); + }; +} + +class ModuleNode { + /** + * Public served url path, starts with / + */ + url; + /** + * Resolved file system path + query + */ + id = null; + file = null; + type; + info; + meta; + importers = new Set(); + clientImportedModules = new Set(); + ssrImportedModules = new Set(); + acceptedHmrDeps = new Set(); + acceptedHmrExports = null; + importedBindings = null; + isSelfAccepting; + transformResult = null; + ssrTransformResult = null; + ssrModule = null; + ssrError = null; + lastHMRTimestamp = 0; + lastInvalidationTimestamp = 0; + /** + * If the module only needs to update its imports timestamp (e.g. within an HMR chain), + * it is considered soft-invalidated. In this state, its `transformResult` should exist, + * and the next `transformRequest` for this module will replace the timestamps. + * + * By default the value is `undefined` if it's not soft/hard-invalidated. If it gets + * soft-invalidated, this will contain the previous `transformResult` value. If it gets + * hard-invalidated, this will be set to `'HARD_INVALIDATED'`. + * @internal + */ + invalidationState; + /** + * @internal + */ + ssrInvalidationState; + /** + * The module urls that are statically imported in the code. This information is separated + * out from `importedModules` as only importers that statically import the module can be + * soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated. + * @internal + */ + staticImportedUrls; + /** + * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870 + */ + constructor(url, setIsSelfAccepting = true) { + this.url = url; + this.type = isDirectCSSRequest(url) ? 'css' : 'js'; + if (setIsSelfAccepting) { + this.isSelfAccepting = false; + } + } + get importedModules() { + const importedModules = new Set(this.clientImportedModules); + for (const module of this.ssrImportedModules) { + importedModules.add(module); + } + return importedModules; + } +} +class ModuleGraph { + resolveId; + urlToModuleMap = new Map(); + idToModuleMap = new Map(); + etagToModuleMap = new Map(); + // a single file may corresponds to multiple modules with different queries + fileToModulesMap = new Map(); + safeModulesPath = new Set(); + /** + * @internal + */ + _unresolvedUrlToModuleMap = new Map(); + /** + * @internal + */ + _ssrUnresolvedUrlToModuleMap = new Map(); + constructor(resolveId) { + this.resolveId = resolveId; + } + async getModuleByUrl(rawUrl, ssr) { + // Quick path, if we already have a module for this rawUrl (even without extension) + rawUrl = removeImportQuery(removeTimestampQuery(rawUrl)); + const mod = this._getUnresolvedUrlToModule(rawUrl, ssr); + if (mod) { + return mod; + } + const [url] = await this._resolveUrl(rawUrl, ssr); + return this.urlToModuleMap.get(url); + } + getModuleById(id) { + return this.idToModuleMap.get(removeTimestampQuery(id)); + } + getModulesByFile(file) { + return this.fileToModulesMap.get(file); + } + onFileChange(file) { + const mods = this.getModulesByFile(file); + if (mods) { + const seen = new Set(); + mods.forEach((mod) => { + this.invalidateModule(mod, seen); + }); + } + } + invalidateModule(mod, seen = new Set(), timestamp = Date.now(), isHmr = false, + /** @internal */ + softInvalidate = false) { + const prevInvalidationState = mod.invalidationState; + const prevSsrInvalidationState = mod.ssrInvalidationState; + // Handle soft invalidation before the `seen` check, as consecutive soft/hard invalidations can + // cause the final soft invalidation state to be different. + // If soft invalidated, save the previous `transformResult` so that we can reuse and transform the + // import timestamps only in `transformRequest`. If there's no previous `transformResult`, hard invalidate it. + if (softInvalidate) { + mod.invalidationState ??= mod.transformResult ?? 'HARD_INVALIDATED'; + mod.ssrInvalidationState ??= mod.ssrTransformResult ?? 'HARD_INVALIDATED'; + } + // If hard invalidated, further soft invalidations have no effect until it's reset to `undefined` + else { + mod.invalidationState = 'HARD_INVALIDATED'; + mod.ssrInvalidationState = 'HARD_INVALIDATED'; + } + // Skip updating the module if it was already invalidated before and the invalidation state has not changed + if (seen.has(mod) && + prevInvalidationState === mod.invalidationState && + prevSsrInvalidationState === mod.ssrInvalidationState) { + return; + } + seen.add(mod); + if (isHmr) { + mod.lastHMRTimestamp = timestamp; + } + else { + // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started + // processing being done for this module + mod.lastInvalidationTimestamp = timestamp; + } + // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline + // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested + const etag = mod.transformResult?.etag; + if (etag) + this.etagToModuleMap.delete(etag); + mod.transformResult = null; + mod.ssrTransformResult = null; + mod.ssrModule = null; + mod.ssrError = null; + mod.importers.forEach((importer) => { + if (!importer.acceptedHmrDeps.has(mod)) { + // If the importer statically imports the current module, we can soft-invalidate the importer + // to only update the import timestamps. If it's not statically imported, e.g. watched/glob file, + // we can only soft invalidate if the current module was also soft-invalidated. A soft-invalidation + // doesn't need to trigger a re-load and re-transform of the importer. + const shouldSoftInvalidateImporter = importer.staticImportedUrls?.has(mod.url) || softInvalidate; + this.invalidateModule(importer, seen, timestamp, isHmr, shouldSoftInvalidateImporter); + } + }); + } + invalidateAll() { + const timestamp = Date.now(); + const seen = new Set(); + this.idToModuleMap.forEach((mod) => { + this.invalidateModule(mod, seen, timestamp); + }); + } + /** + * Update the module graph based on a module's updated imports information + * If there are dependencies that no longer have any importers, they are + * returned as a Set. + * + * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code. + * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing. + */ + async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr, + /** @internal */ + staticImportedUrls) { + mod.isSelfAccepting = isSelfAccepting; + const prevImports = ssr ? mod.ssrImportedModules : mod.clientImportedModules; + let noLongerImported; + let resolvePromises = []; + let resolveResults = new Array(importedModules.size); + let index = 0; + // update import graph + for (const imported of importedModules) { + const nextIndex = index++; + if (typeof imported === 'string') { + resolvePromises.push(this.ensureEntryFromUrl(imported, ssr).then((dep) => { + dep.importers.add(mod); + resolveResults[nextIndex] = dep; + })); + } + else { + imported.importers.add(mod); + resolveResults[nextIndex] = imported; + } + } + if (resolvePromises.length) { + await Promise.all(resolvePromises); + } + const nextImports = new Set(resolveResults); + if (ssr) { + mod.ssrImportedModules = nextImports; + } + else { + mod.clientImportedModules = nextImports; + } + // remove the importer from deps that were imported but no longer are. + prevImports.forEach((dep) => { + if (!mod.clientImportedModules.has(dep) && + !mod.ssrImportedModules.has(dep)) { + dep.importers.delete(mod); + if (!dep.importers.size) { + (noLongerImported || (noLongerImported = new Set())).add(dep); + } + } + }); + // update accepted hmr deps + resolvePromises = []; + resolveResults = new Array(acceptedModules.size); + index = 0; + for (const accepted of acceptedModules) { + const nextIndex = index++; + if (typeof accepted === 'string') { + resolvePromises.push(this.ensureEntryFromUrl(accepted, ssr).then((dep) => { + resolveResults[nextIndex] = dep; + })); + } + else { + resolveResults[nextIndex] = accepted; + } + } + if (resolvePromises.length) { + await Promise.all(resolvePromises); + } + mod.acceptedHmrDeps = new Set(resolveResults); + mod.staticImportedUrls = staticImportedUrls; + // update accepted hmr exports + mod.acceptedHmrExports = acceptedExports; + mod.importedBindings = importedBindings; + return noLongerImported; + } + async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) { + return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting); + } + /** + * @internal + */ + async _ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true, + // Optimization, avoid resolving the same url twice if the caller already did it + resolved) { + // Quick path, if we already have a module for this rawUrl (even without extension) + rawUrl = removeImportQuery(removeTimestampQuery(rawUrl)); + let mod = this._getUnresolvedUrlToModule(rawUrl, ssr); + if (mod) { + return mod; + } + const modPromise = (async () => { + const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, ssr, resolved); + mod = this.idToModuleMap.get(resolvedId); + if (!mod) { + mod = new ModuleNode(url, setIsSelfAccepting); + if (meta) + mod.meta = meta; + this.urlToModuleMap.set(url, mod); + mod.id = resolvedId; + this.idToModuleMap.set(resolvedId, mod); + const file = (mod.file = cleanUrl(resolvedId)); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + fileMappedModules.add(mod); + } + // multiple urls can map to the same module and id, make sure we register + // the url to the existing module in that case + else if (!this.urlToModuleMap.has(url)) { + this.urlToModuleMap.set(url, mod); + } + this._setUnresolvedUrlToModule(rawUrl, mod, ssr); + return mod; + })(); + // Also register the clean url to the module, so that we can short-circuit + // resolving the same url twice + this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr); + return modPromise; + } + // some deps, like a css file referenced via @import, don't have its own + // url because they are inlined into the main css import. But they still + // need to be represented in the module graph so that they can trigger + // hmr in the importing css file. + createFileOnlyEntry(file) { + file = normalizePath$3(file); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + const url = `${FS_PREFIX}${file}`; + for (const m of fileMappedModules) { + if (m.url === url || m.id === file) { + return m; + } + } + const mod = new ModuleNode(url); + mod.file = file; + fileMappedModules.add(mod); + return mod; + } + // for incoming urls, it is important to: + // 1. remove the HMR timestamp query (?t=xxxx) and the ?import query + // 2. resolve its extension so that urls with or without extension all map to + // the same module + async resolveUrl(url, ssr) { + url = removeImportQuery(removeTimestampQuery(url)); + const mod = await this._getUnresolvedUrlToModule(url, ssr); + if (mod?.id) { + return [mod.url, mod.id, mod.meta]; + } + return this._resolveUrl(url, ssr); + } + updateModuleTransformResult(mod, result, ssr) { + if (ssr) { + mod.ssrTransformResult = result; + } + else { + const prevEtag = mod.transformResult?.etag; + if (prevEtag) + this.etagToModuleMap.delete(prevEtag); + mod.transformResult = result; + if (result?.etag) + this.etagToModuleMap.set(result.etag, mod); + } + } + getModuleByEtag(etag) { + return this.etagToModuleMap.get(etag); + } + /** + * @internal + */ + _getUnresolvedUrlToModule(url, ssr) { + return (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).get(url); + } + /** + * @internal + */ + _setUnresolvedUrlToModule(url, mod, ssr) { + (ssr + ? this._ssrUnresolvedUrlToModuleMap + : this._unresolvedUrlToModuleMap).set(url, mod); + } + /** + * @internal + */ + async _resolveUrl(url, ssr, alreadyResolved) { + const resolved = alreadyResolved ?? (await this.resolveId(url, !!ssr)); + const resolvedId = resolved?.id || url; + if (url !== resolvedId && + !url.includes('\0') && + !url.startsWith(`virtual:`)) { + const ext = extname$1(cleanUrl(resolvedId)); + if (ext) { + const pathname = cleanUrl(url); + if (!pathname.endsWith(ext)) { + url = pathname + ext + url.slice(pathname.length); + } + } + } + return [url, resolvedId, resolved?.meta]; + } +} + +function notFoundMiddleware() { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function vite404Middleware(_, res) { + res.statusCode = 404; + res.end(); + }; +} + +function warmupFiles(server) { + const options = server.config.server.warmup; + const root = server.config.root; + if (options?.clientFiles?.length) { + mapFiles(options.clientFiles, root).then((files) => { + for (const file of files) { + warmupFile(server, file, false); + } + }); + } + if (options?.ssrFiles?.length) { + mapFiles(options.ssrFiles, root).then((files) => { + for (const file of files) { + warmupFile(server, file, true); + } + }); + } +} +async function warmupFile(server, file, ssr) { + // transform html with the `transformIndexHtml` hook as Vite internals would + // pre-transform the imported JS modules linked. this may cause `transformIndexHtml` + // plugins to be executed twice, but that's probably fine. + if (file.endsWith('.html')) { + const url = htmlFileToUrl(file, server.config.root); + if (url) { + try { + const html = await fsp.readFile(file, 'utf-8'); + await server.transformIndexHtml(url, html); + } + catch (e) { + // Unexpected error, log the issue but avoid an unhandled exception + server.config.logger.error(`Pre-transform error (${colors$1.cyan(file)}): ${e.message}`, { + error: e, + timestamp: true, + }); + } + } + } + // for other files, pass it through `transformRequest` with warmup + else { + const url = fileToUrl(file, server.config.root); + await server.warmupRequest(url, { ssr }); + } +} +function htmlFileToUrl(file, root) { + const url = path$o.relative(root, file); + // out of root, ignore file + if (url[0] === '.') + return; + // file within root, create root-relative url + return '/' + normalizePath$3(url); +} +function fileToUrl(file, root) { + const url = path$o.relative(root, file); + // out of root, use /@fs/ prefix + if (url[0] === '.') { + return path$o.posix.join(FS_PREFIX, normalizePath$3(file)); + } + // file within root, create root-relative url + return '/' + normalizePath$3(url); +} +function mapFiles(files, root) { + return glob(files, { + cwd: root, + absolute: true, + }); +} + +function createServer(inlineConfig = {}) { + return _createServer(inlineConfig, { hotListen: true }); +} +async function _createServer(inlineConfig = {}, options) { + const config = await resolveConfig(inlineConfig, 'serve'); + const initPublicFilesPromise = initPublicFiles(config); + const { root, server: serverConfig } = config; + const httpsOptions = await resolveHttpsConfig(config.server.https); + const { middlewareMode } = serverConfig; + const resolvedWatchOptions = resolveChokidarOptions(config, { + disableGlobbing: true, + ...serverConfig.watch, + }); + const middlewares = connect$1(); + const httpServer = middlewareMode + ? null + : await resolveHttpServer(serverConfig, middlewares, httpsOptions); + const ws = createWebSocketServer(httpServer, config, httpsOptions); + const hot = createHMRBroadcaster() + .addChannel(ws) + .addChannel(createServerHMRChannel()); + if (typeof config.server.hmr === 'object' && config.server.hmr.channels) { + config.server.hmr.channels.forEach((channel) => hot.addChannel(channel)); + } + if (httpServer) { + setClientErrorHandler(httpServer, config.logger); + } + // eslint-disable-next-line eqeqeq + const watchEnabled = serverConfig.watch !== null; + const watcher = watchEnabled + ? chokidar.watch( + // config file dependencies and env file might be outside of root + [ + root, + ...config.configFileDependencies, + ...getEnvFilesForMode(config.mode, config.envDir), + ], resolvedWatchOptions) + : createNoopWatcher(resolvedWatchOptions); + const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr })); + const container = await createPluginContainer(config, moduleGraph, watcher); + const closeHttpServer = createServerCloseFn(httpServer); + let exitProcess; + const devHtmlTransformFn = createDevHtmlTransformFn(config); + let server = { + config, + middlewares, + httpServer, + watcher, + pluginContainer: container, + ws, + hot, + moduleGraph, + resolvedUrls: null, + ssrTransform(code, inMap, url, originalCode = code) { + return ssrTransform(code, inMap, url, originalCode, server.config); + }, + transformRequest(url, options) { + return transformRequest(url, server, options); + }, + async warmupRequest(url, options) { + await transformRequest(url, server, options).catch((e) => { + if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP || + e?.code === ERR_CLOSED_SERVER) { + // these are expected errors + return; + } + // Unexpected error, log the issue but avoid an unhandled exception + server.config.logger.error(`Pre-transform error: ${e.message}`, { + error: e, + timestamp: true, + }); + }); + }, + transformIndexHtml(url, html, originalUrl) { + return devHtmlTransformFn(server, url, html, originalUrl); + }, + async ssrLoadModule(url, opts) { + return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace); + }, + async ssrFetchModule(url, importer) { + return ssrFetchModule(server, url, importer); + }, + ssrFixStacktrace(e) { + ssrFixStacktrace(e, moduleGraph); + }, + ssrRewriteStacktrace(stack) { + return ssrRewriteStacktrace(stack, moduleGraph); + }, + async reloadModule(module) { + if (serverConfig.hmr !== false && module.file) { + updateModules(module.file, [module], Date.now(), server); + } + }, + async listen(port, isRestart) { + await startServer(server, port); + if (httpServer) { + server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config); + if (!isRestart && config.server.open) + server.openBrowser(); + } + return server; + }, + openBrowser() { + const options = server.config.server; + const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]; + if (url) { + const path = typeof options.open === 'string' + ? new URL(options.open, url).href + : url; + // We know the url that the browser would be opened to, so we can + // start the request while we are awaiting the browser. This will + // start the crawling of static imports ~500ms before. + // preTransformRequests needs to be enabled for this optimization. + if (server.config.server.preTransformRequests) { + setTimeout(() => { + const getMethod = path.startsWith('https:') ? get$1 : get$2; + getMethod(path, { + headers: { + // Allow the history middleware to redirect to /index.html + Accept: 'text/html', + }, + }, (res) => { + res.on('end', () => { + // Ignore response, scripts discovered while processing the entry + // will be preprocessed (server.config.server.preTransformRequests) + }); + }) + .on('error', () => { + // Ignore errors + }) + .end(); + }, 0); + } + openBrowser(path, true, server.config.logger); + } + else { + server.config.logger.warn('No URL available to open in browser'); + } + }, + async close() { + if (!middlewareMode) { + process.off('SIGTERM', exitProcess); + if (process.env.CI !== 'true') { + process.stdin.off('end', exitProcess); + } + } + await Promise.allSettled([ + watcher.close(), + hot.close(), + container.close(), + getDepsOptimizer(server.config)?.close(), + getDepsOptimizer(server.config, true)?.close(), + closeHttpServer(), + ]); + // Await pending requests. We throw early in transformRequest + // and in hooks if the server is closing for non-ssr requests, + // so the import analysis plugin stops pre-transforming static + // imports and this block is resolved sooner. + // During SSR, we let pending requests finish to avoid exposing + // the server closed error to the users. + while (server._pendingRequests.size > 0) { + await Promise.allSettled([...server._pendingRequests.values()].map((pending) => pending.request)); + } + server.resolvedUrls = null; + }, + printUrls() { + if (server.resolvedUrls) { + printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info); + } + else if (middlewareMode) { + throw new Error('cannot print server URLs in middleware mode.'); + } + else { + throw new Error('cannot print server URLs before server.listen is called.'); + } + }, + bindCLIShortcuts(options) { + bindCLIShortcuts(server, options); + }, + async restart(forceOptimize) { + if (!server._restartPromise) { + server._forceOptimizeOnRestart = !!forceOptimize; + server._restartPromise = restartServer(server).finally(() => { + server._restartPromise = null; + server._forceOptimizeOnRestart = false; + }); + } + return server._restartPromise; + }, + _setInternalServer(_server) { + // Rebind internal the server variable so functions reference the user + // server instance after a restart + server = _server; + }, + _restartPromise: null, + _importGlobMap: new Map(), + _forceOptimizeOnRestart: false, + _pendingRequests: new Map(), + _fsDenyGlob: picomatch$4(config.server.fs.deny, { + matchBase: true, + nocase: true, + }), + _shortcutsOptions: undefined, + }; + // maintain consistency with the server instance after restarting. + const reflexServer = new Proxy(server, { + get: (_, property) => { + return server[property]; + }, + set: (_, property, value) => { + server[property] = value; + return true; + }, + }); + if (!middlewareMode) { + exitProcess = async () => { + try { + await server.close(); + } + finally { + process.exit(); + } + }; + process.once('SIGTERM', exitProcess); + if (process.env.CI !== 'true') { + process.stdin.on('end', exitProcess); + } + } + const publicFiles = await initPublicFilesPromise; + const onHMRUpdate = async (file, configOnly) => { + if (serverConfig.hmr !== false) { + try { + await handleHMRUpdate(file, server, configOnly); + } + catch (err) { + hot.send({ + type: 'error', + err: prepareError(err), + }); + } + } + }; + const { publicDir } = config; + const onFileAddUnlink = async (file, isUnlink) => { + file = normalizePath$3(file); + await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' }); + if (publicDir && publicFiles) { + if (file.startsWith(publicDir)) { + const path = file.slice(publicDir.length); + publicFiles[isUnlink ? 'delete' : 'add'](path); + if (!isUnlink) { + const moduleWithSamePath = await moduleGraph.getModuleByUrl(path); + const etag = moduleWithSamePath?.transformResult?.etag; + if (etag) { + // The public file should win on the next request over a module with the + // same path. Prevent the transform etag fast path from serving the module + moduleGraph.etagToModuleMap.delete(etag); + } + } + } + } + await handleFileAddUnlink(file, server, isUnlink); + await onHMRUpdate(file, true); + }; + watcher.on('change', async (file) => { + file = normalizePath$3(file); + await container.watchChange(file, { event: 'update' }); + // invalidate module graph cache on file change + moduleGraph.onFileChange(file); + await onHMRUpdate(file, false); + }); + getFsUtils(config).initWatcher?.(watcher); + watcher.on('add', (file) => { + onFileAddUnlink(file, false); + }); + watcher.on('unlink', (file) => { + onFileAddUnlink(file, true); + }); + hot.on('vite:invalidate', async ({ path, message }) => { + const mod = moduleGraph.urlToModuleMap.get(path); + if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) { + config.logger.info(colors$1.yellow(`hmr invalidate `) + + colors$1.dim(path) + + (message ? ` ${message}` : ''), { timestamp: true }); + const file = getShortName(mod.file, config.root); + updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server, true); + } + }); + if (!middlewareMode && httpServer) { + httpServer.once('listening', () => { + // update actual port since this may be different from initial value + serverConfig.port = httpServer.address().port; + }); + } + // apply server configuration hooks from plugins + const postHooks = []; + for (const hook of config.getSortedPluginHooks('configureServer')) { + postHooks.push(await hook(reflexServer)); + } + // Internal middlewares ------------------------------------------------------ + // request timer + if (process.env.DEBUG) { + middlewares.use(timeMiddleware(root)); + } + // cors (enabled by default) + const { cors } = serverConfig; + if (cors !== false) { + middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); + } + middlewares.use(cachedTransformMiddleware(server)); + // proxy + const { proxy } = serverConfig; + if (proxy) { + const middlewareServer = (isObject$1(serverConfig.middlewareMode) + ? serverConfig.middlewareMode.server + : null) || httpServer; + middlewares.use(proxyMiddleware(middlewareServer, proxy, config)); + } + // base + if (config.base !== '/') { + middlewares.use(baseMiddleware(config.rawBase, middlewareMode)); + } + // open in editor support + middlewares.use('/__open-in-editor', launchEditorMiddleware$1()); + // ping request handler + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + middlewares.use(function viteHMRPingMiddleware(req, res, next) { + if (req.headers['accept'] === 'text/x-vite-ping') { + res.writeHead(204).end(); + } + else { + next(); + } + }); + // serve static files under /public + // this applies before the transform middleware so that these files are served + // as-is without transforms. + if (publicDir) { + middlewares.use(servePublicMiddleware(server, publicFiles)); + } + // main transform middleware + middlewares.use(transformMiddleware(server)); + // serve static files + middlewares.use(serveRawFsMiddleware(server)); + middlewares.use(serveStaticMiddleware(server)); + // html fallback + if (config.appType === 'spa' || config.appType === 'mpa') { + middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa', getFsUtils(config))); + } + // run post config hooks + // This is applied before the html middleware so that user middleware can + // serve custom content instead of index.html. + postHooks.forEach((fn) => fn && fn()); + if (config.appType === 'spa' || config.appType === 'mpa') { + // transform index.html + middlewares.use(indexHtmlMiddleware(root, server)); + // handle 404s + middlewares.use(notFoundMiddleware()); + } + // error handler + middlewares.use(errorMiddleware(server, middlewareMode)); + // httpServer.listen can be called multiple times + // when port when using next port number + // this code is to avoid calling buildStart multiple times + let initingServer; + let serverInited = false; + const initServer = async () => { + if (serverInited) + return; + if (initingServer) + return initingServer; + initingServer = (async function () { + await container.buildStart({}); + // start deps optimizer after all container plugins are ready + if (isDepsOptimizerEnabled(config, false)) { + await initDepsOptimizer(config, server); + } + warmupFiles(server); + initingServer = undefined; + serverInited = true; + })(); + return initingServer; + }; + if (!middlewareMode && httpServer) { + // overwrite listen to init optimizer before server start + const listen = httpServer.listen.bind(httpServer); + httpServer.listen = (async (port, ...args) => { + try { + // ensure ws server started + hot.listen(); + await initServer(); + } + catch (e) { + httpServer.emit('error', e); + return; + } + return listen(port, ...args); + }); + } + else { + if (options.hotListen) { + hot.listen(); + } + await initServer(); + } + return server; +} +async function startServer(server, inlinePort) { + const httpServer = server.httpServer; + if (!httpServer) { + throw new Error('Cannot call server.listen in middleware mode.'); + } + const options = server.config.server; + const hostname = await resolveHostname(options.host); + const configPort = inlinePort ?? options.port; + // When using non strict port for the dev server, the running port can be different from the config one. + // When restarting, the original port may be available but to avoid a switch of URL for the running + // browser tabs, we enforce the previously used port, expect if the config port changed. + const port = (!configPort || configPort === server._configServerPort + ? server._currentServerPort + : configPort) ?? DEFAULT_DEV_PORT; + server._configServerPort = configPort; + const serverPort = await httpServerStart(httpServer, { + port, + strictPort: options.strictPort, + host: hostname.host, + logger: server.config.logger, + }); + server._currentServerPort = serverPort; +} +function createServerCloseFn(server) { + if (!server) { + return () => Promise.resolve(); + } + let hasListened = false; + const openSockets = new Set(); + server.on('connection', (socket) => { + openSockets.add(socket); + socket.on('close', () => { + openSockets.delete(socket); + }); + }); + server.once('listening', () => { + hasListened = true; + }); + return () => new Promise((resolve, reject) => { + openSockets.forEach((s) => s.destroy()); + if (hasListened) { + server.close((err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + } + else { + resolve(); + } + }); +} +function resolvedAllowDir(root, dir) { + return normalizePath$3(path$o.resolve(root, dir)); +} +function resolveServerOptions(root, raw, logger) { + const server = { + preTransformRequests: true, + ...raw, + sourcemapIgnoreList: raw?.sourcemapIgnoreList === false + ? () => false + : raw?.sourcemapIgnoreList || isInNodeModules$1, + middlewareMode: !!raw?.middlewareMode, + }; + let allowDirs = server.fs?.allow; + const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']; + if (!allowDirs) { + allowDirs = [searchForWorkspaceRoot(root)]; + } + allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); + // only push client dir when vite itself is outside-of-root + const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); + if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) { + allowDirs.push(resolvedClientDir); + } + server.fs = { + strict: server.fs?.strict ?? true, + allow: allowDirs, + deny, + cachedChecks: server.fs?.cachedChecks, + }; + if (server.origin?.endsWith('/')) { + server.origin = server.origin.slice(0, -1); + logger.warn(colors$1.yellow(`${colors$1.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`)); + } + return server; +} +async function restartServer(server) { + global.__vite_start_time = performance.now(); + const shortcutsOptions = server._shortcutsOptions; + let inlineConfig = server.config.inlineConfig; + if (server._forceOptimizeOnRestart) { + inlineConfig = mergeConfig(inlineConfig, { + optimizeDeps: { + force: true, + }, + }); + } + // Reinit the server by creating a new instance using the same inlineConfig + // This will triger a reload of the config file and re-create the plugins and + // middlewares. We then assign all properties of the new server to the existing + // server instance and set the user instance to be used in the new server. + // This allows us to keep the same server instance for the user. + { + let newServer = null; + try { + // delay ws server listen + newServer = await _createServer(inlineConfig, { hotListen: false }); + } + catch (err) { + server.config.logger.error(err.message, { + timestamp: true, + }); + server.config.logger.error('server restart failed', { timestamp: true }); + return; + } + await server.close(); + // Assign new server props to existing server instance + const middlewares = server.middlewares; + newServer._configServerPort = server._configServerPort; + newServer._currentServerPort = server._currentServerPort; + Object.assign(server, newServer); + // Keep the same connect instance so app.use(vite.middlewares) works + // after a restart in middlewareMode (.route is always '/') + middlewares.stack = newServer.middlewares.stack; + server.middlewares = middlewares; + // Rebind internal server variable so functions reference the user server + newServer._setInternalServer(server); + } + const { logger, server: { port, middlewareMode }, } = server.config; + if (!middlewareMode) { + await server.listen(port, true); + } + else { + server.hot.listen(); + } + logger.info('server restarted.', { timestamp: true }); + if (shortcutsOptions) { + shortcutsOptions.print = false; + bindCLIShortcuts(server, shortcutsOptions); + } +} +/** + * Internal function to restart the Vite server and print URLs if changed + */ +async function restartServerWithUrls(server) { + if (server.config.server.middlewareMode) { + await server.restart(); + return; + } + const { port: prevPort, host: prevHost } = server.config.server; + const prevUrls = server.resolvedUrls; + await server.restart(); + const { logger, server: { port, host }, } = server.config; + if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || + host !== prevHost || + diffDnsOrderChange(prevUrls, server.resolvedUrls)) { + logger.info(''); + server.printUrls(); + } +} + +var index = { + __proto__: null, + _createServer: _createServer, + createServer: createServer, + createServerCloseFn: createServerCloseFn, + resolveServerOptions: resolveServerOptions, + restartServerWithUrls: restartServerWithUrls +}; + +const debugHmr = createDebugger('vite:hmr'); +const whitespaceRE = /\s/; +const normalizedClientDir = normalizePath$3(CLIENT_DIR); +function getShortName(file, root) { + return file.startsWith(withTrailingSlash(root)) + ? path$o.posix.relative(root, file) + : file; +} +async function handleHMRUpdate(file, server, configOnly) { + const { hot, config, moduleGraph } = server; + const shortFile = getShortName(file, config.root); + const isConfig = file === config.configFile; + const isConfigDependency = config.configFileDependencies.some((name) => file === name); + const isEnv = config.inlineConfig.envFile !== false && + getEnvFilesForMode(config.mode, config.envDir).includes(file); + if (isConfig || isConfigDependency || isEnv) { + // auto restart server + debugHmr?.(`[config change] ${colors$1.dim(shortFile)}`); + config.logger.info(colors$1.green(`${path$o.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true }); + try { + await restartServerWithUrls(server); + } + catch (e) { + config.logger.error(colors$1.red(e)); + } + return; + } + if (configOnly) { + return; + } + debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`); + // (dev only) the client itself cannot be hot updated. + if (file.startsWith(withTrailingSlash(normalizedClientDir))) { + hot.send({ + type: 'full-reload', + path: '*', + }); + return; + } + const mods = moduleGraph.getModulesByFile(file); + // check if any plugin wants to perform custom HMR handling + const timestamp = Date.now(); + const hmrContext = { + file, + timestamp, + modules: mods ? [...mods] : [], + read: () => readModifiedFile(file), + server, + }; + for (const hook of config.getSortedPluginHooks('handleHotUpdate')) { + const filteredModules = await hook(hmrContext); + if (filteredModules) { + hmrContext.modules = filteredModules; + } + } + if (!hmrContext.modules.length) { + // html file cannot be hot updated + if (file.endsWith('.html')) { + config.logger.info(colors$1.green(`page reload `) + colors$1.dim(shortFile), { + clear: true, + timestamp: true, + }); + hot.send({ + type: 'full-reload', + path: config.server.middlewareMode + ? '*' + : '/' + normalizePath$3(path$o.relative(config.root, file)), + }); + } + else { + // loaded but not in the module graph, probably not js + debugHmr?.(`[no modules matched] ${colors$1.dim(shortFile)}`); + } + return; + } + updateModules(shortFile, hmrContext.modules, timestamp, server); +} +function updateModules(file, modules, timestamp, { config, hot, moduleGraph }, afterInvalidation) { + const updates = []; + const invalidatedModules = new Set(); + const traversedModules = new Set(); + let needFullReload = false; + for (const mod of modules) { + const boundaries = []; + const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries); + moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true); + if (needFullReload) { + continue; + } + if (hasDeadEnd) { + needFullReload = hasDeadEnd; + continue; + } + updates.push(...boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({ + type: `${boundary.type}-update`, + timestamp, + path: normalizeHmrUrl(boundary.url), + acceptedPath: normalizeHmrUrl(acceptedVia.url), + explicitImportRequired: boundary.type === 'js' + ? isExplicitImportRequired(acceptedVia.url) + : false, + isWithinCircularImport, + // browser modules are invalidated by changing ?t= query, + // but in ssr we control the module system, so we can directly remove them form cache + ssrInvalidates: getSSRInvalidatedImporters(acceptedVia), + }))); + } + if (needFullReload) { + const reason = typeof needFullReload === 'string' + ? colors$1.dim(` (${needFullReload})`) + : ''; + config.logger.info(colors$1.green(`page reload `) + colors$1.dim(file) + reason, { clear: !afterInvalidation, timestamp: true }); + hot.send({ + type: 'full-reload', + }); + return; + } + if (updates.length === 0) { + debugHmr?.(colors$1.yellow(`no update happened `) + colors$1.dim(file)); + return; + } + config.logger.info(colors$1.green(`hmr update `) + + colors$1.dim([...new Set(updates.map((u) => u.path))].join(', ')), { clear: !afterInvalidation, timestamp: true }); + hot.send({ + type: 'update', + updates, + }); +} +function populateSSRImporters(module, timestamp, seen) { + module.ssrImportedModules.forEach((importer) => { + if (seen.has(importer)) { + return; + } + if (importer.lastHMRTimestamp === timestamp || + importer.lastInvalidationTimestamp === timestamp) { + seen.add(importer); + populateSSRImporters(importer, timestamp, seen); + } + }); + return seen; +} +function getSSRInvalidatedImporters(module) { + return [ + ...populateSSRImporters(module, module.lastHMRTimestamp, new Set()), + ].map((m) => m.file); +} +async function handleFileAddUnlink(file, server, isUnlink) { + const modules = [...(server.moduleGraph.getModulesByFile(file) || [])]; + if (isUnlink) { + for (const deletedMod of modules) { + deletedMod.importedModules.forEach((importedMod) => { + importedMod.importers.delete(deletedMod); + }); + } + } + modules.push(...getAffectedGlobModules(file, server)); + if (modules.length > 0) { + updateModules(getShortName(file, server.config.root), unique(modules), Date.now(), server); + } +} +function areAllImportsAccepted(importedBindings, acceptedExports) { + for (const binding of importedBindings) { + if (!acceptedExports.has(binding)) { + return false; + } + } + return true; +} +function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) { + if (traversedModules.has(node)) { + return false; + } + traversedModules.add(node); + // #7561 + // if the imports of `node` have not been analyzed, then `node` has not + // been loaded in the browser and we should stop propagation. + if (node.id && node.isSelfAccepting === undefined) { + debugHmr?.(`[propagate update] stop propagation because not analyzed: ${colors$1.dim(node.id)}`); + return false; + } + if (node.isSelfAccepting) { + boundaries.push({ + boundary: node, + acceptedVia: node, + isWithinCircularImport: isNodeWithinCircularImports(node, currentChain), + }); + // additionally check for CSS importers, since a PostCSS plugin like + // Tailwind JIT may register any file as a dependency to a CSS file. + for (const importer of node.importers) { + if (isCSSRequest(importer.url) && !currentChain.includes(importer)) { + propagateUpdate(importer, traversedModules, boundaries, currentChain.concat(importer)); + } + } + return false; + } + // A partially accepted module with no importers is considered self accepting, + // because the deal is "there are parts of myself I can't self accept if they + // are used outside of me". + // Also, the imported module (this one) must be updated before the importers, + // so that they do get the fresh imported module when/if they are reloaded. + if (node.acceptedHmrExports) { + boundaries.push({ + boundary: node, + acceptedVia: node, + isWithinCircularImport: isNodeWithinCircularImports(node, currentChain), + }); + } + else { + if (!node.importers.size) { + return true; + } + // #3716, #3913 + // For a non-CSS file, if all of its importers are CSS files (registered via + // PostCSS plugins) it should be considered a dead end and force full reload. + if (!isCSSRequest(node.url) && + [...node.importers].every((i) => isCSSRequest(i.url))) { + return true; + } + } + for (const importer of node.importers) { + const subChain = currentChain.concat(importer); + if (importer.acceptedHmrDeps.has(node)) { + boundaries.push({ + boundary: importer, + acceptedVia: node, + isWithinCircularImport: isNodeWithinCircularImports(importer, subChain), + }); + continue; + } + if (node.id && node.acceptedHmrExports && importer.importedBindings) { + const importedBindingsFromNode = importer.importedBindings.get(node.id); + if (importedBindingsFromNode && + areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) { + continue; + } + } + if (!currentChain.includes(importer) && + propagateUpdate(importer, traversedModules, boundaries, subChain)) { + return true; + } + } + return false; +} +/** + * Check importers recursively if it's an import loop. An accepted module within + * an import loop cannot recover its execution order and should be reloaded. + * + * @param node The node that accepts HMR and is a boundary + * @param nodeChain The chain of nodes/imports that lead to the node. + * (The last node in the chain imports the `node` parameter) + * @param currentChain The current chain tracked from the `node` parameter + * @param traversedModules The set of modules that have traversed + */ +function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = new Set()) { + // To help visualize how each parameters work, imagine this import graph: + // + // A -> B -> C -> ACCEPTED -> D -> E -> NODE + // ^--------------------------| + // + // ACCEPTED: the node that accepts HMR. the `node` parameter. + // NODE : the initial node that triggered this HMR. + // + // This function will return true in the above graph, which: + // `node` : ACCEPTED + // `nodeChain` : [NODE, E, D, ACCEPTED] + // `currentChain` : [ACCEPTED, C, B] + // + // It works by checking if any `node` importers are within `nodeChain`, which + // means there's an import loop with a HMR-accepted module in it. + if (traversedModules.has(node)) { + return false; + } + traversedModules.add(node); + for (const importer of node.importers) { + // Node may import itself which is safe + if (importer === node) + continue; + // a PostCSS plugin like Tailwind JIT may register + // any file as a dependency to a CSS file. + // But in that case, the actual dependency chain is separate. + if (isCSSRequest(importer.url)) + continue; + // Check circular imports + const importerIndex = nodeChain.indexOf(importer); + if (importerIndex > -1) { + // Log extra debug information so users can fix and remove the circular imports + if (debugHmr) { + // Following explanation above: + // `importer` : E + // `currentChain` reversed : [B, C, ACCEPTED] + // `nodeChain` sliced & reversed : [D, E] + // Combined : [E, B, C, ACCEPTED, D, E] + const importChain = [ + importer, + ...[...currentChain].reverse(), + ...nodeChain.slice(importerIndex, -1).reverse(), + ]; + debugHmr(colors$1.yellow(`circular imports detected: `) + + importChain.map((m) => colors$1.dim(m.url)).join(' -> ')); + } + return true; + } + // Continue recursively + if (!currentChain.includes(importer)) { + const result = isNodeWithinCircularImports(importer, nodeChain, currentChain.concat(importer), traversedModules); + if (result) + return result; + } + } + return false; +} +function handlePrunedModules(mods, { hot }) { + // update the disposed modules' hmr timestamp + // since if it's re-imported, it should re-apply side effects + // and without the timestamp the browser will not re-import it! + const t = Date.now(); + mods.forEach((mod) => { + mod.lastHMRTimestamp = t; + debugHmr?.(`[dispose] ${colors$1.dim(mod.file)}`); + }); + hot.send({ + type: 'prune', + paths: [...mods].map((m) => m.url), + }); +} +/** + * Lex import.meta.hot.accept() for accepted deps. + * Since hot.accept() can only accept string literals or array of string + * literals, we don't really need a heavy @babel/parse call on the entire source. + * + * @returns selfAccepts + */ +function lexAcceptedHmrDeps(code, start, urls) { + let state = 0 /* LexerState.inCall */; + // the state can only be 2 levels deep so no need for a stack + let prevState = 0 /* LexerState.inCall */; + let currentDep = ''; + function addDep(index) { + urls.add({ + url: currentDep, + start: index - currentDep.length - 1, + end: index + 1, + }); + currentDep = ''; + } + for (let i = start; i < code.length; i++) { + const char = code.charAt(i); + switch (state) { + case 0 /* LexerState.inCall */: + case 4 /* LexerState.inArray */: + if (char === `'`) { + prevState = state; + state = 1 /* LexerState.inSingleQuoteString */; + } + else if (char === `"`) { + prevState = state; + state = 2 /* LexerState.inDoubleQuoteString */; + } + else if (char === '`') { + prevState = state; + state = 3 /* LexerState.inTemplateString */; + } + else if (whitespaceRE.test(char)) { + continue; + } + else { + if (state === 0 /* LexerState.inCall */) { + if (char === `[`) { + state = 4 /* LexerState.inArray */; + } + else { + // reaching here means the first arg is neither a string literal + // nor an Array literal (direct callback) or there is no arg + // in both case this indicates a self-accepting module + return true; // done + } + } + else if (state === 4 /* LexerState.inArray */) { + if (char === `]`) { + return false; // done + } + else if (char === ',') { + continue; + } + else { + error(i); + } + } + } + break; + case 1 /* LexerState.inSingleQuoteString */: + if (char === `'`) { + addDep(i); + if (prevState === 0 /* LexerState.inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else { + currentDep += char; + } + break; + case 2 /* LexerState.inDoubleQuoteString */: + if (char === `"`) { + addDep(i); + if (prevState === 0 /* LexerState.inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else { + currentDep += char; + } + break; + case 3 /* LexerState.inTemplateString */: + if (char === '`') { + addDep(i); + if (prevState === 0 /* LexerState.inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else if (char === '$' && code.charAt(i + 1) === '{') { + error(i); + } + else { + currentDep += char; + } + break; + default: + throw new Error('unknown import.meta.hot lexer state'); + } + } + return false; +} +function lexAcceptedHmrExports(code, start, exportNames) { + const urls = new Set(); + lexAcceptedHmrDeps(code, start, urls); + for (const { url } of urls) { + exportNames.add(url); + } + return urls.size > 0; +} +function normalizeHmrUrl(url) { + if (url[0] !== '.' && url[0] !== '/') { + url = wrapId(url); + } + return url; +} +function error(pos) { + const err = new Error(`import.meta.hot.accept() can only accept string literals or an ` + + `Array of string literals.`); + err.pos = pos; + throw err; +} +// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file +// change event and sometimes this can be too early and get an empty buffer. +// Poll until the file's modified time has changed before reading again. +async function readModifiedFile(file) { + const content = await fsp.readFile(file, 'utf-8'); + if (!content) { + const mtime = (await fsp.stat(file)).mtimeMs; + for (let n = 0; n < 10; n++) { + await new Promise((r) => setTimeout(r, 10)); + const newMtime = (await fsp.stat(file)).mtimeMs; + if (newMtime !== mtime) { + break; + } + } + return await fsp.readFile(file, 'utf-8'); + } + else { + return content; + } +} +function createHMRBroadcaster() { + const channels = []; + const readyChannels = new WeakSet(); + const broadcaster = { + get channels() { + return [...channels]; + }, + addChannel(channel) { + if (channels.some((c) => c.name === channel.name)) { + throw new Error(`HMR channel "${channel.name}" is already defined.`); + } + channels.push(channel); + return broadcaster; + }, + on(event, listener) { + // emit connection event only when all channels are ready + if (event === 'connection') { + // make a copy so we don't wait for channels that might be added after this is triggered + const channels = this.channels; + channels.forEach((channel) => channel.on('connection', () => { + readyChannels.add(channel); + if (channels.every((c) => readyChannels.has(c))) { + listener(); + } + })); + return; + } + channels.forEach((channel) => channel.on(event, listener)); + return; + }, + off(event, listener) { + channels.forEach((channel) => channel.off(event, listener)); + return; + }, + send(...args) { + channels.forEach((channel) => channel.send(...args)); + }, + listen() { + channels.forEach((channel) => channel.listen()); + }, + close() { + return Promise.all(channels.map((channel) => channel.close())); + }, + }; + return broadcaster; +} +function createServerHMRChannel() { + const innerEmitter = new EventEmitter$4(); + const outsideEmitter = new EventEmitter$4(); + return { + name: 'ssr', + send(...args) { + let payload; + if (typeof args[0] === 'string') { + payload = { + type: 'custom', + event: args[0], + data: args[1], + }; + } + else { + payload = args[0]; + } + outsideEmitter.emit('send', payload); + }, + off(event, listener) { + innerEmitter.off(event, listener); + }, + on: ((event, listener) => { + innerEmitter.on(event, listener); + }), + close() { + innerEmitter.removeAllListeners(); + outsideEmitter.removeAllListeners(); + }, + listen() { + innerEmitter.emit('connection'); + }, + api: { + innerEmitter, + outsideEmitter, + }, + }; +} + +const debug$1 = createDebugger('vite:import-analysis'); +const clientDir = normalizePath$3(CLIENT_DIR); +const skipRE = /\.(?:map|json)(?:$|\?)/; +const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id); +const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/; +const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/; +const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//; +const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/; +const templateLiteralRE = /^\s*`(.*)`\s*$/; +function isExplicitImportRequired(url) { + return !isJSRequest(url) && !isCSSRequest(url); +} +function extractImportedBindings(id, source, importSpec, importedBindings) { + let bindings = importedBindings.get(id); + if (!bindings) { + bindings = new Set(); + importedBindings.set(id, bindings); + } + const isDynamic = importSpec.d > -1; + const isMeta = importSpec.d === -2; + if (isDynamic || isMeta) { + // this basically means the module will be impacted by any change in its dep + bindings.add('*'); + return; + } + const exp = source.slice(importSpec.ss, importSpec.se); + const [match0] = findStaticImports(exp); + if (!match0) { + return; + } + const parsed = parseStaticImport(match0); + if (!parsed) { + return; + } + if (parsed.namespacedImport) { + bindings.add('*'); + } + if (parsed.defaultImport) { + bindings.add('default'); + } + if (parsed.namedImports) { + for (const name of Object.keys(parsed.namedImports)) { + bindings.add(name); + } + } +} +/** + * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. + * + * - Imports are resolved to ensure they exist on disk + * + * - Lexes HMR accept calls and updates import relationships in the module graph + * + * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to + * absolute file paths, e.g. + * + * ```js + * import 'foo' + * ``` + * is rewritten to + * ```js + * import '/@fs//project/node_modules/foo/dist/foo.js' + * ``` + * + * - CSS imports are appended with `.js` since both the js module and the actual + * css (referenced via ``) may go through the transform pipeline: + * + * ```js + * import './style.css' + * ``` + * is rewritten to + * ```js + * import './style.css.js' + * ``` + */ +function importAnalysisPlugin(config) { + const { root, base } = config; + const fsUtils = getFsUtils(config); + const clientPublicPath = path$o.posix.join(base, CLIENT_PUBLIC_PATH); + const enablePartialAccept = config.experimental?.hmrPartialAccept; + let server; + let _env; + let _ssrEnv; + function getEnv(ssr) { + if (!_ssrEnv || !_env) { + const importMetaEnvKeys = {}; + const userDefineEnv = {}; + for (const key in config.env) { + importMetaEnvKeys[key] = JSON.stringify(config.env[key]); + } + for (const key in config.define) { + // non-import.meta.env.* is handled in `clientInjection` plugin + if (key.startsWith('import.meta.env.')) { + userDefineEnv[key.slice(16)] = config.define[key]; + } + } + const env = `import.meta.env = ${serializeDefine({ + ...importMetaEnvKeys, + SSR: '__vite_ssr__', + ...userDefineEnv, + })};`; + _ssrEnv = env.replace('__vite_ssr__', 'true'); + _env = env.replace('__vite_ssr__', 'false'); + } + return ssr ? _ssrEnv : _env; + } + return { + name: 'vite:import-analysis', + configureServer(_server) { + server = _server; + }, + async transform(source, importer, options) { + // In a real app `server` is always defined, but it is undefined when + // running src/node/server/__tests__/pluginContainer.spec.ts + if (!server) { + return null; + } + const ssr = options?.ssr === true; + if (canSkipImportAnalysis(importer)) { + debug$1?.(colors$1.dim(`[skipped] ${prettifyUrl(importer, root)}`)); + return null; + } + const msAtStart = debug$1 ? performance.now() : 0; + await init; + let imports; + let exports; + source = stripBomTag(source); + try { + [imports, exports] = parse$e(source); + } + catch (_e) { + const e = _e; + const { message, showCodeFrame } = createParseErrorInfo(importer, source); + this.error(message, showCodeFrame ? e.idx : undefined); + } + const depsOptimizer = getDepsOptimizer(config, ssr); + const { moduleGraph } = server; + // since we are already in the transform phase of the importer, it must + // have been loaded so its entry is guaranteed in the module graph. + const importerModule = moduleGraph.getModuleById(importer); + if (!importerModule) { + // This request is no longer valid. It could happen for optimized deps + // requests. A full reload is going to request this id again. + // Throwing an outdated error so we properly finish the request with a + // 504 sent to the browser. + throwOutdatedRequest(importer); + } + if (!imports.length && !this._addedImports) { + importerModule.isSelfAccepting = false; + debug$1?.(`${timeFrom(msAtStart)} ${colors$1.dim(`[no imports] ${prettifyUrl(importer, root)}`)}`); + return source; + } + let hasHMR = false; + let isSelfAccepting = false; + let hasEnv = false; + let needQueryInjectHelper = false; + let s; + const str = () => s || (s = new MagicString(source)); + let isPartiallySelfAccepting = false; + const importedBindings = enablePartialAccept + ? new Map() + : null; + const toAbsoluteUrl = (url) => path$o.posix.resolve(path$o.posix.dirname(importerModule.url), url); + const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => { + url = stripBase(url, base); + let importerFile = importer; + const optimizeDeps = getDepOptimizationConfig(config, ssr); + if (moduleListContains(optimizeDeps?.exclude, url)) { + if (depsOptimizer) { + await depsOptimizer.scanProcessing; + // if the dependency encountered in the optimized file was excluded from the optimization + // the dependency needs to be resolved starting from the original source location of the optimized file + // because starting from node_modules/.vite will not find the dependency if it was not hoisted + // (that is, if it is under node_modules directory in the package source of the optimized file) + for (const optimizedModule of depsOptimizer.metadata.depInfoList) { + if (!optimizedModule.src) + continue; // Ignore chunks + if (optimizedModule.file === importerModule.file) { + importerFile = optimizedModule.src; + } + } + } + } + const resolved = await this.resolve(url, importerFile); + if (!resolved || resolved.meta?.['vite:alias']?.noResolved) { + // in ssr, we should let node handle the missing modules + if (ssr) { + return [url, url]; + } + // fix#9534, prevent the importerModuleNode being stopped from propagating updates + importerModule.isSelfAccepting = false; + return this.error(`Failed to resolve import "${url}" from "${normalizePath$3(path$o.relative(process.cwd(), importerFile))}". Does the file exist?`, pos); + } + if (isExternalUrl(resolved.id)) { + return [resolved.id, resolved.id]; + } + const isRelative = url[0] === '.'; + const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer); + // normalize all imports into resolved URLs + // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'` + if (resolved.id.startsWith(withTrailingSlash(root))) { + // in root: infer short absolute path from root + url = resolved.id.slice(root.length); + } + else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || + // vite-plugin-react isn't following the leading \0 virtual module convention. + // This is a temporary hack to avoid expensive fs checks for React apps. + // We'll remove this as soon we're able to fix the react plugins. + (resolved.id !== '/@react-refresh' && + path$o.isAbsolute(resolved.id) && + fsUtils.existsSync(cleanUrl(resolved.id)))) { + // an optimized deps may not yet exists in the filesystem, or + // a regular file exists but is out of root: rewrite to absolute /@fs/ paths + url = path$o.posix.join(FS_PREFIX, resolved.id); + } + else { + url = resolved.id; + } + // if the resolved id is not a valid browser import specifier, + // prefix it to make it valid. We will strip this before feeding it + // back into the transform pipeline + if (url[0] !== '.' && url[0] !== '/') { + url = wrapId(resolved.id); + } + // make the URL browser-valid if not SSR + if (!ssr) { + // mark non-js/css imports with `?import` + if (isExplicitImportRequired(url)) { + url = injectQuery(url, 'import'); + } + else if ((isRelative || isSelfImport) && + !DEP_VERSION_RE.test(url)) { + // If the url isn't a request for a pre-bundled common chunk, + // for relative js/css imports, or self-module virtual imports + // (e.g. vue blocks), inherit importer's version query + // do not do this for unknown type imports, otherwise the appended + // query can break 3rd party plugin's extension checks. + const versionMatch = importer.match(DEP_VERSION_RE); + if (versionMatch) { + url = injectQuery(url, versionMatch[1]); + } + } + // check if the dep has been hmr updated. If yes, we need to attach + // its last updated timestamp to force the browser to fetch the most + // up-to-date version of this module. + try { + // delay setting `isSelfAccepting` until the file is actually used (#7870) + // We use an internal function to avoid resolving the url again + const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), ssr, canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved); + if (depModule.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`); + } + } + catch (e) { + // it's possible that the dep fails to resolve (non-existent import) + // attach location to the missing import + e.pos = pos; + throw e; + } + // prepend base + url = joinUrlSegments(base, url); + } + return [url, resolved.id]; + }; + const orderedImportedUrls = new Array(imports.length); + const orderedAcceptedUrls = new Array(imports.length); + const orderedAcceptedExports = new Array(imports.length); + await Promise.all(imports.map(async (importSpecifier, index) => { + const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: attributeIndex, } = importSpecifier; + // #2083 User may use escape path, + // so use imports[index].n to get the unescaped string + let specifier = importSpecifier.n; + const rawUrl = source.slice(start, end); + // check import.meta usage + if (rawUrl === 'import.meta') { + const prop = source.slice(end, end + 4); + if (prop === '.hot') { + hasHMR = true; + const endHot = end + 4 + (source[end + 4] === '?' ? 1 : 0); + if (source.slice(endHot, endHot + 7) === '.accept') { + // further analyze accepted modules + if (source.slice(endHot, endHot + 14) === '.acceptExports') { + const importAcceptedExports = (orderedAcceptedExports[index] = + new Set()); + lexAcceptedHmrExports(source, source.indexOf('(', endHot + 14) + 1, importAcceptedExports); + isPartiallySelfAccepting = true; + } + else { + const importAcceptedUrls = (orderedAcceptedUrls[index] = + new Set()); + if (lexAcceptedHmrDeps(source, source.indexOf('(', endHot + 7) + 1, importAcceptedUrls)) { + isSelfAccepting = true; + } + } + } + } + else if (prop === '.env') { + hasEnv = true; + } + return; + } + else if (templateLiteralRE.test(rawUrl)) { + // If the import has backticks but isn't transformed as a glob import + // (as there's nothing to glob), check if it's simply a plain string. + // If so, we can replace the specifier as a plain string to prevent + // an incorrect "cannot be analyzed" warning. + if (!(rawUrl.includes('${') && rawUrl.includes('}'))) { + specifier = rawUrl.replace(templateLiteralRE, '$1'); + } + } + const isDynamicImport = dynamicIndex > -1; + // strip import attributes as we can process them ourselves + if (!isDynamicImport && attributeIndex > -1) { + str().remove(end + 1, expEnd); + } + // static import or valid string in dynamic import + // If resolvable, let's resolve it + if (specifier) { + // skip external / data uri + if (isExternalUrl(specifier) || isDataUrl(specifier)) { + return; + } + // skip ssr external + if (ssr) { + if (shouldExternalizeForSSR(specifier, importer, config)) { + return; + } + if (isBuiltin(specifier)) { + return; + } + } + // skip client + if (specifier === clientPublicPath) { + return; + } + // warn imports to non-asset /public files + if (specifier[0] === '/' && + !(config.assetsInclude(cleanUrl(specifier)) || + urlRE.test(specifier)) && + checkPublicFile(specifier, config)) { + throw new Error(`Cannot import non-asset file ${specifier} which is inside /public. ` + + `JS/CSS files inside /public are copied as-is on build and ` + + `can only be referenced via + + + +
+ + +