@chromaui/test-archiver
Advanced tools
Comparing version
@@ -18,3 +18,3 @@ 'use strict'; | ||
var v=Object.defineProperty;var O=(i,t,e)=>t in i?v(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var c=(i,t)=>v(i,"name",{value:t,configurable:!0});var a=(i,t,e)=>(O(i,typeof t!="symbol"?t+"":t,e),e);var n=process.env.LOG?console:{log:(...i)=>{},warn:(...i)=>{}};var S=class{constructor(t,e,r){a(this,"url");a(this,"response");a(this,"shortenedFileNameLength");a(this,"pageUrl");this.url=new URL(t),this.response=e,this.shortenedFileNameLength=250,this.pageUrl=new URL(r);}originalSrc(){return this.url.toString()}toFileSystemPath(){let t=this.url.pathname;return t=this.preserveExternalDomain(this.url),t=this.ensureNonDirectory(t),t=this.encodeQueryString(t),t=this.truncateFileName(t),t=this.removeSpecialChars(t),t=this.addExtension(t),t}ensureNonDirectory(t){return t.endsWith("/")?`${t}index.html`:t}encodeQueryString(t){let e=this.url.search;if(!e)return t;let r=this.hash(e);return `${t}-${r}`}truncateFileName(t){let e=t.split("/"),r=[];return e.forEach((s,o)=>{let h=s;s.length>this.shortenedFileNameLength&&(h=s.substring(0,this.shortenedFileNameLength),n.log(`Chunk of filename '${s}' is too long. Shortening to '${h}'`)),r.push(h);}),`${t.startsWith("/")?"/":""}${E__default.default.join(...r)}`}removeSpecialChars(t){return t.replace(/[%]/g,"")}addExtension(t){if("error"in this.response||!this.response.contentType)return t;let e=t;if(!E__default.default.extname(e)){let r=___default.default.getExtension(this.response.contentType);r&&(e=`${t}.${r}`);}return e}preserveExternalDomain(t){return t.origin===this.pageUrl.origin?t.pathname:`/${encodeURIComponent(t.host)}/${t.pathname}`}hash(t){return crypto.createHash("md5").update(t).digest("hex")}};c(S,"ArchiveFile");var j=/url\((?!['"]?(?:data):)['"]?([^'")]*)['"]?\)/gi,y=class{constructor(t){a(this,"snapshot");if(Buffer.isBuffer(t)){let e=t.toString("utf-8");this.snapshot=JSON.parse(e);}else this.snapshot=JSON.parse(t);}async mapAssetPaths(t){let e=await this.mapNode(this.snapshot,t);return JSON.stringify(e)}async mapNode(t,e){return t=this.mapNodeAttributes(t,e),t=this.mapTextElement(t,e),"childNodes"in t&&(t.childNodes=await Promise.all(t.childNodes.map(async r=>this.mapNode(r,e)))),t}mapNodeAttributes(t,e){if(t.type===rrwebSnapshot.NodeType.Element){if(t.attributes.src){let r=t.attributes.src;e.has(r)&&(t.attributes.src=e.get(r));}if(t.attributes.style){let r=t.attributes.style,s=this.mapCssUrls(r,e);t.attributes.style=s;}if(t.attributes._cssText){let r=t.attributes._cssText,s=this.mapCssUrls(r,e);t.attributes._cssText=s;}if(t.tagName==="img"&&t.attributes.srcset){let r=t.attributes.srcset,s=this.mapSrcsetUrls(r,e);s&&(t.attributes.src=s,delete t.attributes.srcset,delete t.attributes.sizes);}}return t}mapTextElement(t,e){if(t.type===rrwebSnapshot.NodeType.Text&&t.isStyle&&t.textContent){let r=this.mapCssUrls(t.textContent,e);t.textContent=r;}return t}mapCssUrls(t,e){return t.replace(j,(r,s)=>{let o=r;return e.has(s)&&(o=r.replace(s,e.get(s))),o})}mapSrcsetUrls(t,e){let r=P__default.default.parse(t),s;return r.forEach(o=>{e.has(o.url)&&(s=e.get(o.url));}),s}};c(y,"DOMSnapshot");var N=c(i=>i.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,""),"sanitize");async function F(i,t,e,r){let{title:s,outputDir:o,pageUrl:h}=i,l=E.join(o,"..","chromatic-archives"),u=E.join(l,"archive");await fsExtra.ensureDir(l),n.log(`Writing test results for "${s}"`);let w=new Map;await Promise.all(Object.entries(e).map(async([m,p])=>{if("error"in p)return;let b=new S(m,p,h),g=b.originalSrc(),R=b.toFileSystemPath();g!==R&&w.set(g,R),await fsExtra.outputFile(E.join(u,R),p.body);})),await Promise.all(await Object.entries(t).map(async([m,p])=>{let g=await new y(p).mapAssetPaths(w);await fsExtra.outputFile(E.join(u,`${N(s)}-${N(m)}.snapshot.json`),g);})),await D(E.join(l,`${N(s)}.stories.json`),s,t,r);let d=Object.entries(e).filter(([,m])=>"error"in m);d.length>0&&(n.log(`Encountered ${d.length} errors archiving resources, writing to 'errors.json'`),await fsExtra.outputJson(E.join(u,"errors.json"),{errors:Object.fromEntries(d)}));}c(F,"writeTestResult");async function D(i,t,e,r){n.log(`Writing ${i}`),await fsExtra.outputJson(i,{title:t,stories:Object.keys(e).map(s=>({name:s,parameters:{server:{id:`${N(t)}-${N(s)}.snapshot.json`},chromatic:{...r}}}))});}c(D,"writeStoriesFile");var T=class{constructor(t,e=1e4,r){a(this,"archive",{});a(this,"client");a(this,"globalNetworkTimeoutMs");a(this,"allowedArchiveOrigins");a(this,"firstUrl");a(this,"closed",!1);a(this,"globalNetworkTimerId",null);a(this,"globalNetworkResolver");this.client=t,this.globalNetworkTimeoutMs=e,this.allowedArchiveOrigins=(r||[]).map(s=>`https://${s}`);}async watch(){this.client.on("Network.requestWillBeSent",this.requestWillBeSent.bind(this)),this.client.on("Network.responseReceived",this.responseReceived.bind(this)),this.client.on("Fetch.requestPaused",this.requestPaused.bind(this)),await this.client.send("Fetch.enable");}async idle(t){let r=[new Promise((s,o)=>{this.globalNetworkResolver=s,this.globalNetworkTimerId=setTimeout(()=>{n.warn(`Global timeout of ${this.globalNetworkTimeoutMs}ms reached`),this.globalNetworkResolver();},this.globalNetworkTimeoutMs);})];if(t){let s=t.waitForLoadState("networkidle").finally(()=>{clearTimeout(this.globalNetworkTimerId);});r.push(s);}await Promise.race(r),n.log("Watcher closing"),this.closed=!0;}setResponse(t,e){this.archive[t]=e;}requestWillBeSent(t){n.log("requestWillBeSent"),n.log(t);}responseReceived(t){n.log("responseReceived"),n.log(t);}async clientSend(t,e,r){try{return await this.client.send(e,r)}catch(s){return n.log("Client error",t.url,s),this.archive[t.url]={error:s},null}}async requestPaused({requestId:t,request:e,responseStatusCode:r,responseStatusText:s,responseErrorReason:o,responseHeaders:h}){if(!e.method.match(/get/i)){await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}if(r===304){await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}let l=new URL(e.url);this.firstUrl??(this.firstUrl=l);let u=l.origin===this.firstUrl.origin||this.allowedArchiveOrigins.includes(l.origin);if(n.log("requestPaused",l.toString(),r||o?"response":"request",this.firstUrl.toString(),u),this.closed&&n.log("Watcher closed, ignoring"),o){n.log(`Got response error: ${o}`),await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}if(r){if([301,302,307,308].includes(r)){await this.clientSend(e,"Fetch.continueRequest",{requestId:t,interceptResponse:!0});return}let w=await this.clientSend(e,"Fetch.getResponseBody",{requestId:t});if(w===null)return;let{body:d,base64Encoded:m}=w,p=h.find(({name:g})=>g.toLowerCase()==="content-type"),b=l.toString()===this.firstUrl.toString();u&&!b&&(this.archive[e.url]={statusCode:r,statusText:s,body:Buffer.from(d,m?"base64":"utf8"),contentType:p?.value}),await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}await this.clientSend(e,"Fetch.continueRequest",{requestId:t,interceptResponse:!0});}};c(T,"Watcher");var J=c(async({testTitle:i,domSnapshots:t,resourceArchive:e,chromaticStorybookParams:r,pageUrl:s})=>{let o=Object.entries(e).map(([l,u])=>[l,{...u,body:Buffer.from(u.body,"utf8")}]),h=Object.fromEntries(t.map((l,u)=>[`Snapshot #${u+1}`,Buffer.from(JSON.stringify(l))]));await F({title:i,outputDir:"./cypress/downloads/some",pageUrl:s},h,Object.fromEntries(o),r);},"writeArchives"),x=null,L="",C=0,dt=c(async()=>{try{let{webSocketDebuggerUrl:i}=await G.Version({host:L,port:C}),t=await G__default.default({target:i});x||(x=new T(t),await x.watch());}catch(i){console.log("err",i);}return null},"setupNetworkListener"),bt=c(i=>new Promise(t=>{x.idle().then(()=>J({...i,resourceArchive:x.archive}).then(()=>{t(null);}));}),"saveArchives"),St=c((i,t)=>{let e=t.args.find(o=>o.startsWith("--remote-debugging-address="));L=e?e.split("=")[1]:"127.0.0.1";let r=t.args.find(o=>o.startsWith("--remote-debugging-port=")),s="";return r?[,s]=r.split("="):[,s]=process.env.ELECTRON_EXTRA_LAUNCH_ARGS.split(" ").find(h=>h.startsWith("--remote-debugging-port")).split("="),C=parseInt(s,10),t},"onBeforeBrowserLaunch"); | ||
var v=Object.defineProperty;var O=(i,t,e)=>t in i?v(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var c=(i,t)=>v(i,"name",{value:t,configurable:!0});var a=(i,t,e)=>(O(i,typeof t!="symbol"?t+"":t,e),e);var n=process.env.LOG?console:{log:(...i)=>{},warn:(...i)=>{}};var S=class{constructor(t,e,r){a(this,"url");a(this,"response");a(this,"shortenedFileNameLength");a(this,"pageUrl");this.url=new URL(t),this.response=e,this.shortenedFileNameLength=250,this.pageUrl=new URL(r);}originalSrc(){return this.url.toString()}toFileSystemPath(){let t=this.url.pathname;return t=this.preserveExternalDomain(this.url),t=this.ensureNonDirectory(t),t=this.encodeQueryString(t),t=this.truncateFileName(t),t=this.removeSpecialChars(t),t=this.addExtension(t),t}ensureNonDirectory(t){return t.endsWith("/")?`${t}index.html`:t}encodeQueryString(t){let e=this.url.search;if(!e)return t;let r=this.hash(e);return `${t}-${r}`}truncateFileName(t){let e=t.split("/"),r=[];return e.forEach((s,o)=>{let h=s;s.length>this.shortenedFileNameLength&&(h=s.substring(0,this.shortenedFileNameLength),n.log(`Chunk of filename '${s}' is too long. Shortening to '${h}'`)),r.push(h);}),`${t.startsWith("/")?"/":""}${E__default.default.join(...r)}`}removeSpecialChars(t){return t.replace(/[%]/g,"")}addExtension(t){if("error"in this.response||!this.response.contentType)return t;let e=t;if(!E__default.default.extname(e)){let r=___default.default.getExtension(this.response.contentType);r&&(e=`${t}.${r}`);}return e}preserveExternalDomain(t){return t.origin===this.pageUrl.origin?t.pathname:`/${encodeURIComponent(t.host)}/${t.pathname}`}hash(t){return crypto.createHash("md5").update(t).digest("hex")}};c(S,"ArchiveFile");var j=/url\((?!['"]?(?:data):)['"]?([^'")]*)['"]?\)/gi,y=class{constructor(t){a(this,"snapshot");if(Buffer.isBuffer(t)){let e=t.toString("utf-8");this.snapshot=JSON.parse(e);}else this.snapshot=JSON.parse(t);}async mapAssetPaths(t){let e=await this.mapNode(this.snapshot,t);return JSON.stringify(e)}async mapNode(t,e){return t=this.mapNodeAttributes(t,e),t=this.mapTextElement(t,e),"childNodes"in t&&(t.childNodes=await Promise.all(t.childNodes.map(async r=>this.mapNode(r,e)))),t}mapNodeAttributes(t,e){if(t.type===rrwebSnapshot.NodeType.Element){if(t.attributes.src){let r=t.attributes.src;e.has(r)&&(t.attributes.src=e.get(r));}if(t.attributes.style){let r=t.attributes.style,s=this.mapCssUrls(r,e);t.attributes.style=s;}if(t.attributes._cssText){let r=t.attributes._cssText,s=this.mapCssUrls(r,e);t.attributes._cssText=s;}if(t.tagName==="img"&&t.attributes.srcset){let r=t.attributes.srcset,s=this.mapSrcsetUrls(r,e);s&&(t.attributes.src=s,delete t.attributes.srcset,delete t.attributes.sizes);}}return t}mapTextElement(t,e){if(t.type===rrwebSnapshot.NodeType.Text&&t.isStyle&&t.textContent){let r=this.mapCssUrls(t.textContent,e);t.textContent=r;}return t}mapCssUrls(t,e){return t.replace(j,(r,s)=>{let o=r;return e.has(s)&&(o=r.replace(s,e.get(s))),o})}mapSrcsetUrls(t,e){let r=P__default.default.parse(t),s;return r.forEach(o=>{e.has(o.url)&&(s=e.get(o.url));}),s}};c(y,"DOMSnapshot");var N=c(i=>i.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,""),"sanitize");async function F(i,t,e,r){let{title:s,outputDir:o,pageUrl:h}=i,l=E.join(o,"..","chromatic-archives"),u=E.join(l,"archive");await fsExtra.ensureDir(l),n.log(`Writing test results for "${s}"`);let w=new Map;await Promise.all(Object.entries(e).map(async([m,p])=>{if("error"in p)return;let b=new S(m,p,h),g=b.originalSrc(),R=b.toFileSystemPath();g!==R&&w.set(g,R),await fsExtra.outputFile(E.join(u,R),p.body);})),await Promise.all(await Object.entries(t).map(async([m,p])=>{let g=await new y(p).mapAssetPaths(w);await fsExtra.outputFile(E.join(u,`${N(s)}-${N(m)}.snapshot.json`),g);})),await D(E.join(l,`${N(s)}.stories.json`),s,t,r);let d=Object.entries(e).filter(([,m])=>"error"in m);d.length>0&&(n.log(`Encountered ${d.length} errors archiving resources, writing to 'errors.json'`),await fsExtra.outputJson(E.join(u,"errors.json"),{errors:Object.fromEntries(d)}));}c(F,"writeTestResult");async function D(i,t,e,r){n.log(`Writing ${i}`),await fsExtra.outputJson(i,{title:t,stories:Object.keys(e).map(s=>({name:s,parameters:{server:{id:`${N(t)}-${N(s)}.snapshot.json`},chromatic:{...r}}}))});}c(D,"writeStoriesFile");var T=class{constructor(t,e=1e4,r){a(this,"archive",{});a(this,"client");a(this,"globalNetworkTimeoutMs");a(this,"allowedArchiveOrigins");a(this,"firstUrl");a(this,"closed",!1);a(this,"globalNetworkTimerId",null);a(this,"globalNetworkResolver");this.client=t,this.globalNetworkTimeoutMs=e,this.allowedArchiveOrigins=(r||[]).map(s=>`https://${s}`);}async watch(){this.client.on("Network.requestWillBeSent",this.requestWillBeSent.bind(this)),this.client.on("Network.responseReceived",this.responseReceived.bind(this)),this.client.on("Fetch.requestPaused",this.requestPaused.bind(this)),await this.client.send("Fetch.enable");}async idle(t){let r=[new Promise((s,o)=>{this.globalNetworkResolver=s,this.globalNetworkTimerId=setTimeout(()=>{n.warn(`Global timeout of ${this.globalNetworkTimeoutMs}ms reached`),this.globalNetworkResolver();},this.globalNetworkTimeoutMs);})];if(t){let s=t.waitForLoadState("networkidle").finally(()=>{clearTimeout(this.globalNetworkTimerId);});r.push(s);}await Promise.race(r),n.log("Watcher closing"),this.closed=!0;}setResponse(t,e){this.archive[t]=e;}requestWillBeSent(t){n.log("requestWillBeSent"),n.log(t);}responseReceived(t){n.log("responseReceived"),n.log(t);}async clientSend(t,e,r){try{return await this.client.send(e,r)}catch(s){return n.log("Client error",t.url,s),this.archive[t.url]={error:s},null}}async requestPaused({requestId:t,request:e,responseStatusCode:r,responseStatusText:s,responseErrorReason:o,responseHeaders:h}){if(!e.method.match(/get/i)){await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}if(r===304){await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}let l=new URL(e.url);this.firstUrl??(this.firstUrl=l);let u=l.origin===this.firstUrl.origin||this.allowedArchiveOrigins.includes(l.origin);if(n.log("requestPaused",l.toString(),r||o?"response":"request",this.firstUrl.toString(),u),this.closed&&n.log("Watcher closed, ignoring"),o){n.log(`Got response error: ${o}`),await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}if(r){if([301,302,307,308].includes(r)){await this.clientSend(e,"Fetch.continueRequest",{requestId:t,interceptResponse:!0});return}let w=await this.clientSend(e,"Fetch.getResponseBody",{requestId:t});if(w===null)return;let{body:d,base64Encoded:m}=w,p=h.find(({name:g})=>g.toLowerCase()==="content-type"),b=l.toString()===this.firstUrl.toString();u&&!b&&(this.archive[e.url]={statusCode:r,statusText:s,body:Buffer.from(d,m?"base64":"utf8"),contentType:p?.value}),await this.clientSend(e,"Fetch.continueRequest",{requestId:t});return}await this.clientSend(e,"Fetch.continueRequest",{requestId:t,interceptResponse:!0});}};c(T,"Watcher");var J=c(async({testTitle:i,domSnapshots:t,resourceArchive:e,chromaticStorybookParams:r,pageUrl:s})=>{let o=Object.entries(e).map(([l,u])=>[l,{...u,body:Buffer.from(u.body,"utf8")}]),h=Object.fromEntries(t.map((l,u)=>[`Snapshot #${u+1}`,Buffer.from(JSON.stringify(l))]));await F({title:i,outputDir:"./cypress/downloads/some",pageUrl:s},h,Object.fromEntries(o),r);},"writeArchives"),x=null,L="",C=0,dt=c(async()=>{try{let{webSocketDebuggerUrl:i}=await G.Version({host:L,port:C}),t=await G__default.default({target:i});x||(x=new T(t),await x.watch());}catch(i){console.log("err",i);}return null},"setupNetworkListener"),bt=c(i=>new Promise(t=>x.idle().then(()=>J({...i,resourceArchive:x.archive}).then(()=>{t(null);}))),"saveArchives"),St=c((i,t)=>{let e=t.args.find(o=>o.startsWith("--remote-debugging-address="));L=e?e.split("=")[1]:"127.0.0.1";let r=t.args.find(o=>o.startsWith("--remote-debugging-port=")),s="";return r?[,s]=r.split("="):[,s]=process.env.ELECTRON_EXTRA_LAUNCH_ARGS.split(" ").find(h=>h.startsWith("--remote-debugging-port")).split("="),C=parseInt(s,10),t},"onBeforeBrowserLaunch"); | ||
@@ -21,0 +21,0 @@ exports.onBeforeBrowserLaunch = St; |
{ | ||
"name": "@chromaui/test-archiver", | ||
"version": "0.0.54--canary.f648e60.0", | ||
"version": "0.0.54", | ||
"description": "Archive end-to-end tests to be replayed in Storybook and Chromatic", | ||
@@ -5,0 +5,0 @@ "repository": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
213087
0.8%