@flemist/simple-utils 2.0.2 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../urlGet-jyEOC24k.js"),C=require("@flemist/async-utils"),S=require("@flemist/time-limits"),b=require("node:os"),V=require("path"),W=require("@flemist/priority-queue"),ee=require("fs"),te=require("picomatch");function j(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const a in e)if(a!=="default"){const i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,i.get?i:{enumerable:!0,get:()=>e[a]})}}return n.default=e,Object.freeze(n)}const w=j(V),g=j(ee),z=new S.Pool(b.cpus().length);function x(e){return e.replace(/\\/g,"/")}let I=null;function ne(e){I==null&&(I=new Map);const n=x(e);let a=I.get(n);return a==null&&(a=new C.Locker,I.set(n,a)),a}function re(e){const{filePath:n,func:a}=e;return ne(n).lock(()=>S.poolRunWait({pool:z,count:1,func:a}))}function B(e){return e.match(/^[/\\]?[^/\\]+/)[0]}function H(e,n){return B(e)+"|"+n.ino}function $(e){return e.endsWith(":")&&(e+="/"),w.resolve(e)}function _(e,n){e.totalSize+=n.totalSize,e.maxFileDateModified=Math.max(e.maxFileDateModified,n.maxFileDateModified),e.countFiles+=n.countFiles,e.countDirs+=n.countDirs,e.countLinks+=n.countLinks}const J=function(n){return n.code==="ENOENT"};function Q(e){const n=e.paths;if(!n||n.length===0)return Promise.resolve({totalSize:0,maxFileDateModified:0,countFiles:0,countDirs:0,countLinks:0});const a=e.level??0,i=e.walkedIds??new Set,r=e.abortSignal,l=e.pool??z,p=e.handleError,d=e.priority??W.priorityCreate(0),c=e.walkLinks??!1,m=e.log,D=e.handlePath,N=e.matchPath;async function R(L){if(!(p&&await p(L))&&!J(L))throw L}function Y(L){return!(!m||m.minTotalContentSize!=null&&L<m.minTotalContentSize||m.maxNestedLevel!=null&&a>m.maxNestedLevel)}return C.useAbortController(async L=>{const E=C.combineAbortSignals(r,L),T={totalSize:0,maxFileDateModified:0,countFiles:0,countDirs:0,countLinks:0};function q(f,y){if(Y(y.totalSize)){const o=`${y.totalSize.toLocaleString("en-US").replace(/,/g," ").padStart(19)}: ${f}`;m?.handleLog?m.handleLog(o):console.log(o)}}async function G(f,y,k,o){return D?await S.poolRunWait({pool:l,func:async()=>{try{return await D({level:a,path:f,stat:y,itemStat:k,totalStat:T,abortSignal:E})}catch(u){return await R(u),!1}},count:1,priority:o,abortSignal:E}):!0}async function O(f,y,k,o){o||(o=f);const u=await S.poolRunWait({pool:l,func:()=>g.promises.lstat(f).catch(R),count:1,priority:W.priorityCreate(y,W.priorityCreate(1,d)),abortSignal:E});if(!u||!k&&u.isFile())return null;const U=H(f,u);if(i.has(U))return null;i.add(U);let s={totalSize:u.size,maxFileDateModified:u.isDirectory()?0:u.mtimeMs,countFiles:0,countDirs:0,countLinks:0};const M=W.priorityCreate(y,W.priorityCreate(u.isDirectory()?2:3,d));if(u.isSymbolicLink()){if(c){const h=await S.poolRunWait({pool:l,func:()=>g.promises.readlink(f).catch(R).then(F=>F??null),count:1,priority:M,abortSignal:E});if(h){const F=w.isAbsolute(h)?h:w.resolve(w.dirname(o),h),v=await O(F,y,k,o);v&&(s=v)}}return(k||s.countFiles+s.countDirs+s.countLinks>=1)&&(s.countLinks+=1,await G(o,u,s,M)&&(_(T,s),q(o,s))),s}else if(u.isDirectory()){const h=await S.poolRunWait({pool:l,func:()=>g.promises.readdir(f).catch(R),count:1,priority:d,abortSignal:E});if(h){for(let F=0,v=h.length;F<v;F++)h[F]=w.join(o,h[F]);s=await Q({...e,paths:h,abortSignal:E,priority:M,level:a+1,walkedIds:i})}}return(k||s.countFiles+s.countDirs+s.countLinks>=1)&&(u.isDirectory()?s.countDirs+=1:u.isFile()&&(s.countFiles+=1),await G(o,u,s,M)&&(_(T,s),q(o,s))),s}const A=[];for(let f=0,y=n.length;f<y;f++){const k=$(n[f]),o=N?N(k):!0;o!==!1&&A.push(O(k,f,o))}return await Promise.all(A),T})}function ae(e){return Q(e)}function ie({globs:e,rootDir:n,noCase:a}){const i=[];return e.forEach(r=>{r=x(r).trim();const l=r.startsWith("^");l&&(r=r.substring(1).trim());const p=r.startsWith("!");if(p&&(r=r.substring(1).trim()),r.startsWith("!")||r.startsWith("^"))throw new Error(`Invalid glob pattern: "${r}". The syntax '${r.substring(0,2)}' is not supported. Valid glob patterns use: * (match any characters), ** (match any directories), ? (match single character), [abc] (character class), ! (negate pattern), ^ (exclude if included). Examples of valid patterns: "*.js", "src/**/*.ts", "!node_modules", "^dist". Avoid starting with '!' after '^' or multiple special prefixes.`);r.startsWith("/")&&(r="."+r);const d=x(n?w.resolve(n,r):r);if(!d)return;let c;try{c=te(d,{nocase:a??!1,dot:!0,strictBrackets:!0})}catch(m){throw new Error(`Invalid glob pattern: "${r}". ${m instanceof Error?m.message:"Unknown error"}. Valid glob patterns use: * (match any characters), ** (match any directories), ? (match single character), [abc] (character class with balanced brackets), ! (negate pattern), ^ (exclude if included). Examples: "*.js", "src/**/*.ts", "!node_modules", "[abc]def.txt". Ensure all brackets [ ] are properly closed and balanced.`)}i.push({exclude:l,negative:p,debugInfo:d,match:c})}),function(l){l=x(l);let p=null,d=!1;for(let c=0,m=i.length;c<m;c++){const D=i[c];D.match(l)&&(D.exclude?d=!D.negative:(p=!D.negative,d=!1))}return d?!1:p}}function X(e){const n=e.startsWith("!");return n&&(e=e.substring(1)),e.startsWith("/")?e=e.substring(1):!e.startsWith("**")&&!e.startsWith("../")&&(e=`**/${e}`),n&&(e="!"+e),e}function Z(e,n){if(!n||n===".")return e;const a=e.startsWith("^");a&&(e=e.substring(1));const i=e.startsWith("!");return i&&(e=e.substring(1)),e.startsWith("/")?(n.endsWith("/")&&(n=n.substring(0,n.length-1)),e=n+e):(n.endsWith("/")||(n+="/"),e.startsWith("./")?e=n+e.substring(2):e.startsWith("../")?e=n+e:(n.startsWith("..")&&(n=""),e.startsWith("**")?e=n+e:e=n+"**/"+e)),e=x(w.normalize(e)),i&&(e="!"+e),a&&(e="^"+e),e}function P(e){return"^"+e}async function K(e){const a=(await g.promises.readFile(e,"utf-8")).split(`
2
- `),i=[];return a.forEach(r=>{r=r.trim(),!(!r||r.startsWith("#"))&&i.push(r)}),i}async function se(e){const n=e.rootDir??".",a=[];if(!e.globs?.length)return a;const i=[];return e.globs.forEach(r=>{r.value&&(r.valueType==="file-contains-patterns"?i.push(r):r.valueType==="pattern"&&a.push(r.exclude?P(r.value):r.value))}),i.length&&await Promise.all(i.map(async r=>{await S.poolRunWait({pool:z,count:1,func:async()=>{const l=w.resolve(n,r.value),p=await K(l),d=w.relative(n,w.dirname(l));p.forEach(c=>{c=X(c),c=Z(c,d),a.push(r.exclude?P(c):c)})}})})),a}exports.ConsoleMessageLevel=t.ConsoleMessageLevel;exports.Lazy=t.Lazy;exports.LazyWithId=t.LazyWithId;exports.Random=t.Random;exports.UNIQUE_PSEUDO_RANDOM_MAX_COUNT=t.UNIQUE_PSEUDO_RANDOM_MAX_COUNT;exports.alertReplace=t.alertReplace;exports.consoleReplace=t.consoleReplace;exports.convertTimeZone=t.convertTimeZone;exports.createUniquePseudoRandom=t.createUniquePseudoRandom;exports.dateNowUnique=t.dateNowUnique;exports.deepCloneJsonLike=t.deepCloneJsonLike;exports.deepEqualJsonLike=t.deepEqualJsonLike;exports.deepEqualJsonLikeMap=t.deepEqualJsonLikeMap;exports.equalArray=t.equalArray;exports.escapeHtml=t.escapeHtml;exports.escapeRegExp=t.escapeRegExp;exports.fixStackTrace=t.fixStackTrace;exports.formatAny=t.formatAny;exports.formatDate=t.formatDate;exports.formatDateFileName=t.formatDateFileName;exports.getDateInet=t.getDateInet;exports.getNormalizedObject=t.getNormalizedObject;exports.getRandomFunc=t.getRandomFunc;exports.getRandomSeed=t.getRandomSeed;exports.getStackTrace=t.getStackTrace;exports.max=t.max;exports.min=t.min;exports.minMax=t.minMax;exports.numberMod=t.numberMod;exports.randomBoolean=t.randomBoolean;exports.randomEnum=t.randomEnum;exports.randomFloat=t.randomFloat;exports.randomIndexWeighted=t.randomIndexWeighted;exports.randomInt=t.randomInt;exports.randomItem=t.randomItem;exports.randomItems=t.randomItems;exports.setFuncName=t.setFuncName;exports.sha256=t.sha256;exports.sha256Buffer=t.sha256Buffer;exports.timeoutAbortController=t.timeoutAbortController;exports.toHex=t.toHex;exports.truncateString=t.truncateString;exports.urlGetBoolean=t.urlGetBoolean;exports.urlGetFloat=t.urlGetFloat;exports.urlGetInt=t.urlGetInt;exports.urlGetParams=t.urlGetParams;exports.urlGetString=t.urlGetString;exports.urlParamToBoolean=t.urlParamToBoolean;exports.urlParamToFloat=t.urlParamToFloat;exports.urlParamToInt=t.urlParamToInt;exports.withConsoleReplace=t.withConsoleReplace;exports.withTimeout=t.withTimeout;exports.createMatchPath=ie;exports.fileLock=re;exports.getDrive=B;exports.getFileId=H;exports.globGitIgnoreToPicomatch=X;exports.globToRelative=Z;exports.loadGlobs=se;exports.loadGlobsFromFile=K;exports.pathNormalize=x;exports.pathResolve=$;exports.poolFs=z;exports.walkPathHandleErrorDefault=J;exports.walkPaths=ae;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../urlGet-BOGFUahf.js"),$=require("@flemist/async-utils"),M=require("@flemist/time-limits"),Ie=require("node:os"),ne=require("path"),J=require("@flemist/priority-queue"),Te=require("fs"),Fe=require("picomatch"),K=require("child_process"),Re=require("@flemist/abort-controller-fast");function ue(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const o in e)if(o!=="default"){const s=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:()=>e[o]})}}return t.default=e,Object.freeze(t)}const F=ue(ne),R=ue(Te),ee=new M.Pool(Ie.cpus().length);function B(e){return e.replace(/\\/g,"/")}let H=null;function _e(e){H==null&&(H=new Map);const t=B(e);let o=H.get(t);return o==null&&(o=new $.Locker,H.set(t,o)),o}function Ne(e){const{filePath:t,func:o}=e;return _e(t).lock(()=>M.poolRunWait({pool:ee,count:1,func:o}))}function fe(e){return e.match(/^[/\\]?[^/\\]+/)[0]}function he(e,t){return fe(e)+"|"+t.ino}function de(e){return e.endsWith(":")&&(e+="/"),F.resolve(e)}function ce(e,t){e.totalSize+=t.totalSize,e.maxFileDateModified=Math.max(e.maxFileDateModified,t.maxFileDateModified),e.countFiles+=t.countFiles,e.countDirs+=t.countDirs,e.countLinks+=t.countLinks}const me=function(t){return t.code==="ENOENT"};function ye(e){const t=e.paths;if(!t||t.length===0)return Promise.resolve({totalSize:0,maxFileDateModified:0,countFiles:0,countDirs:0,countLinks:0});const o=e.level??0,s=e.walkedIds??new Set,r=e.abortSignal,i=e.pool??ee,a=e.handleError,c=e.priority??J.priorityCreate(0),f=e.walkLinks??!1,l=e.log,E=e.handlePath,h=e.matchPath;async function w(d){if(!(a&&await a(d))&&!me(d))throw d}function j(d){return!(!l||l.minTotalContentSize!=null&&d<l.minTotalContentSize||l.maxNestedLevel!=null&&o>l.maxNestedLevel)}return $.useAbortController(async d=>{const g=$.combineAbortSignals(r,d),y={totalSize:0,maxFileDateModified:0,countFiles:0,countDirs:0,countLinks:0};function I(S,P){if(j(P.totalSize)){const b=`${P.totalSize.toLocaleString("en-US").replace(/,/g," ").padStart(19)}: ${S}`;l?.handleLog?l.handleLog(b):console.log(b)}}async function u(S,P,p,b){return E?await M.poolRunWait({pool:i,func:async()=>{try{return await E({level:o,path:S,stat:P,itemStat:p,totalStat:y,abortSignal:g})}catch(k){return await w(k),!1}},count:1,priority:b,abortSignal:g}):!0}async function O(S,P,p,b){b||(b=S);const k=await M.poolRunWait({pool:i,func:()=>R.promises.lstat(S).catch(w),count:1,priority:J.priorityCreate(P,J.priorityCreate(1,c)),abortSignal:g});if(!k||!p&&k.isFile())return null;const A=he(S,k);if(s.has(A))return null;s.add(A);let m={totalSize:k.size,maxFileDateModified:k.isDirectory()?0:k.mtimeMs,countFiles:0,countDirs:0,countLinks:0};const D=J.priorityCreate(P,J.priorityCreate(k.isDirectory()?2:3,c));if(k.isSymbolicLink()){if(f){const C=await M.poolRunWait({pool:i,func:()=>R.promises.readlink(S).catch(w).then(T=>T??null),count:1,priority:D,abortSignal:g});if(C){const T=F.isAbsolute(C)?C:F.resolve(F.dirname(b),C),_=await O(T,P,p,b);_&&(m=_)}}return(p||m.countFiles+m.countDirs+m.countLinks>=1)&&(m.countLinks+=1,await u(b,k,m,D)&&(ce(y,m),I(b,m))),m}else if(k.isDirectory()){const C=await M.poolRunWait({pool:i,func:()=>R.promises.readdir(S).catch(w),count:1,priority:c,abortSignal:g});if(C){for(let T=0,_=C.length;T<_;T++)C[T]=F.join(b,C[T]);m=await ye({...e,paths:C,abortSignal:g,priority:D,level:o+1,walkedIds:s})}}return(p||m.countFiles+m.countDirs+m.countLinks>=1)&&(k.isDirectory()?m.countDirs+=1:k.isFile()&&(m.countFiles+=1),await u(b,k,m,D)&&(ce(y,m),I(b,m))),m}const x=[];for(let S=0,P=t.length;S<P;S++){const p=de(t[S]),b=h?h(p):!0;b!==!1&&x.push(O(p,S,b))}return await Promise.all(x),y})}function We(e){return ye(e)}function Me({globs:e,rootDir:t,noCase:o}){const s=[];return e.forEach(r=>{r=B(r).trim();const i=r.startsWith("^");i&&(r=r.substring(1).trim());const a=r.startsWith("!");if(a&&(r=r.substring(1).trim()),r.startsWith("!")||r.startsWith("^"))throw new Error(`Invalid glob pattern: "${r}". The syntax '${r.substring(0,2)}' is not supported. Valid glob patterns use: * (match any characters), ** (match any directories), ? (match single character), [abc] (character class), ! (negate pattern), ^ (exclude if included). Examples of valid patterns: "*.js", "src/**/*.ts", "!node_modules", "^dist". Avoid starting with '!' after '^' or multiple special prefixes.`);r.startsWith("/")&&(r="."+r);const c=B(t?F.resolve(t,r):r);if(!c)return;let f;try{f=Fe(c,{nocase:o??!1,dot:!0,strictBrackets:!0})}catch(l){throw new Error(`Invalid glob pattern: "${r}". ${l instanceof Error?l.message:"Unknown error"}. Valid glob patterns use: * (match any characters), ** (match any directories), ? (match single character), [abc] (character class with balanced brackets), ! (negate pattern), ^ (exclude if included). Examples: "*.js", "src/**/*.ts", "!node_modules", "[abc]def.txt". Ensure all brackets [ ] are properly closed and balanced.`)}s.push({exclude:i,negative:a,debugInfo:c,match:f})}),function(i){i=B(i);let a=null,c=!1;for(let f=0,l=s.length;f<l;f++){const E=s[f];E.match(i)&&(E.exclude?c=!E.negative:(a=!E.negative,c=!1))}return c?!1:a}}function pe(e){const t=e.startsWith("!");return t&&(e=e.substring(1)),e.startsWith("/")?e=e.substring(1):!e.startsWith("**")&&!e.startsWith("../")&&(e=`**/${e}`),t&&(e="!"+e),e}function we(e,t){if(!t||t===".")return e;const o=e.startsWith("^");o&&(e=e.substring(1));const s=e.startsWith("!");return s&&(e=e.substring(1)),e.startsWith("/")?(t.endsWith("/")&&(t=t.substring(0,t.length-1)),e=t+e):(t.endsWith("/")||(t+="/"),e.startsWith("./")?e=t+e.substring(2):e.startsWith("../")?e=t+e:(t.startsWith("..")&&(t=""),e.startsWith("**")?e=t+e:e=t+"**/"+e)),e=B(F.normalize(e)),s&&(e="!"+e),o&&(e="^"+e),e}function le(e){return"^"+e}async function ge(e){const o=(await R.promises.readFile(e,"utf-8")).split(`
2
+ `),s=[];return o.forEach(r=>{r=r.trim(),!(!r||r.startsWith("#"))&&s.push(r)}),s}async function Be(e){const t=e.rootDir??".",o=[];if(!e.globs?.length)return o;const s=[];return e.globs.forEach(r=>{r.value&&(r.valueType==="file-contains-patterns"?s.push(r):r.valueType==="pattern"&&o.push(r.exclude?le(r.value):r.value))}),s.length&&await Promise.all(s.map(async r=>{await M.poolRunWait({pool:ee,count:1,func:async()=>{const i=F.resolve(t,r.value),a=await ge(i),c=F.relative(t,F.dirname(i));a.forEach(f=>{f=pe(f),f=we(f,c),o.push(r.exclude?le(f):f)})}})})),o}function be(e,t={}){return new Promise((o,s)=>{const r=K.spawn(e,{shell:!0,...t}),i=[];r.stdout.on("data",a=>{i.push(a)}),r.on("error",a=>{s(a)}),r.on("exit",a=>{const c=Buffer.concat(i).toString("utf8");if(a!==0){s(new Error(`[exec][exit] code: ${a}`));return}o(c)})})}async function $e(){let e;switch(process.platform){case"darwin":e=K.spawn("afplay",["/System/Library/Sounds/Ping.aiff"],{stdio:"ignore"});break;case"linux":e=K.spawn("beep",[],{stdio:"ignore",shell:!0});break;case"win32":e=K.spawn("powershell",["-c","[console]::beep(1000,300)"],{stdio:"ignore"});break;default:throw new Error(`[nodeBeep] Beep not supported on platform: ${process.platform}`)}await new Promise((t,o)=>{e.on("error",o),e.on("close",s=>{s!==0?o(new Error(`[nodeBeep] Beep process exited with code ${s}`)):t()})})}async function Se({page:e,urlFilters:t,timeouts:o}){return o||(o={}),o.downloadInternal||(o.downloadInternal=10*1e3),o.downloadExternal||(o.downloadExternal=60*1e3),o.total||(o.total=300*1e3),await n.withTimeout(()=>e.evaluate(({urlFilters:r,timeouts:i})=>{function a(l){return function(h){let w=!1;for(let j=0,d=l.length;j<d;j++){const g=l[j];g.pattern.test(h)&&(w=g.value)}return w}}const c=r&&a(r);let f=performance.getEntries&&performance.getEntries();return f||(f=[]),f.push({name:location.href}),Promise.all(f.map(l=>{if(l.entryType!=null&&l.entryType!=="resource"||c&&!c(l.name))return null;if(l.responseStatus!=null)return l.responseStatus>=400?Promise.resolve({url:l.name,error:l.responseStatus}):null;if(navigator.userAgent.indexOf("Chrome")===-1)return null;const E=typeof AbortController<"u"?new AbortController:null,h=new URL(l.name).origin===location.origin,w=h?i.downloadInternal:i.downloadExternal;let j;const d=new Promise((u,O)=>{j=O}),g=w&&setTimeout(()=>{E?.abort(),j(new Error("[test][getPageHttpErrors] fetch timeout"))},w);let y=fetch(l.name,{mode:h?"same-origin":"no-cors",signal:E?.signal,cache:h?"force-cache":void 0,method:"HEAD"}).then(u=>u.ok?null:{url:l.name,error:u.status+" "+u.statusText}).catch(u=>({url:l.name,error:u.message}));E||(y=Promise.race([y,d]));function I(){g&&clearTimeout(g)}return y.then(u=>(I(),u),u=>{throw I(),u})})).then(l=>{const E=l.filter(h=>h).map(h=>({url:new URL(h.url),error:h.error}));return E.length>0?E:null})},{urlFilters:t,timeouts:o}),{timeout:o.total})}async function Ee({page:e,urlFilters:t,errorFilter:o}){let s=await Se({page:e,urlFilters:t});if(s&&(o&&(s=s.filter(o)),s.length>0))throw new Error(`[test][checkPageHttpErrors] Page has http errors: ${JSON.stringify(s,null,2)}`)}async function Oe({page:e,filter:t,onError:o}){const s="callback_191b355ea6f64499a6607ad571da5d4d",r=e.context().browser()?.browserType().name(),i=n.getStackTrace();function a(c){try{if(t&&!t({url:new URL(e.url()),error:c}))return}catch(f){c=String(f)}try{console.error(`[test][subscribeJsErrors] BROWSER JS ERROR (${r}): ${c}`);const f=new Error(c);f.stack=i,o(f)}catch(f){console.error("[test][subscribeJsErrors] error",f)}}await e.exposeFunction(s,a),await e.addInitScript(c=>{function f(h){if(Array.isArray(h))return h.map(f).join(`\r
3
+ \r
4
+ `);if(h instanceof Error)return h.stack||h.toString();if(typeof h=="object"&&h!=null){const w=new Set;return JSON.stringify(h,(j,d)=>{if(typeof d=="object"&&d!=null){if(w.has(d))return"[Circular]";w.add(d)}return d},2)}return String(h)}function l(h){window[c](h)}const E={warn:console.warn.bind(console),error:console.error.bind(console)};console.warn=function(...w){return l("console.warn: "+f(w)),E.warn.apply(this,w)},console.error=function(...w){return l("console.error: "+f(w)),E.error.apply(this,w)},window.addEventListener("error",function(h){l("window error: "+(h.message||JSON.stringify(h)))},!0),window.addEventListener("unhandledrejection",function(h){l("window unhandledrejection: "+f(h.reason))},!0)},s)}async function xe(){try{process.platform==="win32"&&await be(`wmic process where "commandline like '%ms-playwright%' and not commandline like '%wmic.exe%' and priority != 4" CALL setpriority "idle"`)}catch(e){const t=e?.message?.trim();if(/exit code: 2147749890/.test(t))return;console.warn("[test][setPlaywrightPriorityLow] error: "+t)}}let V=null,te=null;function ze(e){te=e}function ke(){if(V)return;const e=te||(process.env.DELAY_ON_ERROR?parseInt(process.env.DELAY_ON_ERROR,10):0);if(te)return console.log(`[test][delayOnError] Delay on error: ${e} ms`),V=$.delay(e),V}function ve(){return V}async function Pe(e){const{page:t}=e,o=t.context().browser()?.browserType().name(),s=new Re.AbortControllerFast,r=$.combineAbortSignals(s.signal,e.abortSignal),i=c=>{let f=`Error in (${o}) ${t.url()}
5
+ `;e.pageFilePath&&(f+=` at _ (${ne.resolve(e.pageFilePath)}:0:0)
6
+ `),c.stack=f+(c.stack||c.message),c.message=f+c.message,console.error("[test][initPage] error",c),s.abort(c)};return await Oe({page:t,filter:e.filters?.js?.filter,onError:i}),{abortSignal:r,checkErrors:async()=>{await Ee({page:t,urlFilters:e.filters?.http?.urlFilters,errorFilter:e.filters?.http?.errorFilter}),r.throwIfAborted()}}}async function Je({page:e,abortSignal:t,filters:o,func:s,pageFilePath:r}){const i=e.context().browser()?.browserType().name();try{const{abortSignal:a,checkErrors:c}=await Pe({page:e,abortSignal:t,filters:o,pageFilePath:r});await s({page:e,abortSignal:a,checkErrors:c}),await c()}catch(a){let c=`Error in (${i}) ${e.url()}
7
+ `;throw r&&(c+=` at _ (${ne.resolve(r)}:0:0)
8
+ `),a.stack=c+(a.stack||a.message),a.message=c+a.message,a}}function Ue({browserType:e,options:t}){return async function(s){const r=await e.launch(t??void 0);try{return await s(r)}finally{await r.close()}}}function Ge({browser:e,options:t}){return async function(s){const r=await e.newContext(t??void 0);await xe();try{const i=await s(r);return await r.close(),i}catch(i){const a=ke?.();throw a?(console.error("[test][useBrowserContext] error",i),a.finally(()=>r.close())):await r.close(),i}}}async function Q(e,t){const o=F.dirname(e);await R.promises.stat(o).catch(()=>null)||await R.promises.mkdir(o,{recursive:!0}),await R.promises.writeFile(e,JSON.stringify(t,null,4),{encoding:"utf-8"})}async function je(e){if(!await R.promises.stat(e).catch(()=>null))return null;const t=await R.promises.readFile(e,{encoding:"utf-8"});return JSON.parse(t)}const X="-",Z="+";function U(e,t,o){if(e===t)return null;if(Array.isArray(e)){if(Array.isArray(t)){let r=null;for(let i=0,a=Math.max(t.length,t.length);i<a;i++){const c=U(e[i],t[i],o);c!=null&&(r||(r=[]),r.push(c))}return r!=null&&o&&(r=o(e,t,r)),r}}else if(e instanceof Object&&t instanceof Object){let r=null;for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const a=U(e[i],t[i],o);a!=null&&(r||(r={}),r[i]=a)}for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&!Object.prototype.hasOwnProperty.call(e,i)){const a=U(e[i],t[i],o);a!=null&&(r||(r={}),r[i]=a)}return r!=null&&o&&(r=o(e,t,r)),r}let s={[X]:e,[Z]:t};return o&&(s=o(e,t,s)),s}function re(e){function t(u){return u.sort((O,x)=>O[0]>x[0]?1:-1).reduce((O,x)=>(O[x[0]]=x[1],O),{})}function o(u){return u.reduce((O,x)=>(O[x]=!0,O),{})}const s=e.filters&&e.filters.excludeAttrs&&o(e.filters.excludeAttrs),r=e.filters&&e.filters.fixAttrs,i=e.filters&&e.filters.fixStyles,a=e.filters&&e.filters.excludeStyles&&o(e.filters.excludeStyles),c=e.filters&&e.filters.fixTags,f=e.filters&&e.filters.excludeClasses,l=e.filters&&e.filters.excludeIds,E=e.filters&&e.filters.excludeSelectorClasses,h=e.filters&&e.filters.excludeSelectorIds;let w;if(e.filters&&e.filters.excludeSelectors&&e.filters.excludeSelectors.length>0){const u=Array.from(document.querySelectorAll(e.filters.excludeSelectors.join(",")));u.length>0&&(w=new Set(u))}function j(u,O,x,S){const P=getComputedStyle(u,O),p=[];for(let b=0,k=P.length;b<k;b++){const A=P[b];if(a&&a[A])continue;let m=P[A];if(m&&i)for(let D=0,C=i.length;D<C;D++)i[D].name.test(A)&&(m=m.replace(i[D].search,i[D].replace));(!x||x[A]!==m)&&(!S||S[A]===m)&&p.push([A,m])}return t(p)}function d(u,O,x){return{_:j(u,void 0,O&&O._,x&&x._),before:j(u,"before",O&&O.before,x&&x.before),after:j(u,"after",O&&O.after,x&&x.after)}}function g(u,O,x,S,P){for(let p=0,b=u.childNodes.length;p<b;p++){const k=u.childNodes[p];if(!k)throw new Error(`child is null; index=${p}; ${S}, ${u.className}\r
9
+ You should wait js executions before test`);k instanceof Element&&y(k,O,x,S,P)}}function y(u,O,x,S,P){const p=P&&P[O.length];if(P&&!p||w&&w.has(u))return;let b=u.tagName&&u.tagName.toLowerCase();if(b==="head"&&(x=!1),c)for(let L=0,z=c.length;L<z;L++)b=b.replace(c[L].search,c[L].replace);if(p&&p.tag!==b)return;const k=[];for(let L=0,z=u.attributes.length;L<z;L++){const N=u.attributes.item(L);let W=N.name,q=N.value;if(W=W.toLowerCase(),W!=="class"&&!(s&&s[W])){if(r)for(let v=0,Le=r.length;v<Le;v++)r[v].name.test(W)&&(q=q.replace(r[v].search,r[v].replace));(!p||p.attrs&&p.attrs[W]===q)&&k.push([W,q])}}const A=[],m=[];for(let L=0,z=u.classList.length;L<z;L++){const N=u.classList.item(L);(!f||!f.test(N))&&A.push(N),(!E||!E.test(N))&&m.push(N)}const D=x?d(u,e.defaultStyle,p&&p.style):null,C=u.childElementCount?[]:null;u.id&&(!l||!l.test(u.id))&&u.id;const T=u.id&&(!h||!h.test(u.id))?u.id:"",_=(b||"")+(T?"#"+T:"")+(m.length>0?"."+m.join("."):""),ae=_?S?S+" > "+_:_:S,De={tag:b,selector:ae,classes:A,attrs:k.length>0?t(k):null,style:D,childs:C};O.push(De),C&&g(u,C,x,ae,p&&p.childs)}const I=[];return y(document.documentElement,I,!0,"",e.shouldEqualResult&&[e.shouldEqualResult]),I[0]}async function oe(e){const t=await e.context().newCDPSession(e);return await t.send("DOM.enable"),await t.send("CSS.enable"),t}async function se(e){await e.send("CSS.disable"),await e.send("DOM.disable"),await e.detach()}async function qe(e,t){const o=await oe(e);try{return await t(o)}finally{await se(o)}}async function Ce(e,t){const{nodes:o}=await e.send("DOM.getFlattenedDocument",{depth:-1,pierce:!0}),s=o.filter(r=>r.nodeType===1).map(r=>r.nodeId);for(const r of s)await e.send("CSS.forcePseudoState",{nodeId:r,forcedPseudoClasses:t})}function Y(e,t){if(!e||!t)return t||null;let o=null;for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==e[s]&&(o||(o={}),o[s]=t[s]);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&!Object.prototype.hasOwnProperty.call(t,s)&&(o||(o={}),o[s]="");return o}function He(e,t){if(!e||!t)return t||null;const o=Y(e._,t._),s=Y(e.before,t.before),r=Y(e.after,t.after);return!o&&!s&&!r?null:{_:o||{},before:s||{},after:r||{}}}function Ke(e,t){if(!e||!t)return t||null;if(e.length!==t.length)return t;for(let o=0,s=e.length;o<s;o++)if(e[o]!==t[o])return t;return null}function ie(e,t){const o=Ke(e.classes,t.classes),s=Y(e.attrs,t.attrs),r=He(e.style,t.style);let i=null;if(e.childs&&t.childs){const a=Math.min(e.childs.length,t.childs.length);for(let c=0;c<a;c++){const f=ie(e.childs[c],t.childs[c]);if(f){if(!i){i=[];for(let l=0;l<a;l++)i.push({})}i[c]=f}}}return!o&&!s&&!r&&!i?null:{tag:t.tag,selector:t.selector,classes:o,attrs:s,style:r,childs:i}}const G=(e,t,o,s)=>{const r=s(e,t,o,s);if(r==null)return r;if(Array.isArray(r))return r.map((i,a,c)=>G(i,a,c,s));if(typeof r=="object"){const i={};for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&(i[a]=G(r[a],a,r,s));return i}return r};function Ae(e,t){if(e.attrs&&t.excludeAttrs){for(let o=0,s=t.excludeAttrs.length;o<s;o++)delete e.attrs[t.excludeAttrs[o]];Object.keys(e.attrs).length===0&&(e.attrs=null)}if(e.classes&&t.excludeClasses&&(e.classes=e.classes.filter(o=>!t.excludeClasses.test(o))),e.style&&t.excludeStyles)for(const o of["_","before","after"]){const s=e.style[o];if(s)for(let r=0,i=t.excludeStyles.length;r<i;r++)delete s[t.excludeStyles[r]]}if(e.childs)for(let o=0,s=e.childs.length;o<s;o++)Ae(e.childs[o],t)}function Ve(e,t){for(const o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;const s=e[o];for(const r in s){if(!Object.prototype.hasOwnProperty.call(s,r))continue;const i=s[r];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&Ae(i[a],t)}}}function Qe({actualResultFile:e,expectedResultFile:t,diffResultFile:o,filters:s,transform:r,pseudoStates:i}){let a,c,f,l={};return{async init(E){a=await je(t),r&&(a=G(a,null,null,r)),a&&s&&Ve(a,s),await E.goto("about:blank"),c=await E.evaluate(re,{filters:s}),f=c.style},async handlePage({page:E,testId:h,url:w,stateId:j,_filters:d}){let g=l[h];g||(g={},l[h]=g);let y=g[w.href];y||(y={},g[w.href]=y),await E.addStyleTag({content:"*, *::before, *::after { animation-name: none!important; transition-duration: 0s !important; }"});const I=i??[{states:[]}];let u=null,O;try{for(let x=0;x<I.length;x++){const S=I[x],P=S.states.length>0?j+":"+S.states.join(":"):j;let p=null;if(S.states.length>0){u||(u=await oe(E));const m=performance.now();await Ce(u,S.states),p=performance.now()-m}S.delay&&await $.delay(S.delay);const b=performance.now(),k=await E.evaluate(re,{filters:d||s,defaultStyle:f,shouldEqualResult:y[P]}),A=performance.now()-b;if(console.log(`SNAPSHOT ${P}:`+(p!=null?` forcePseudoClasses ${p.toFixed(0)}ms,`:"")+` getAllElements ${A.toFixed(0)}ms`),!O)O=k,y[P]=k;else{const m=ie(O,k);m&&(y[P]=m)}}}finally{u&&await se(u)}},async end({checkExistUrlsOnly:E}){if(l=n.getNormalizedObject(l),r&&(l=G(l,null,null,r)),a){let h,w;if(!E)h=a,w=l;else{h={},w={};for(const d in a)if(Object.prototype.hasOwnProperty.call(a,d)&&Object.prototype.hasOwnProperty.call(l,d)){h[d]={},w[d]={};for(const g in a[d])Object.prototype.hasOwnProperty.call(a[d],g)&&Object.prototype.hasOwnProperty.call(l[d],g)&&(h[d][g]=a[d][g],w[d][g]=l[d][g])}}const j=U(h,w,(d,g,y)=>y.selector&&(delete y.selector,Object.keys(y).length===0)?null:y.childs&&y.childs.length===1?y.childs[0]:(g&&g.selector?y[Z]?y[Z]=g.selector:y={selector:g.selector,...y}:d&&d.selector&&(y[X]?y[X]=d.selector:y={selector:d.selector,...y}),y));if(o&&await Q(o,j||{}),j)throw await Q(e,l),console.error("Pages elements changes: "+JSON.stringify(j,null,4).substring(0,5e3)),new Error("Pages elements changes detected");await R.promises.stat(e).catch(()=>null)&&await R.promises.unlink(e)}else await Q(t,l);return l}}}exports.ConsoleMessageLevel=n.ConsoleMessageLevel;exports.Lazy=n.Lazy;exports.LazyWithId=n.LazyWithId;exports.LogLevel=n.LogLevel;exports.Random=n.Random;exports.Subject=n.Subject;exports.SubjectWithId=n.SubjectWithId;exports.UNIQUE_PSEUDO_RANDOM_MAX_COUNT=n.UNIQUE_PSEUDO_RANDOM_MAX_COUNT;exports.alertConsole=n.alertConsole;exports.alertReplace=n.alertReplace;exports.check=n.check;exports.consoleIntercept=n.consoleIntercept;exports.consoleMessageToString=n.consoleMessageToString;exports.consoleReplace=n.consoleReplace;exports.convertTimeZone=n.convertTimeZone;exports.createTaskDelayRetry=n.createTaskDelayRetry;exports.createUniquePseudoRandom=n.createUniquePseudoRandom;exports.dateNowUnique=n.dateNowUnique;exports.deepCloneJsonLike=n.deepCloneJsonLike;exports.deepEqualJsonLike=n.deepEqualJsonLike;exports.deepEqualJsonLikeMap=n.deepEqualJsonLikeMap;exports.equalArray=n.equalArray;exports.escapeHtml=n.escapeHtml;exports.escapeRegExp=n.escapeRegExp;exports.fixStackTrace=n.fixStackTrace;exports.formatAny=n.formatAny;exports.formatDate=n.formatDate;exports.formatDateFileName=n.formatDateFileName;exports.getConsoleMessages=n.getConsoleMessages;exports.getDateInet=n.getDateInet;exports.getNormalizedObject=n.getNormalizedObject;exports.getRandomFunc=n.getRandomFunc;exports.getRandomSeed=n.getRandomSeed;exports.getStackTrace=n.getStackTrace;exports.isObservable=n.isObservable;exports.match=n.match;exports.matchAnd=n.matchAnd;exports.matchAndPipe=n.matchAndPipe;exports.matchAny=n.matchAny;exports.matchArray=n.matchArray;exports.matchArrayBuffer=n.matchArrayBuffer;exports.matchArrayIncludes=n.matchArrayIncludes;exports.matchArrayItem=n.matchArrayItem;exports.matchArrayLength=n.matchArrayLength;exports.matchArrayWith=n.matchArrayWith;exports.matchBoolean=n.matchBoolean;exports.matchConstructor=n.matchConstructor;exports.matchConvert=n.matchConvert;exports.matchCustom=n.matchCustom;exports.matchDeep=n.matchDeep;exports.matchEnum=n.matchEnum;exports.matchFloat=n.matchFloat;exports.matchIn=n.matchIn;exports.matchInstanceOf=n.matchInstanceOf;exports.matchInt=n.matchInt;exports.matchIntDate=n.matchIntDate;exports.matchIs=n.matchIs;exports.matchIsNonStrict=n.matchIsNonStrict;exports.matchNever=n.matchNever;exports.matchNot=n.matchNot;exports.matchNotNullish=n.matchNotNullish;exports.matchNullish=n.matchNullish;exports.matchNumber=n.matchNumber;exports.matchObject=n.matchObject;exports.matchObjectEntries=n.matchObjectEntries;exports.matchObjectEntry=n.matchObjectEntry;exports.matchObjectKey=n.matchObjectKey;exports.matchObjectKeyValue=n.matchObjectKeyValue;exports.matchObjectKeys=n.matchObjectKeys;exports.matchObjectKeysNotNull=n.matchObjectKeysNotNull;exports.matchObjectPartial=n.matchObjectPartial;exports.matchObjectValue=n.matchObjectValue;exports.matchObjectValues=n.matchObjectValues;exports.matchObjectWith=n.matchObjectWith;exports.matchOptional=n.matchOptional;exports.matchOr=n.matchOr;exports.matchOrPipe=n.matchOrPipe;exports.matchRange=n.matchRange;exports.matchRangeDate=n.matchRangeDate;exports.matchRef=n.matchRef;exports.matchString=n.matchString;exports.matchStringLength=n.matchStringLength;exports.matchTypeOf=n.matchTypeOf;exports.matchUuid=n.matchUuid;exports.matchValueState=n.matchValueState;exports.max=n.max;exports.min=n.min;exports.minMax=n.minMax;exports.numberMod=n.numberMod;exports.randomBoolean=n.randomBoolean;exports.randomEnum=n.randomEnum;exports.randomFloat=n.randomFloat;exports.randomIndexWeighted=n.randomIndexWeighted;exports.randomInt=n.randomInt;exports.randomItem=n.randomItem;exports.randomItems=n.randomItems;exports.setFuncName=n.setFuncName;exports.sha256=n.sha256;exports.sha256Buffer=n.sha256Buffer;exports.timeoutAbortController=n.timeoutAbortController;exports.toHex=n.toHex;exports.truncateString=n.truncateString;exports.urlGetBoolean=n.urlGetBoolean;exports.urlGetFloat=n.urlGetFloat;exports.urlGetInt=n.urlGetInt;exports.urlGetParams=n.urlGetParams;exports.urlGetString=n.urlGetString;exports.urlParamToBoolean=n.urlParamToBoolean;exports.urlParamToFloat=n.urlParamToFloat;exports.urlParamToInt=n.urlParamToInt;exports.waitObservable=n.waitObservable;exports.withConsoleReplace=n.withConsoleReplace;exports.withRetry=n.withRetry;exports.withTimeout=n.withTimeout;exports.DIFF_NEW=Z;exports.DIFF_OLD=X;exports.checkPageHttpErrors=Ee;exports.createCDPSession=oe;exports.createMatchPath=Me;exports.createPagesElementsChangesTest=Qe;exports.delayOnErrorCall=ke;exports.delayOnErrorSet=ze;exports.delayOnErrorWait=ve;exports.destroyCDPSession=se;exports.exec=be;exports.fileLock=Ne;exports.forcePseudoClasses=Ce;exports.getAllElements=re;exports.getDrive=fe;exports.getElementsStyleDiff=ie;exports.getFileId=he;exports.getObjectsDiff=U;exports.getPageHttpErrors=Se;exports.globGitIgnoreToPicomatch=pe;exports.globToRelative=we;exports.initPage=Pe;exports.loadGlobs=Be;exports.loadGlobsFromFile=ge;exports.loadJson=je;exports.nodeBeep=$e;exports.objectTransform=G;exports.pathNormalize=B;exports.pathResolve=de;exports.poolFs=ee;exports.saveJson=Q;exports.setPlaywrightPriorityLow=xe;exports.subscribeJsErrors=Oe;exports.testPage=Je;exports.useBrowser=Ue;exports.useBrowserContext=Ge;exports.usingCDPSession=qe;exports.walkPathHandleErrorDefault=me;exports.walkPaths=We;
@@ -1,2 +1,4 @@
1
1
  export * from '../common';
2
2
  export * from './fs';
3
+ export * from './process';
4
+ export * from './test';