@tobelabs/chainwright 0.3.1 → 0.3.3

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.
package/dist/cli/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import O from"path";import{fileURLToPath as Te}from"url";import{styleText as d}from"util";import De from"@inquirer/checkbox";import{Command as Re}from"commander";import L from"fs";import H from"path";import{fileURLToPath as ee}from"url";var te=ee(import.meta.url),oe=H.dirname(te),$=H.resolve(oe,"..","..","generated-profile-name.types.ts"),re=e=>e.replace(/(^\w)/g,o=>o.toUpperCase());async function G({walletName:e,profileName:o}){let t=re(e),a=`export type ${t}Profiles = "${o}";`;if(L.existsSync($)){let r=L.readFileSync($,"utf-8"),s=r.match(new RegExp(`export type ${t}Profiles = ("[^"]+"(?:\\s*\\|\\s*"[^"]+")*)`));if(s){let l=s[0];if(!l.includes(`"${o}"`)){let i=l.concat(` | "${o}"`),c=r.replace(l,i);try{L.writeFileSync($,c)}catch(n){console.error("Error updating existing profile name type: ",n)}}}else try{L.appendFileSync($,`
3
- ${a}`,{encoding:"utf-8"})}catch(l){console.error("Error appending new profile name type: ",l)}}else try{L.writeFileSync($,a)}catch(r){console.error("Error writing new profile name type: ",r)}}import ne from"path";import{pathToFileURL as se}from"url";import{styleText as ie}from"util";import{glob as le}from"glob";import ae from"path";function N(e){let o=ae.basename(e),t=o.match(/^([a-z0-9_]+)(?:-[a-z0-9_]+)*\.setup\.(?:ts|js|mjs)$/i);if(!t)throw new Error(`Invalid wallet setup filename: ${o} (expected "<name>[ -variant].setup.{ts,js,mjs}")`);return t[1]}var pe=e=>e.replace(/\\/g,"/"),ce=e=>`${pe(ne.resolve(e))}/**/*.setup.{ts,js,}`;async function U({walletSetupDir:e,selectedWallets:o}){let t=ce(e),a=(await le(t,{dot:!0,absolute:!0,nodir:!0,windowsPathsNoEscape:!0})).sort(),r=o.length===1?o[0]:o,s=["metamask","solflare","petra","meteor","keplr","phantom"];Array.isArray(r)&&r.forEach(n=>{s.includes(n)||console.warn(ie("magenta",`Unsupported wallet: "${n}". Supported wallets are: ${s.join(", ")}`,{validateStream:!1}))});let i=(r==="all"?a:Array.isArray(r)?a.filter(n=>r.some(u=>n.includes(u))):a.filter(n=>n.includes(r))).map(n=>({filePath:n,walletName:N(n)}));if(!i.length||i.length===0)throw new Error([`No wallet setup file found at ${e} for wallet: "${o}".`,'Setup files must use a ".setup.{ts,js,mjs}" extension and include a valid wallet name.','Examples: "metamask.setup.ts", "solflare.setup.ts", "phantom.setup.ts", "metamask-connected.setup.ts"'].join(`
4
- `));return await Promise.all(i.map(async({filePath:n,walletName:u})=>{let m=await import(new URL(se(n)).href).then(S=>S.default),{fn:w,config:y,password:x}=m;return{walletName:u,fileList:i,config:y,walletPassword:x,setupFunction:w}}))}import E from"fs";import R from"path";import{styleText as v}from"util";import{chromium as Fe}from"@playwright/test";import k from"path";import{fileURLToPath as me}from"url";var fe=me(import.meta.url),ue=k.dirname(fe),de=k.resolve(ue,"..","../.wallet-cache");function P(e){return k.resolve(`${de}/${e}`)}import{z as F}from"zod";var we=F.object({id:F.string(),name:F.string()}),ge=F.array(we);async function K(e,o){let t=await e.newPage();await t.goto("chrome://extensions");let a=await t.evaluate("chrome.management.getAll()"),r=ge.parse(a),s=r.find(l=>l.name.toLowerCase()===o.toLowerCase());if(!s)throw new Error([`[GetExtensionId] Extension with name ${o} not found.`,`Available extensions: ${r.map(l=>l.name).join(", ")}`].join(`
5
- `));return await t.close(),s.id}var Y="wallet-setup",V="13.22.0",C="https://github.com/amaify/chainwright/releases/download/v0.1.0/",he=`https://github.com/MetaMask/metamask-extension/releases/download/v${V}/metamask-chrome-${V}.zip`,ye=`${C}solflare-wallet-extension-v2.19.1.zip`,xe=`${C}petra-wallet-extension-v2.4.8.zip`,Se=`${C}phantom-wallet-extension-v26.10.0.zip`,Ee=`${C}meteor-wallet-extension-v0.7.0.zip`,ve=`${C}keplr-wallet-extension-v0.13.3.zip`,T={metamask:{downloadUrl:he,extensionName:"MetaMask"},solflare:{downloadUrl:ye,extensionName:"Solflare Wallet"},petra:{downloadUrl:xe,extensionName:"Petra Aptos Wallet"},phantom:{downloadUrl:Se,extensionName:"Phantom"},meteor:{downloadUrl:Ee,extensionName:"Meteor Wallet"},keplr:{downloadUrl:ve,extensionName:"Keplr"}};import A from"fs";import M from"path";import{styleText as _}from"util";import Ce from"adm-zip";import{createWriteStream as Ae}from"fs";import{Readable as Le}from"stream";import{styleText as B}from"util";import $e from"cli-progress";var Pe=12e4;async function X({url:e,destination:o}){let t=new AbortController,a=setTimeout(()=>t.abort(),Pe),r=await fetch(e,{redirect:"follow",signal:t.signal});r.ok||(console.error(B("redBright",`\u274C Download failed: HTTP ${r.status}`,{validateStream:!1})),t.abort(),process.exit(1));let s=parseInt(r.headers.get("content-length")||"0",10),l=0,i=Le.fromWeb(r.body);try{let c=new $e.SingleBar({format:`Downloading ${B("cyan","{bar}",{validateStream:!1})} {percentage}%`,clearOnComplete:!0,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});c.start(s,0,{speed:"N/A"}),await new Promise((n,u)=>{let p=Ae(o);i.pipe(p),i.on("data",m=>{l+=m.length,c.update(l)}),p.on("error",u),p.on("finish",()=>{c.stop(),n(void 0)})})}catch(c){console.error(B("redBright",`\u274C Download failed: ${c}`,{validateStream:!1})),process.exit(1)}finally{clearTimeout(a)}}var q=!1;async function Z({downloadUrl:e,name:o,force:t}){let a=P(o),s=T[o].extensionName,l=M.join(a,`${o}-extension.zip`),i=M.join(a,`${o}-extension`);if(t&&A.existsSync(a)&&(A.rmSync(a,{recursive:!0}),console.info(_("magenta",`\u{1F9F9} Removed ${s} because of the force flag`,{validateStream:!1}))),A.existsSync(a)||A.mkdir(a,{recursive:!0},n=>{if(n)throw Error("Failed to create cache directory");console.info(`\u2705 ${s} Cache directory created successfully.`)}),A.existsSync(i)?console.info(`\u2705 ${s} Version is downloaded already.`):(console.info(_("cyanBright",`\u{1F4E5} Downloading ${s} extension...`,{validateStream:!1})),await X({url:e,destination:l}),console.info(_("green",`\u2705 ${o.toUpperCase()} Extension downloaded successfully.`,{validateStream:!1}))),!A.existsSync(i))console.info("\u{1F4E6} Extracting extension..."),new Ce(l).extractAllTo(i,!0),console.info(`\u2705 ${s} Extension extracted successfully.`);else{if(q)return console.info(_("magentaBright",`Using the cached ${s} extension for profile creation.`,{validateStream:!1})),i;console.info(_("yellow",`\u26A0\uFE0F Skipping ${s} cache creation: Cache already exists at ${i}. Use --force to overwrite.`,{validateStream:!1}))}let c=M.join(i,"manifest.json");if(!A.existsSync(c))throw new Error(`\u274C (${s}) Invalid extension: manifest.json not found`);return q=!0,i}import{styleText as _e}from"util";function j(e){return new Promise(o=>setTimeout(o,e))}var D=20,We=6e3,J=4e3;async function be(e){return e.pages().find(a=>{try{return a.url().startsWith("chrome-extension://")}catch(r){return console.error("[WaitForExtensionOnLoadPage] Error checking page URL:",r),!1}})}async function Q(e,o){let t=0,a=null;if(o==="meteor")return await e.newPage();for(console.info(`Waiting ${J}ms for browser to initialize...`),await j(J);t<=D;)try{if(console.info(`Looking for extension page (attempt ${t+1}/${D})...`),t===D)throw new Error("Extension page not found after maximum retries");let r=await be(e);if(r){console.info(`Found extension page after ${t+1} polling attempts`),a=r;break}r||(t++,console.info(`Extension page not found, retrying (${t}/${D})...`),await j(We))}catch(r){throw console.error("Error waiting for extension page:",r instanceof Error?r.message:"Unknown error"),new Error(`Extension failed to load properly after ${t} attempts!`)}return console.info(_e("greenBright","\u2705 Extension page is properly loaded and ready",{validateStream:!1})),a}async function z({walletName:e,force:o,config:t,fileList:a,walletPassword:r,setupFunction:s}){let{downloadUrl:l,extensionName:i}=T[e],c=P(e),n=t?.profileName,u=n?`${n}`:"wallet-data",p=R.resolve(c,"extension-id.txt"),m=R.resolve(c,"extension-path.txt"),w=R.resolve(c,"password.txt"),y=R.resolve(c,u),x=await Z({downloadUrl:l,name:e,force:o}),S=[`--disable-extensions-except=${x}`,`--load-extension=${x}`];if(E.existsSync(y)&&a.length>1)throw Error([v("yellowBright",[`\u274C ${u} directory already exists for ${i}.`,`
6
- To setup another wallet profile, add a profile name to the wallet setup function.`,v(["blueBright","italic"],'Example: defineWalletSetup(async ({ context, walletPage }) => { ... }, { profileName: "profile-name" });'),v("italic","You can also use the --force flag to overwrite the existing cache.")].join(`
2
+ import j from"path";import{styleText as h}from"util";import Te from"@inquirer/checkbox";import{Command as De}from"commander";import L from"fs";import z from"path";import{fileURLToPath as ee}from"url";var te=ee(import.meta.url),oe=z.dirname(te),$=z.resolve(oe,"..","..","generated-profile-name.types.ts"),re=e=>e.replace(/(^\w)/g,o=>o.toUpperCase());async function H({walletName:e,profileName:o}){let t=re(e),a=`export type ${t}Profiles = "${o}";`;if(L.existsSync($)){let r=L.readFileSync($,"utf-8"),n=r.match(new RegExp(`export type ${t}Profiles = ("[^"]+"(?:\\s*\\|\\s*"[^"]+")*)`));if(n){let l=n[0];if(!l.includes(`"${o}"`)){let s=l.concat(` | "${o}"`),c=r.replace(l,s);try{L.writeFileSync($,c)}catch(i){console.error("Error updating existing profile name type: ",i)}}}else try{L.appendFileSync($,`
3
+ ${a}`,{encoding:"utf-8"})}catch(l){console.error("Error appending new profile name type: ",l)}}else try{L.writeFileSync($,a)}catch(r){console.error("Error writing new profile name type: ",r)}}import ne from"path";import{pathToFileURL as se}from"url";import{styleText as ie}from"util";import{glob as le}from"glob";import ae from"path";function O(e){let o=ae.basename(e),t=o.match(/^([a-z0-9_]+)(?:-[a-z0-9_]+)*\.setup\.(?:ts|js|mjs)$/i);if(!t)throw new Error(`Invalid wallet setup filename: ${o} (expected "<name>[ -variant].setup.{ts,js,mjs}")`);return t[1]}var pe=e=>e.replace(/\\/g,"/"),ce=e=>`${pe(ne.resolve(e))}/**/*.setup.{ts,js,}`;async function I({walletSetupDir:e,selectedWallets:o}){let t=ce(e),a=(await le(t,{dot:!0,absolute:!0,nodir:!0,windowsPathsNoEscape:!0})).sort(),r=o.length===1?o[0]:o,n=["metamask","solflare","petra","meteor","keplr","phantom"];Array.isArray(r)&&r.forEach(i=>{n.includes(i)||console.warn(ie("magenta",`Unsupported wallet: "${i}". Supported wallets are: ${n.join(", ")}`,{validateStream:!1}))});let s=(r==="all"?a:Array.isArray(r)?a.filter(i=>r.some(p=>i.includes(p))):a.filter(i=>i.includes(r))).map(i=>({filePath:i,walletName:O(i)}));if(!s.length||s.length===0)throw new Error([`No wallet setup file found at ${e} for wallet: "${o}".`,'Setup files must use a ".setup.{ts,js,mjs}" extension and include a valid wallet name.','Examples: "metamask.setup.ts", "solflare.setup.ts", "phantom.setup.ts", "metamask-connected.setup.ts"'].join(`
4
+ `));return await Promise.all(s.map(async({filePath:i,walletName:p})=>{let f=await import(new URL(se(i)).href).then(d=>d.default),{fn:E,config:y,password:u}=f;return{walletName:p,fileList:s,config:y,walletPassword:u,setupFunction:E}}))}import x from"fs";import R from"path";import{styleText as S}from"util";import{chromium as Fe}from"@playwright/test";import N from"path";import{fileURLToPath as me}from"url";var fe=me(import.meta.url),ue=N.dirname(fe),de=N.resolve(ue,"..","../.wallet-cache");function P(e){return N.resolve(`${de}/${e}`)}import{z as F}from"zod";var we=F.object({id:F.string(),name:F.string()}),ge=F.array(we);async function G(e,o){let t=await e.newPage();await t.goto("chrome://extensions");let a=await t.evaluate("chrome.management.getAll()"),r=ge.parse(a),n=r.find(l=>l.name.toLowerCase()===o.toLowerCase());if(!n)throw new Error([`[GetExtensionId] Extension with name ${o} not found.`,`Available extensions: ${r.map(l=>l.name).join(", ")}`].join(`
5
+ `));return await t.close(),n.id}var V="wallet-setup",K="13.22.0",C="https://github.com/amaify/chainwright/releases/download/v0.1.0/",he=`https://github.com/MetaMask/metamask-extension/releases/download/v${K}/metamask-chrome-${K}.zip`,ye=`${C}solflare-wallet-extension-v2.19.1.zip`,xe=`${C}petra-wallet-extension-v2.4.8.zip`,Se=`${C}phantom-wallet-extension-v26.10.0.zip`,Ee=`${C}meteor-wallet-extension-v0.7.0.zip`,ve=`${C}keplr-wallet-extension-v0.13.3.zip`,T={metamask:{downloadUrl:he,extensionName:"MetaMask"},solflare:{downloadUrl:ye,extensionName:"Solflare Wallet"},petra:{downloadUrl:xe,extensionName:"Petra Aptos Wallet"},phantom:{downloadUrl:Se,extensionName:"Phantom"},meteor:{downloadUrl:Ee,extensionName:"Meteor Wallet"},keplr:{downloadUrl:ve,extensionName:"Keplr"}};import A from"fs";import U from"path";import{styleText as W}from"util";import Ce from"adm-zip";import{createWriteStream as Ae}from"fs";import{Readable as Le}from"stream";import{styleText as k}from"util";import $e from"cli-progress";var Pe=12e4;async function Y({url:e,destination:o}){let t=new AbortController,a=setTimeout(()=>t.abort(),Pe),r=await fetch(e,{redirect:"follow",signal:t.signal});r.ok||(console.error(k("redBright",`\u274C Download failed: HTTP ${r.status}`,{validateStream:!1})),t.abort(),process.exit(1));let n=parseInt(r.headers.get("content-length")||"0",10),l=0,s=Le.fromWeb(r.body);try{let c=new $e.SingleBar({format:`Downloading ${k("cyan","{bar}",{validateStream:!1})} {percentage}%`,clearOnComplete:!0,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});c.start(n,0,{speed:"N/A"}),await new Promise((i,p)=>{let m=Ae(o);s.pipe(m),s.on("data",f=>{l+=f.length,c.update(l)}),m.on("error",p),m.on("finish",()=>{c.stop(),i(void 0)})})}catch(c){console.error(k("redBright",`\u274C Download failed: ${c}`,{validateStream:!1})),process.exit(1)}finally{clearTimeout(a)}}var X=!1;async function q({downloadUrl:e,name:o,force:t}){let a=P(o),n=T[o].extensionName,l=U.join(a,`${o}-extension.zip`),s=U.join(a,`${o}-extension`);if(t&&A.existsSync(a)&&(A.rmSync(a,{recursive:!0}),console.info(W("magenta",`\u{1F9F9} Removed ${n} because of the force flag`,{validateStream:!1}))),A.existsSync(a)||A.mkdir(a,{recursive:!0},i=>{if(i)throw Error("Failed to create cache directory");console.info(`\u2705 ${n} Cache directory created successfully.`)}),A.existsSync(s)?console.info(`\u2705 ${n} Version is downloaded already.`):(console.info(W("cyanBright",`\u{1F4E5} Downloading ${n} extension...`,{validateStream:!1})),await Y({url:e,destination:l}),console.info(W("green",`\u2705 ${o.toUpperCase()} Extension downloaded successfully.`,{validateStream:!1}))),!A.existsSync(s))console.info("\u{1F4E6} Extracting extension..."),new Ce(l).extractAllTo(s,!0),console.info(`\u2705 ${n} Extension extracted successfully.`);else{if(X)return console.info(W("magentaBright",`Using the cached ${n} extension for profile creation.`,{validateStream:!1})),s;console.info(W("yellow",`\u26A0\uFE0F Skipping ${n} cache creation: Cache already exists at ${s}. Use --force to overwrite.`,{validateStream:!1}))}let c=U.join(s,"manifest.json");if(!A.existsSync(c))throw new Error(`\u274C (${n}) Invalid extension: manifest.json not found`);return X=!0,s}import{styleText as We}from"util";function B(e){return new Promise(o=>setTimeout(o,e))}var D=20,_e=6e3,Z=4e3;async function be(e){return e.pages().find(a=>{try{return a.url().startsWith("chrome-extension://")}catch(r){return console.error("[WaitForExtensionOnLoadPage] Error checking page URL:",r),!1}})}async function J(e,o){let t=0,a=null;if(o==="meteor")return await e.newPage();for(console.info(`Waiting ${Z}ms for browser to initialize...`),await B(Z);t<=D;)try{if(console.info(`Looking for extension page (attempt ${t+1}/${D})...`),t===D)throw new Error("Extension page not found after maximum retries");let r=await be(e);if(r){console.info(`Found extension page after ${t+1} polling attempts`),a=r;break}r||(t++,console.info(`Extension page not found, retrying (${t}/${D})...`),await B(_e))}catch(r){throw console.error("Error waiting for extension page:",r instanceof Error?r.message:"Unknown error"),new Error(`Extension failed to load properly after ${t} attempts!`)}return console.info(We("greenBright","\u2705 Extension page is properly loaded and ready",{validateStream:!1})),a}async function M({walletName:e,force:o,config:t,fileList:a,walletPassword:r,setupFunction:n}){let{downloadUrl:l,extensionName:s}=T[e],c=P(e),i=t?.profileName,p=i?`${i}`:"wallet-data",m=R.resolve(c,"extension-id.txt"),f=R.resolve(c,"extension-path.txt"),E=R.resolve(c,"password.txt"),y=R.resolve(c,p),u=await q({downloadUrl:l,name:e,force:o}),d=[`--disable-extensions-except=${u}`,`--load-extension=${u}`];if(x.existsSync(y)&&a.length>1)throw Error([S("yellowBright",[`\u274C ${p} directory already exists for ${s}.`,`
6
+ To setup another wallet profile, add a profile name to the wallet setup function.`,S(["blueBright","italic"],'Example: defineWalletSetup(async ({ context, walletPage }) => { ... }, { profileName: "profile-name" });'),S("italic","You can also use the --force flag to overwrite the existing cache.")].join(`
7
7
  `),{validateStream:!1})].join(`
8
- `));if(E.existsSync(y))return;let f=await Fe.launchPersistentContext(y,{headless:!1,args:S,slowMo:t?.slowMo??0});console.info(v("magentaBright",`\u{1F9E9}\u{1F680} Starting Chrome extension for ${e.toUpperCase()}`,{validateStream:!1}));let I=await Q(f,e);if(!E.existsSync(p)&&!E.existsSync(m)){let b=await K(f,i);console.info(v("magentaBright",`\u{1F194} ${i} extension ID: ${b}`,{validateStream:!1})),E.writeFileSync(p,b,"utf-8"),console.info(v("cyanBright",`\u{1F4BE} Saved extension ID to: ${p}`,{validateStream:!1})),E.writeFileSync(m,x,"utf-8"),console.info(v("blueBright",`\u{1F4C1} Saved extension Path to: ${m}`,{validateStream:!1})),E.writeFileSync(w,r,"utf-8"),console.info(v("yellowBright",`\u{1F511} Saved ${e} password to: ${w}`,{validateStream:!1}))}try{await s({context:f,walletPage:I})}catch(b){await f.close(),E.rmSync(c,{force:!0,recursive:!0}),console.error("Error setting up wallet: ",b.message)}await f.close()}var Oe=Te(import.meta.url),Ie=O.dirname(Oe),Ne=O.join(Ie,"..","tests",Y),W=2;async function Ue(){let e=new Re;e.name(d("yellow","Chainwright")).description(d("green","A CLI tool for setting up wallet cache for E2E testing of web3 applications")).version(d("blue","0.0.0")),e.command("chainwright").argument("[dir]","Directory containing the wallet setup functions",O.resolve(Ne)).option("--headless","Build cache in the headless browser mode. Alternatively, set the `HEADLESS` env variable to `true`",!1).option("-f, --force","Force the creation of cache even if it already exists",!1).option("-a, --all","Setup all wallets","all").option("--kp, --keplr","Setup Keplr","keplr").option("-m, --metamask","Setup MetaMask","metamask").option("--mt, --meteor","Setup Meteor","meteor").option("--pt, --petra","Setup Petra","petra").option("--ph, --phantom","Setup Phantom","phantom").option("-s, --solflare","Setup Solflare","solflare").option("--wls, --wallets <wallets...>","Specify wallets to setup (e.g., --wallets keplr metamask)").action(async(o,t)=>{let a=["all","metamask","solflare","petra","meteor","keplr","phantom"],r=Object.keys(t).filter(p=>a.includes(p)?t[p]===!0:!1),s=r.length>0,l=t.wallets,i=l||(s?r:await De({message:"Select the wallet you want to setup",choices:[{name:"All",value:"all"},{name:"Keplr",value:"keplr"},{name:"MetaMask",value:"metamask"},{name:"Meteor",value:"meteor"},{name:"Petra",value:"petra"},{name:"Phantom",value:"phantom"},{name:"Solflare",value:"solflare"}],validate:p=>{let m=p.map(w=>w.value);return m.includes("all")&&m.length>1?'Select either "All" or specific wallets, not both.':!0},pageSize:10})),c=o,n=e.commands[0]?.args??[];n[0]&&(c=O.resolve(process.cwd(),n[0])),t.headless&&(process.env.HEADLESS=!0);let u=await U({walletSetupDir:c,selectedWallets:i});for(let{walletName:p,config:m,walletPassword:w,setupFunction:y,fileList:x}of u)try{console.info(d("cyanBright",`
9
- Setting up cache for ${p}...`,{validateStream:!1})),await z({walletName:p,config:m,setupFunction:y,fileList:x,force:t.force,walletPassword:w}),m.profileName&&await G({walletName:p,profileName:m.profileName})}catch(S){if(S.message.includes("directory already exists")&&console.warn(S.message),!S.message.includes("directory already exists")){console.error(d("redBright",`
10
- \u274C Failed to setup cache for ${p}: ${S.message}`,{validateStream:!1}));let f=0;for(;W>f;){console.info(`${d("yellow",`Retry Attempt ${f+1} of ${W} for ${p}...`,{validateStream:!1})}`),console.info(d("yellow","Retrying wallet setup...",{validateStream:!1}));try{await z({walletName:p,config:m,setupFunction:y,fileList:x,force:t.force,walletPassword:w});break}catch(I){f+1<W&&console.error(d("redBright",`
11
- \u274C Attempt ${f+1} failed! Retrying...`,{validateStream:!1})),f++,f===W&&console.error(d("redBright",`\u274C Failed to setup cache after ${W} attempts for ${p}: ${I.message}`,{validateStream:!1}))}}}}}),await e.parseAsync(process.argv)}Ue().catch(e=>console.error(d("redBright",`Failed to run the CLI: ${e.message})`,{validateStream:!1})));export{Ue as clientEntry};
8
+ `));if(x.existsSync(y))return;let v=await Fe.launchPersistentContext(y,{headless:!1,args:d,slowMo:t?.slowMo??0});console.info(S("magentaBright",`\u{1F9E9}\u{1F680} Starting Chrome extension for ${e.toUpperCase()}`,{validateStream:!1}));let Q=await J(v,e);if(!x.existsSync(m)&&!x.existsSync(f)){let b=await G(v,s);console.info(S("magentaBright",`\u{1F194} ${s} extension ID: ${b}`,{validateStream:!1})),x.writeFileSync(m,b,"utf-8"),console.info(S("cyanBright",`\u{1F4BE} Saved extension ID to: ${m}`,{validateStream:!1})),x.writeFileSync(f,u,"utf-8"),console.info(S("blueBright",`\u{1F4C1} Saved extension Path to: ${f}`,{validateStream:!1})),x.writeFileSync(E,r,"utf-8"),console.info(S("yellowBright",`\u{1F511} Saved ${e} password to: ${E}`,{validateStream:!1}))}try{await n({context:v,walletPage:Q})}catch(b){await v.close(),x.rmSync(c,{force:!0,recursive:!0}),console.error("Error setting up wallet: ",b.message)}await v.close()}var Re=j.resolve(process.cwd(),"tests",V),_=2;async function Oe(){let e=new De;e.name(h("yellow","Chainwright")).description(h("green","A CLI tool for setting up wallet cache for E2E testing of web3 applications")).version(h("blue","0.0.0")),e.argument("[dir]","Directory containing the wallet setup functions",j.resolve(Re)).option("--headless","Build cache in the headless browser mode. Alternatively, set the `HEADLESS` env variable to `true`",!1).option("-f, --force","Force the creation of cache even if it already exists",!1).option("-a, --all","Setup all wallets","all").option("--kp, --keplr","Setup Keplr","keplr").option("-m, --metamask","Setup MetaMask","metamask").option("--mt, --meteor","Setup Meteor","meteor").option("--pt, --petra","Setup Petra","petra").option("--ph, --phantom","Setup Phantom","phantom").option("-s, --solflare","Setup Solflare","solflare").option("--wls, --wallets <wallets...>","Specify wallets to setup (e.g., --wallets keplr metamask)").action(async(o,t)=>{let a=["all","metamask","solflare","petra","meteor","keplr","phantom"],r=Object.keys(t).filter(p=>a.includes(p)?t[p]===!0:!1),n=r.length>0,l=t.wallets,s=l||(n?r:await Te({message:"Select the wallet you want to setup",choices:[{name:"All",value:"all"},{name:"Keplr",value:"keplr"},{name:"MetaMask",value:"metamask"},{name:"Meteor",value:"meteor"},{name:"Petra",value:"petra"},{name:"Phantom",value:"phantom"},{name:"Solflare",value:"solflare"}],validate:p=>{let m=p.map(f=>f.value);return m.includes("all")&&m.length>1?'Select either "All" or specific wallets, not both.':!0},pageSize:10})),c=j.resolve(process.cwd(),o);t.headless&&(process.env.HEADLESS=!0);let i=await I({walletSetupDir:c,selectedWallets:s});for(let{walletName:p,config:m,walletPassword:f,setupFunction:E,fileList:y}of i)try{console.info(h("cyanBright",`
9
+ Setting up cache for ${p}...`,{validateStream:!1})),await M({walletName:p,config:m,setupFunction:E,fileList:y,force:t.force,walletPassword:f}),m.profileName&&await H({walletName:p,profileName:m.profileName})}catch(u){if(u.message.includes("directory already exists")&&console.warn(u.message),!u.message.includes("directory already exists")){console.error(h("redBright",`
10
+ \u274C Failed to setup cache for ${p}: ${u.message}`,{validateStream:!1}));let d=0;for(;_>d;){console.info(`${h("yellow",`Retry Attempt ${d+1} of ${_} for ${p}...`,{validateStream:!1})}`),console.info(h("yellow","Retrying wallet setup...",{validateStream:!1}));try{await M({walletName:p,config:m,setupFunction:E,fileList:y,force:t.force,walletPassword:f});break}catch(v){d+1<_&&console.error(h("redBright",`
11
+ \u274C Attempt ${d+1} failed! Retrying...`,{validateStream:!1})),d++,d===_&&console.error(h("redBright",`\u274C Failed to setup cache after ${_} attempts for ${p}: ${v.message}`,{validateStream:!1}))}}}}}),await e.parseAsync(process.argv)}Oe().catch(e=>console.error(h("redBright",`Failed to run the CLI: ${e.message})`,{validateStream:!1})));export{Oe as clientEntry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tobelabs/chainwright",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "An end-to-end testing framework built on top of Playwright for Web3 wallet interactions",
5
5
  "type": "module",
6
6
  "license": "MIT",